filebrowser/config/secure.go

43 lines
1.2 KiB
Go
Raw Normal View History

2016-07-05 16:46:45 +00:00
package config
import (
"math/rand"
"net/http"
"time"
)
const (
2016-07-05 16:49:15 +00:00
tokenSize = 80
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
2016-07-05 16:46:45 +00:00
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
// CheckToken checs if current token is the same as the one used in the request
func (c Config) CheckToken(r *http.Request) bool {
token := r.Header.Get("Token")
return c.Token == token
}
// GenerateToken geneerates a new token
func (c *Config) GenerateToken() {
src := rand.NewSource(time.Now().UnixNano())
2016-07-05 16:49:15 +00:00
b := make([]byte, tokenSize)
2016-07-05 16:46:45 +00:00
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
// future reference: http://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang
2016-07-05 16:49:15 +00:00
for i, cache, remain := tokenSize-1, src.Int63(), letterIdxMax; i >= 0; {
2016-07-05 16:46:45 +00:00
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
c.Token = string(b)
}