12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- package captcha
- import (
- "fmt"
- "git.bvbej.com/bvbej/base-golang/pkg/cache"
- "github.com/mojocn/base64Captcha"
- "go.uber.org/zap"
- "time"
- )
- const RedisKeyPrefixCaptcha = "captcha:base64:"
- var _ base64Captcha.Store = (*store)(nil)
- type store struct {
- cache cache.Repo
- ttl time.Duration
- logger *zap.Logger
- }
- func (s *store) Set(id string, value string) error {
- err := s.cache.Set(RedisKeyPrefixCaptcha+id, value, s.ttl)
- if err != nil {
- s.logger.Error(fmt.Sprintf("hu缓存Captcha信息错误[%s]", err))
- return err
- }
- return nil
- }
- func (s *store) Get(id string, clear bool) string {
- value, err := s.cache.Get(RedisKeyPrefixCaptcha + id)
- if err != nil {
- s.logger.Error(fmt.Sprintf("获取Captcha信息错误[%s]", err))
- }
- return value
- }
- func (s *store) Verify(id, answer string, clear bool) bool {
- return s.Get(id, clear) == answer
- }
- func NewStore(cache cache.Repo, ttl time.Duration, logger *zap.Logger) base64Captcha.Store {
- return &store{
- cache: cache,
- ttl: ttl,
- logger: logger,
- }
- }
- var _ Captcha = (*captcha)(nil)
- type Captcha interface {
- Generate() (id, b64s string, err error)
- Verify(id, value string) bool
- }
- type captcha struct {
- conf *base64Captcha.DriverString
- store base64Captcha.Store
- }
- func NewCaptcha(store base64Captcha.Store, height, width, length int) Captcha {
- conf := &base64Captcha.DriverString{
- Height: height,
- Width: width,
- Length: length,
- }
- return &captcha{
- conf: conf,
- store: store,
- }
- }
- func (c *captcha) Generate() (id, b64s string, err error) {
- driver := base64Captcha.DriverString.ConvertFonts(c.conf)
- newCaptcha := base64Captcha.NewCaptcha(driver, c.store)
- return newCaptcha.Generate()
- }
- func (c *captcha) Verify(id, value string) bool {
- return c.store.Verify(id, value, true)
- }
|