You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.6 KiB

2 years ago
package captcha
import (
2 years ago
"fmt"
"git.diulo.com/mogfee/protoc-gen-kit/pkg/base64Captcha"
"github.com/go-redis/redis"
"time"
2 years ago
)
2 years ago
var DefaultConfig = base64Captcha.DriverString{
Height: 80,
Width: 240,
NoiseCount: 20,
ShowLineOptions: 100,
Length: 5,
BgColor: nil,
Source: "1234567890qwertyuioplkjhgfdsazxcvbnm",
Fonts: []string{"wqy-microhei.ttc", "chromohv.ttf", "actionj.ttf", "RitaSmith.ttf"},
}
2 years ago
var DefaultStore = base64Captcha.DefaultMemStore
2 years ago
2 years ago
func SetStore(store base64Captcha.Store) {
DefaultStore = store
}
func Generate() (id, b64s string, err error) {
return base64Captcha.NewCaptcha(&DefaultConfig, DefaultStore).Generate()
2 years ago
}
type redisStore struct {
2 years ago
redis *redis.Client
2 years ago
}
2 years ago
func NewRedisStore(redis *redis.Client) *redisStore {
2 years ago
return &redisStore{
2 years ago
redis: redis,
2 years ago
}
}
func (r *redisStore) Key(key string) string {
2 years ago
return fmt.Sprintf("captach:%s", key)
2 years ago
}
func (r *redisStore) Set(id string, value string) error {
return r.redis.Set(r.Key(id), value, time.Second*3700).Err()
}
func (r *redisStore) Get(id string, clear bool) string {
val, err := r.redis.Get(r.Key(id)).Result()
if err != nil {
return ""
}
if clear {
r.redis.Del(r.Key(id))
2 years ago
}
2 years ago
return val
2 years ago
}
2 years ago
func (r *redisStore) Verify(id, answer string, clear bool) bool {
2 years ago
val, err := r.redis.Get(r.Key(id)).Result()
if err != nil {
2 years ago
return false
}
2 years ago
if val != answer {
return false
}
if clear {
r.redis.Del(r.Key(id))
}
return true
}
func Get(id string, clear bool) string {
return DefaultStore.Get(id, clear)
}
func Verify(id, answer string, clear bool) bool {
return DefaultStore.Verify(id, answer, clear)
2 years ago
}