43 lines
917 B
Go
43 lines
917 B
Go
package captcha
|
||
|
||
import (
|
||
"context"
|
||
"time"
|
||
|
||
"github.com/redis/go-redis/v9"
|
||
)
|
||
|
||
const codeKeyPrefix = "captcha:code:"
|
||
|
||
// redisStore 实现 base64Captcha.Store,将验证码答案存入 Redis。
|
||
type redisStore struct {
|
||
client *redis.Client
|
||
ttl time.Duration
|
||
}
|
||
|
||
func newRedisStore(client *redis.Client, ttl time.Duration) *redisStore {
|
||
return &redisStore{client: client, ttl: ttl}
|
||
}
|
||
|
||
func (s *redisStore) Set(id string, value string) error {
|
||
return s.client.Set(context.Background(), codeKeyPrefix+id, value, s.ttl).Err()
|
||
}
|
||
|
||
func (s *redisStore) Get(id string, clear bool) string {
|
||
ctx := context.Background()
|
||
key := codeKeyPrefix + id
|
||
val, err := s.client.Get(ctx, key).Result()
|
||
if err != nil {
|
||
return ""
|
||
}
|
||
if clear {
|
||
_ = s.client.Del(ctx, key).Err()
|
||
}
|
||
return val
|
||
}
|
||
|
||
func (s *redisStore) Verify(id, answer string, clear bool) bool {
|
||
val := s.Get(id, clear)
|
||
return val != "" && val == answer
|
||
}
|