增加图形验证码的功能
This commit is contained in:
42
captcha/redis_store.go
Normal file
42
captcha/redis_store.go
Normal file
@@ -0,0 +1,42 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user