From b65f3be236f4d624a7bb4ed22d17a8d3f498804c Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Mon, 27 Jun 2022 01:02:24 +0400 Subject: [PATCH] ID generating moved off to a separate function NewID(). --- pkg/captcha/db.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) 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()