-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhcaptcha.go
128 lines (107 loc) · 3.56 KB
/
hcaptcha.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
116
117
118
119
120
121
122
123
124
125
126
127
128
// Package hcaptcha handles hCaptcha (https://hcaptcha.com) form submissions
//
// This package is designed to be called from within an HTTP server or web framework
// which offers hCaptcha form inputs and requires them to be evaluated for correctness
//
// Edit the hcaptchaPrivateKey constant before building and using
package hcaptcha
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"time"
"go.elastic.co/apm/module/apmhttp"
)
// Response holds the response provided by
// google hcaptcha
type Response struct {
Success bool `json:"success"`
Score float32 `json:"score"`
Hostname string `json:"hostname"`
ErrorCodes []string `json:"error-codes"`
}
const hcaptchaServerName = "https://hcaptcha.com/siteverify"
var hcaptchaPrivateKey string
var hcaptchaScore float32
var timeResponse int
var postError bool
func check(ctx context.Context, response string, ip string) (r Response, err error) {
postError = false
resp, err := performCaptchaRequest(ctx, response, ip)
if err != nil {
log.Printf("Post error: %s\n", err)
postError = true
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Read error: could not read body: %s", err)
return
}
err = json.Unmarshal(body, &r)
if err != nil {
fmt.Printf("Read error: got invalid JSON: %s", err)
return
}
return
}
func performCaptchaRequest(ctx context.Context, response string, ip string) (*http.Response, error) {
netClient := apmhttp.WrapClient(&http.Client{
Timeout: time.Duration(timeResponse) * time.Second,
})
payload := url.Values{
"secret": {hcaptchaPrivateKey},
"response": {response},
"remoteip": {ip},
}
log.Printf("[%v] Validating captcha challenge result\n", ip)
request, _ := http.NewRequest("POST", hcaptchaServerName, strings.NewReader(payload.Encode()))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return netClient.Do(request.WithContext(ctx))
}
// Confirm adds a default context and calls ConfirmWithContext
func Confirm(response, ip string) (result bool, score float32, err error) {
return ConfirmWithContext(context.Background(), response, ip)
}
// ConfirmWithContext is the public interface function.
// It calls check, which the client ip address, the challenge code from the hCaptcha form,
// and the client's response input to that challenge to determine whether or not
// the client answered the hCaptcha input question correctly.
// It returns a boolean value indicating whether or not the client answered correctly.
func ConfirmWithContext(ctx context.Context, response string, ip string) (result bool, score float32, err error) {
result = false
score = 0.0
resp, err := check(ctx, response, ip)
log.Printf("[%v] Captcha: User token: %s\n", ip, response)
if resp.Success {
score = resp.Score
if resp.Score < hcaptchaScore {
result = true
log.Printf("[%v] Captcha: Valid token with risk score of %f\n", ip, resp.Score)
} else {
result = false
log.Printf("[%v] Captcha: Valid token but refused due high risk score(got: %f, expected: < %f)", ip, resp.Score, hcaptchaScore)
}
return
}
if postError {
log.Printf("[%v] Unable to verify captcha due request error", ip)
result = true
return
}
log.Printf("[%v] Captcha: Invalid token", ip)
return
}
// Init allows the webserver or code evaluating the hCaptcha form input to set the
// hCaptcha private key (string) value, which will be different for every domain.
func Init(key string, score float32, time int) {
hcaptchaPrivateKey = key
hcaptchaScore = score
timeResponse = time
}