tkcashgame_v4/pkg/captcha/captcha.go

78 lines
1.8 KiB
Go
Raw Normal View History

2025-10-22 10:01:11 +00:00
package captcha
import (
"math/rand"
"time"
"github.com/mojocn/base64Captcha"
)
func init() {
//init rand seed
rand.Seed(time.Now().UnixNano())
}
// Captcha captcha basic information.
type Captcha struct {
Driver base64Captcha.Driver
Store base64Captcha.Store
Config *configJsonBody
}
// NewCaptcha creates a captcha instance from driver and store
func NewCaptcha() *Captcha {
config := &configJsonBody{
DriverAudio: audioConfig(),
DriverDigit: digitConfig(),
DriverString: stringConfig(),
DriverMath: mathConfig(),
DriverChinese: chineseConfig(),
}
driver := config.DriverMath
return &Captcha{
Driver: driver,
Store: base64Captcha.DefaultMemStore,
Config: config,
}
}
func (c *Captcha) SetDriver(captchaType string) *Captcha {
var driver base64Captcha.Driver
//create base64 encoding captcha
switch captchaType {
case "audio":
driver = c.Config.DriverAudio
case "string":
driver = c.Config.DriverString
case "math":
driver = c.Config.DriverMath
case "chinese":
driver = c.Config.DriverChinese
default:
driver = c.Config.DriverDigit
}
c.Driver = driver
return c
}
// Generate generates a random id, base64 image string or an error if any
func (c *Captcha) Generate() (id, b64s string, err error) {
id, content, answer := c.Driver.GenerateIdQuestionAnswer()
item, err := c.Driver.DrawCaptcha(content)
if err != nil {
return "", "", err
}
c.Store.Set(id, answer)
b64s = item.EncodeB64string()
return
}
// Verify by a given id key and remove the captcha value in store,
// return boolean value.
// if you has multiple captcha instances which share a same store.
// You may want to call `store.Verify` method instead.
func (c *Captcha) Verify(id, answer string, clear bool) (match bool) {
match = c.Store.Get(id, clear) == answer
return
}