This commit is contained in:
Henrique Dias
2016-07-05 17:49:15 +01:00
parent 37c77a3cee
commit 7743b56f05
2 changed files with 5 additions and 6 deletions

View File

@@ -6,8 +6,9 @@ import (
"time"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
const (
tokenSize = 80
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
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
@@ -21,12 +22,11 @@ func (c Config) CheckToken(r *http.Request) bool {
// GenerateToken geneerates a new token
func (c *Config) GenerateToken() {
n := rand.Intn(80)
src := rand.NewSource(time.Now().UnixNano())
b := make([]byte, n)
b := make([]byte, tokenSize)
// 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
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
for i, cache, remain := tokenSize-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}