|
|
|
package captcha
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"git.diulo.com/mogfee/protoc-gen-kit/pkg/base64Captcha"
|
|
|
|
"github.com/go-redis/redis"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
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"},
|
|
|
|
}
|
|
|
|
var DefaultStore = base64Captcha.DefaultMemStore
|
|
|
|
|
|
|
|
func SetStore(store base64Captcha.Store) {
|
|
|
|
DefaultStore = store
|
|
|
|
}
|
|
|
|
|
|
|
|
func Generate() (id, b64s string, err error) {
|
|
|
|
return base64Captcha.NewCaptcha(&DefaultConfig, DefaultStore).Generate()
|
|
|
|
}
|
|
|
|
|
|
|
|
type redisStore struct {
|
|
|
|
redis *redis.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewRedisStore(redis *redis.Client) *redisStore {
|
|
|
|
return &redisStore{
|
|
|
|
redis: redis,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *redisStore) Key(key string) string {
|
|
|
|
return fmt.Sprintf("captach:%s", key)
|
|
|
|
}
|
|
|
|
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))
|
|
|
|
}
|
|
|
|
return val
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *redisStore) Verify(id, answer string, clear bool) bool {
|
|
|
|
val, err := r.redis.Get(r.Key(id)).Result()
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
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)
|
|
|
|
}
|