-
Notifications
You must be signed in to change notification settings - Fork 0
/
recaptcha.go
115 lines (93 loc) · 2.31 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
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
package recaptcha
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"sync"
"time"
)
type Request struct {
sync.RWMutex
SecretKey string `json:"secret"`
Response string `json:"response"`
RemoteIP string `json:"remoteip,omitempty"`
Transport http.RoundTripper `json:"-"`
}
func (req *Request) httpClient() *http.Client {
req.RLock()
defer req.RUnlock()
if req.Transport == nil {
return http.DefaultClient
}
return &http.Client{
Transport: req.Transport,
}
}
type Response struct {
Success bool `json:"success"`
ErrorCodes []string `json:"error-codes"`
ChallengeTimeStamp *time.Time `json:"challenge_ts"`
}
const verifyURL = "https://www.google.com/recaptcha/api/siteverify"
var (
errEmptySecretKey = errors.New("empty secretKey")
errEmptyResponse = errors.New("empty response")
errNilRequest = errors.New("nil request cannot be validated")
)
func (req *Request) Validate() error {
req.RLock()
defer req.RUnlock()
if req.SecretKey == "" {
return errEmptySecretKey
}
if req.Response == "" {
return errEmptyResponse
}
return nil
}
func (req *Request) Verify() (*Response, error) {
if req == nil {
return nil, errNilRequest
}
if err := req.Validate(); err != nil {
return nil, err
}
// The recaptcha documentation claims POST parameters
// but actually it takes in Query string keys and values
// so need to transform the request into url.Values then .Encode()
// Contrary to the claims at https://developers.google.com/recaptcha/docs/verify
// See https://twitter.com/odeke_et/status/846786233221222400.
blob, err := json.Marshal(req)
if err != nil {
return nil, err
}
asMap := make(map[string]string)
_ = json.Unmarshal(blob, &asMap)
values := make(url.Values)
for key, value := range asMap {
values.Add(key, value)
}
httpClient := req.httpClient()
httpRes, err := httpClient.PostForm(verifyURL, values)
if err != nil {
return nil, err
}
if httpRes.Body != nil {
defer httpRes.Body.Close()
}
if !statusOK(httpRes.StatusCode) {
return nil, errors.New(httpRes.Status)
}
resBlob, err := ioutil.ReadAll(httpRes.Body)
if err != nil {
return nil, err
}
res := new(Response)
if err := json.Unmarshal(resBlob, res); err != nil {
return nil, err
}
return res, nil
}
func statusOK(code int) bool { return code >= 200 && code <= 299 }