-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcaptcha.go
121 lines (108 loc) · 2.32 KB
/
captcha.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package kuu
import (
"github.com/gin-gonic/gin"
"github.com/mojocn/base64Captcha"
"math/rand"
"strings"
"time"
)
var (
// CaptchaIDKey
CaptchaIDKey = "captcha_id"
// CaptchaValKey
CaptchaValKey = "captcha_val"
store = &captchaStore{}
)
func init() {
//init rand seed
rand.Seed(time.Now().UnixNano())
}
type captchaStore struct{}
func (cs *captchaStore) Set(id string, value string) error {
DefaultCache.SetString(id, value)
return nil
}
func (cs *captchaStore) Get(id string, clear bool) string {
v := DefaultCache.GetString(id)
if clear {
DefaultCache.Del(id)
}
return v
}
func (cs *captchaStore) Verify(id, answer string, clear bool) bool {
v := cs.Get(id, clear)
return v == answer
}
// NewCaptcha creates a captcha instance from driver and store
func NewCaptcha() *base64Captcha.Captcha {
driver := &base64Captcha.DriverDigit{
Height: 80,
Width: 280,
Length: 4,
MaxSkew: 0.1,
DotCount: 10,
}
return base64Captcha.NewCaptcha(driver, store)
}
// GenerateCaptcha create a digit captcha.
func GenerateCaptcha() (id string, base64Str string) {
c := NewCaptcha()
id, base64Str, err := c.Generate()
if err != nil {
ERROR(err)
}
return
}
// VerifyCaptcha Verify captcha value.
func VerifyCaptcha(idKey, value string) bool {
return store.Verify(idKey, value, true)
}
// VerifyCaptchaWithClear Verify captcha value.
func VerifyCaptchaWithClear(idKey, value string, clear bool) bool {
return store.Verify(idKey, value, clear)
}
// ParseCaptchaID
func ParseCaptchaID(c interface{}) string {
var (
ctx *gin.Context
id string
)
if v, ok := c.(*gin.Context); ok {
ctx = v
} else if v, ok := c.(*Context); ok {
ctx = v.Context
}
if ctx != nil {
id = ctx.Query(CaptchaIDKey)
if id == "" {
id = ctx.GetHeader(CaptchaIDKey)
}
if id == "" {
id = ctx.GetHeader(strings.ReplaceAll(CaptchaIDKey, "-", ""))
}
id, _ = ctx.Cookie(CaptchaIDKey)
}
return id
}
// ParseCaptchaValue
func ParseCaptchaValue(c interface{}) string {
var (
ctx *gin.Context
val string
)
if v, ok := c.(*gin.Context); ok {
ctx = v
} else if v, ok := c.(*Context); ok {
ctx = v.Context
}
if ctx != nil {
val = ctx.Query(CaptchaValKey)
if val == "" {
val = ctx.GetHeader(CaptchaValKey)
}
if val == "" {
val = ctx.GetHeader(strings.ReplaceAll(CaptchaValKey, "-", ""))
}
}
return val
}