-
Notifications
You must be signed in to change notification settings - Fork 0
/
captcha.go
75 lines (66 loc) · 1.91 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
package part
import (
"github.com/anden007/dp_clean_core/pkg"
"github.com/mojocn/base64Captcha"
)
type Captcha struct {
captcha *base64Captcha.Captcha
}
type ICaptcha interface {
New() (result *pkg.CaptchaData, err error)
Reload(id string) (result *pkg.CaptchaData, err error)
Draw(id string) (result *pkg.CaptchaData, err error)
Verify(id string, digits string) (result bool, err error)
}
func NewCaptcha(cache ICache) ICaptcha {
instance := new(Captcha)
store := NewRedisStore(cache)
driver := base64Captcha.NewDriverDigit(32, 110, 4, 0.1, 10)
instance.captcha = base64Captcha.NewCaptcha(driver, store)
return instance
}
func (m *Captcha) New() (result *pkg.CaptchaData, err error) {
err = nil
id, digits, answer := m.captcha.Driver.GenerateIdQuestionAnswer()
item, err := m.captcha.Driver.DrawCaptcha(digits)
if err == nil {
result = &pkg.CaptchaData{
ID: id,
Digits: answer,
Base64Image: item.EncodeB64string(),
}
m.captcha.Store.Set(result.ID, result.Digits)
}
return result, err
}
func (m *Captcha) Reload(id string) (result *pkg.CaptchaData, err error) {
err = nil
_, digits, answer := m.captcha.Driver.GenerateIdQuestionAnswer()
item, err := m.captcha.Driver.DrawCaptcha(digits)
if err == nil {
result = &pkg.CaptchaData{
ID: id,
Digits: answer,
Base64Image: item.EncodeB64string(),
}
m.captcha.Store.Set(result.ID, result.Digits)
}
return result, err
}
func (m *Captcha) Verify(id string, digits string) (result bool, err error) {
result = m.captcha.Store.Verify(id, digits, true)
return result, err
}
func (m *Captcha) Draw(id string) (result *pkg.CaptchaData, err error) {
digits := m.captcha.Store.Get(id, false)
if item, drawErr := m.captcha.Driver.DrawCaptcha(digits); drawErr == nil {
result = &pkg.CaptchaData{
ID: id,
Digits: digits,
Base64Image: item.EncodeB64string(),
}
} else {
err = drawErr
}
return
}