forked from dpapathanasiou/go-recaptcha
-
Notifications
You must be signed in to change notification settings - Fork 1
/
recaptcha.go
69 lines (62 loc) · 2.3 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
// Package recaptcha handles reCaptcha (http://www.google.com/recaptcha) form submissions
//
// This package is designed to be called from within an HTTP server or web framework
// which offers reCaptcha form inputs and requires them to be evaluated for correctness
//
// Edit the recaptchaPrivateKey constant before building and using
package recaptcha
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
)
type RecaptchaResponse struct {
Success bool `json:"success"`
ChallengeTS time.Time `json:"challenge_ts"`
Hostname string `json:"hostname"`
ErrorCodes []string `json:"error-codes"`
}
const recaptchaServerName = "https://www.google.com/recaptcha/api/siteverify"
var recaptchaPrivateKey string
// check uses the client ip address, the challenge code from the reCaptcha form,
// and the client's response input to that challenge to determine whether or not
// the client answered the reCaptcha input question correctly.
// It returns a boolean value indicating whether or not the client answered correctly.
func check(remoteip, response string) (r RecaptchaResponse, err error) {
resp, err := http.PostForm(recaptchaServerName,
url.Values{"secret": {recaptchaPrivateKey}, "remoteip": {remoteip}, "response": {response}})
if err != nil {
log.Printf("Post error: %s\n", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Read error: could not read body: %s", err)
return
}
err = json.Unmarshal(body, &r)
if err != nil {
log.Println("Read error: got invalid JSON: %s", err)
return
}
return
}
// Confirm is the public interface function.
// It calls check, which the client ip address, the challenge code from the reCaptcha form,
// and the client's response input to that challenge to determine whether or not
// the client answered the reCaptcha input question correctly.
// It returns a boolean value indicating whether or not the client answered correctly.
func Confirm(remoteip, response string) (result bool, err error) {
resp, err := check(remoteip, response)
result = resp.Success
return
}
// Init allows the webserver or code evaluating the reCaptcha form input to set the
// reCaptcha private key (string) value, which will be different for every domain.
func Init(key string) {
recaptchaPrivateKey = key
}