ID generating moved off to a separate function NewID().

This commit is contained in:
Alexander Andreev 2022-06-27 01:02:24 +04:00
parent 6307433ea0
commit b65f3be236
Signed by: Arav
GPG Key ID: 0388CC8FAA51063F

View File

@ -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()