-
Notifications
You must be signed in to change notification settings - Fork 0
/
captcha.go
108 lines (96 loc) · 1.95 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
package rtfblog
import (
"encoding/json"
"fmt"
"log/slog"
"math/rand"
"net/http"
)
type CaptchaTask struct {
Task string
ID string
Answer string
}
type Deck struct {
nextTask int
tasks []CaptchaTask
}
var (
deck *Deck
)
func NewDeck() *Deck {
var deck Deck
answers := []string{
"vienuolika",
"dvylika",
"trylika",
"keturiolika",
"penkiolika",
"šešiolika",
"septyniolika",
"aštuoniolika",
"devyniolika",
}
deck.tasks = make([]CaptchaTask, 0, 0)
for i, answer := range answers {
task := CaptchaTask{
Task: fmt.Sprintf("9 + %d =", i+2),
ID: fmt.Sprintf("%d", 666+i),
Answer: answer,
}
deck.tasks = append(deck.tasks, task)
}
return &deck
}
func init() {
deck = NewDeck()
}
func (d *Deck) NextTask() *CaptchaTask {
return &d.tasks[d.nextTask]
}
func (d *Deck) GetTask(id string) *CaptchaTask {
for _, t := range d.tasks {
if t.ID == id {
return &t
}
}
return &d.tasks[0]
}
func (d *Deck) SetNextTask(task int) {
if task < 0 {
task = rand.Int() % len(d.tasks)
}
d.nextTask = task
}
func CheckCaptcha(task *CaptchaTask, input string) bool {
return input == task.Answer
}
func WrongCaptchaReply(w http.ResponseWriter, req *http.Request, status string, task *CaptchaTask, log *slog.Logger) error {
b, err := json.Marshal(map[string]interface{}{
"status": status,
"captcha-id": task.ID,
"captcha-task": task.Task,
"name": req.FormValue("name"),
"email": req.FormValue("email"),
"website": req.FormValue("website"),
"body": req.FormValue("text"),
})
if err != nil {
log.Error("WrongCaptchaReply json.Marshal", E(err))
return err
}
w.Write(b)
return nil
}
func RightCaptchaReply(w http.ResponseWriter, redir string, log *slog.Logger) error {
b, err := json.Marshal(map[string]interface{}{
"status": "accepted",
"redir": redir,
})
if err != nil {
log.Error("RightCaptchaReply json.Marshal", E(err))
return err
}
w.Write(b)
return nil
}