diff --git a/pkg/captcha/db.go b/pkg/captcha/db.go index 758125e..b9fa5e7 100644 --- a/pkg/captcha/db.go +++ b/pkg/captcha/db.go @@ -9,9 +9,21 @@ import ( "time" ) +var expiredScanInterval = 60 * time.Second + type ID string -var expiredScanInterval = 60 * time.Second +// NewID generates an ID as a sha256 hash of additionalData, current time +// and answer encoded with base64 in raw URL variant. +func NewID(additionalData string, answer Answer) ID { + idHash := sha256.New() + + idHash.Write([]byte(additionalData)) + idHash.Write([]byte(strconv.FormatInt(time.Now().UnixMicro(), 16))) + idHash.Write([]byte(answer)) + + return ID(base64.RawURLEncoding.EncodeToString(idHash.Sum(nil))) +} type ICaptchaDB interface { New(data string) (ICaptcha, ID) @@ -54,13 +66,7 @@ func (cdb *CaptchaDB) SetExpiry(expire time.Duration) { // `data` string is an additional random data used to generate an ID, // e.g. IP-address. func (cdb *CaptchaDB) New(data string, captcha ICaptcha) (ICaptcha, ID) { - idHash := sha256.New() - - idHash.Write([]byte(data)) - idHash.Write([]byte(strconv.FormatInt(time.Now().UnixMicro(), 16))) - idHash.Write([]byte(captcha.GetAnswer())) - - id := ID(base64.RawURLEncoding.EncodeToString(idHash.Sum(nil))) + id := NewID(data, captcha.GetAnswer()) cdb.mut.Lock() defer cdb.mut.Unlock()