mirror of
https://gitee.com/shikong-sk/gofiber-study
synced 2025-02-24 15:52:15 +08:00
51 lines
1.0 KiB
Go
51 lines
1.0 KiB
Go
package global
|
|
|
|
import (
|
|
"context"
|
|
"github.com/go-redis/redis/v8"
|
|
"github.com/mojocn/base64Captcha"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
var Captcha *base64Captcha.Captcha
|
|
|
|
const (
|
|
CaptchaPrefix = "captcha"
|
|
CaptchaSeparator = ":"
|
|
)
|
|
|
|
type CaptchaStore struct {
|
|
Ctx context.Context
|
|
Store *redis.Client
|
|
}
|
|
|
|
func NewCaptchaStore(redis *redis.Client) *CaptchaStore {
|
|
return &CaptchaStore{
|
|
context.Background(),
|
|
redis,
|
|
}
|
|
}
|
|
|
|
func (c *CaptchaStore) Set(id string, value string) error {
|
|
return c.Store.SetEX(c.Ctx, CaptchaPrefix+CaptchaSeparator+id, value, time.Duration(Config.Captcha.Expire)*time.Second).Err()
|
|
}
|
|
|
|
func (c *CaptchaStore) Get(id string, clear bool) string {
|
|
str, err := c.Store.Get(c.Ctx, CaptchaPrefix+CaptchaSeparator+id).Result()
|
|
if clear {
|
|
c.Store.Del(c.Ctx, CaptchaPrefix+CaptchaSeparator+id)
|
|
}
|
|
|
|
if err != nil {
|
|
return ""
|
|
} else {
|
|
return str
|
|
}
|
|
}
|
|
|
|
func (c *CaptchaStore) Verify(id, answer string, clear bool) (match bool) {
|
|
match = strings.EqualFold(c.Get(id, clear), strings.TrimSpace(answer))
|
|
return
|
|
}
|