-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathcaptcha.go
79 lines (66 loc) · 2.05 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
package controllers
import (
"bytes"
"net/http"
"path"
"strings"
"time"
"github.com/dchest/captcha"
"github.com/zenazn/goji/web"
)
type captchaHandler struct {
ImgWidth int
ImgHeight int
}
// CaptchaServe writes and serves captchas.
func (controller *MainController) CaptchaServe(c web.C, w http.ResponseWriter, r *http.Request) {
// Get the captcha id by stripping the file extension.
_, file := path.Split(r.URL.Path)
ext := path.Ext(file)
id := strings.TrimSuffix(file, ext)
if ext != ".png" || id == "" {
http.NotFound(w, r)
return
}
h := controller.captchaHandler
if r.FormValue("reload") != "" {
captcha.Reload(id)
}
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
var content bytes.Buffer
w.Header().Set("Content-Type", "image/png")
err := captcha.WriteImage(&content, id, h.ImgWidth, h.ImgHeight)
if err != nil {
http.Error(w, "failed to generate captcha image", http.StatusInternalServerError)
}
http.ServeContent(w, r, id+ext, time.Time{}, bytes.NewReader(content.Bytes()))
}
// CaptchaVerify verifies that the provided captcha matches the on screen text
// and sets the CaptchaDone session value.
func (controller *MainController) CaptchaVerify(c web.C, w http.ResponseWriter, r *http.Request) {
id, solution := r.FormValue("captchaId"), r.FormValue("captchaSolution")
if id == "" {
http.Error(w, "invalid captcha id", http.StatusBadRequest)
return
}
session := controller.GetSession(c)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if captcha.VerifyString(id, solution) {
session.Values["CaptchaDone"] = true
} else {
session.Values["CaptchaDone"] = false
session.AddFlash("Captcha verification failed. Please try again.",
"captchaFailed")
}
if err := session.Save(r, w); err != nil {
log.Criticalf("session.Save() failed: %v", err)
http.Error(w, "failed to save session", http.StatusInternalServerError)
}
ref := r.Referer()
if ref == "" {
ref = "/"
}
http.Redirect(w, r, ref, http.StatusFound)
}