forked from haisum/recaptcha
/
recaptcha.go
78 lines (72 loc) · 1.98 KB
/
recaptcha.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
// Package github.com/haisum/recaptcha is google golang module for google re-captcha.
//
// Installation
//
// go get github.com/haisum/recaptcha
//
// Usage
//
// Usage example can be found in example/main.go file.
//
//
// Source code
//
// Available on github: http://github.com/haisum/recaptcha
//
// Author: Haisum (haisumbhatti@gmail.com)
package recaptcha
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"time"
)
// recaptcha.R type represents an object of Recaptcha and has public property Secret,
// which is secret obtained from google recaptcha tool admin interface
type R struct {
Secret string
lastError []string
}
// Struct for parsing json in google's response
type googleResponse struct {
Success bool
ErrorCodes []string `json:"error-codes"`
}
// url to post submitted re-captcha response to
var postUrl string = "https://www.google.com/recaptcha/api/siteverify"
// Verify method, verifies if current request have valid re-captcha response and returns true or false
// This method also records any errors in validation.
// These errors can be received by calling LastError() method.
func (r *R) Verify(req http.Request) bool {
r.lastError = make([]string, 1)
response := req.PostFormValue("g-recaptcha-response")
client := &http.Client{Timeout: 20 * time.Second}
resp, err := client.PostForm(postUrl,
url.Values{"secret": {r.Secret}, "response": {response}})
if err != nil {
r.lastError = append(r.lastError, err.Error())
return false
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
r.lastError = append(r.lastError, err.Error())
return false
} else {
gr := new(googleResponse)
err := json.Unmarshal(body, gr)
if err != nil {
r.lastError = append(r.lastError, err.Error())
return false
}
if !gr.Success {
r.lastError = append(r.lastError, gr.ErrorCodes...)
}
return gr.Success
}
}
// Returns errors occurred in last re-captcha validation attempt
func (r R) LastError() []string {
return r.lastError
}