You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

recaptcha.go 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package recaptcha
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. "time"
  12. "code.gitea.io/gitea/modules/setting"
  13. )
  14. // Response is the structure of JSON returned from API
  15. type Response struct {
  16. Success bool `json:"success"`
  17. ChallengeTS time.Time `json:"challenge_ts"`
  18. Hostname string `json:"hostname"`
  19. ErrorCodes []string `json:"error-codes"`
  20. }
  21. const apiURL = "https://www.google.com/recaptcha/api/siteverify"
  22. // Verify calls Google Recaptcha API to verify token
  23. func Verify(response string) (bool, error) {
  24. resp, err := http.PostForm(apiURL,
  25. url.Values{"secret": {setting.Service.RecaptchaSecret}, "response": {response}})
  26. if err != nil {
  27. return false, fmt.Errorf("Failed to send CAPTCHA response: %s", err)
  28. }
  29. defer resp.Body.Close()
  30. body, err := ioutil.ReadAll(resp.Body)
  31. if err != nil {
  32. return false, fmt.Errorf("Failed to read CAPTCHA response: %s", err)
  33. }
  34. var jsonResponse Response
  35. err = json.Unmarshal(body, &jsonResponse)
  36. if err != nil {
  37. return false, fmt.Errorf("Failed to parse CAPTCHA response: %s", err)
  38. }
  39. return jsonResponse.Success, nil
  40. }