Debian Codegraph @

recaptcha.go

raw
1 // Package recaptcha handles reCaptcha (http://www.google.com/recaptcha) form submissions
2 //
3 // This package is designed to be called from within an HTTP server or web framework
4 // which offers reCaptcha form inputs and requires them to be evaluated for correctness
5 //
6 // Edit the recaptchaPrivateKey constant before building and using
7 package recaptcha
8
9 import (
10 "encoding/json"
11 "io/ioutil"
12 "log"
13 "net/http"
14 "net/url"
15 "time"
16 )
17
18 type RecaptchaResponse struct {
19 Success bool `json:"success"`
20 Score float64 `json:"score"`
21 Action string `json:"action"`
22 ChallengeTS time.Time `json:"challenge_ts"`
23 Hostname string `json:"hostname"`
24 ErrorCodes []string `json:"error-codes"`
25 }
26
27 const recaptchaServerName = "https://www.google.com/recaptcha/api/siteverify"
28
29 var recaptchaPrivateKey string
30
31 // check uses the client ip address, the challenge code from the reCaptcha form,
32 // and the client's response input to that challenge to determine whether or not
33 // the client answered the reCaptcha input question correctly.
34 // It returns a boolean value indicating whether or not the client answered correctly.
35 func check(remoteip, response string) (r RecaptchaResponse, err error) {
36 resp, err := http.PostForm(recaptchaServerName,
37 url.Values{"secret": {recaptchaPrivateKey}, "remoteip": {remoteip}, "response": {response}})
38 if err != nil {
39 log.Printf("Post error: %s\n", err)
40 return
41 }
42 defer resp.Body.Close()
43 body, err := ioutil.ReadAll(resp.Body)
44 if err != nil {
45 log.Println("Read error: could not read body: %s", err)
46 return
47 }
48 err = json.Unmarshal(body, &r)
49 if err != nil {
50 log.Println("Read error: got invalid JSON: %s", err)
51 return
52 }
53 return
54 }
55
56 // Confirm is the public interface function.
57 // It calls check, which the client ip address, the challenge code from the reCaptcha form,
58 // and the client's response input to that challenge to determine whether or not
59 // the client answered the reCaptcha input question correctly.
60 // It returns a boolean value indicating whether or not the client answered correctly.
61 func Confirm(remoteip, response string) (result bool, err error) {
62 resp, err := check(remoteip, response)
63 result = resp.Success
64 return
65 }
66
67 // Init allows the webserver or code evaluating the reCaptcha form input to set the
68 // reCaptcha private key (string) value, which will be different for every domain.
69 func Init(key string) {
70 recaptchaPrivateKey = key
71 }