123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package captcha
- import (
- "git.bvbej.com/bvbej/base-golang/pkg/cache"
- "github.com/mojocn/base64Captcha"
- "go.uber.org/zap"
- "strings"
- "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 {
- return err
- }
- return nil
- }
- func (s *store) Get(id string, clear bool) string {
- value, err := s.cache.Get(RedisKeyPrefixCaptcha + id)
- if err == nil && clear {
- s.cache.Del(RedisKeyPrefixCaptcha + id)
- }
- return value
- }
- func (s *store) Verify(id, answer string, clear bool) bool {
- value := s.Get(id, clear)
- if value == "" || answer == "" {
- return false
- }
- return strings.ToLower(value) == strings.ToLower(answer)
- }
- func NewStore(cache cache.Repo, ttl time.Duration) base64Captcha.Store {
- return &store{
- cache: cache,
- ttl: ttl,
- }
- }
- 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,
- NoiseCount: length * 2,
- ShowLineOptions: base64Captcha.OptionShowHollowLine,
- Length: length,
- Source: "ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz0123456789",
- }
- return &captcha{
- conf: conf,
- store: store,
- }
- }
- func (c *captcha) Generate() (id, b64s string, err error) {
- driver := c.conf.ConvertFonts()
- newCaptcha := base64Captcha.NewCaptcha(driver, c.store)
- return newCaptcha.Generate()
- }
- func (c *captcha) Verify(id, value string) bool {
- return c.store.Verify(id, value, true)
- }
|