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.

48 lines
1.3 KiB

  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. "code.gitea.io/gitea/modules/util"
  14. )
  15. // Response is the structure of JSON returned from API
  16. type Response struct {
  17. Success bool `json:"success"`
  18. ChallengeTS time.Time `json:"challenge_ts"`
  19. Hostname string `json:"hostname"`
  20. ErrorCodes []string `json:"error-codes"`
  21. }
  22. const apiURL = "api/siteverify"
  23. // Verify calls Google Recaptcha API to verify token
  24. func Verify(response string) (bool, error) {
  25. resp, err := http.PostForm(util.URLJoin(setting.Service.RecaptchaURL, apiURL),
  26. url.Values{"secret": {setting.Service.RecaptchaSecret}, "response": {response}})
  27. if err != nil {
  28. return false, fmt.Errorf("Failed to send CAPTCHA response: %s", err)
  29. }
  30. defer resp.Body.Close()
  31. body, err := ioutil.ReadAll(resp.Body)
  32. if err != nil {
  33. return false, fmt.Errorf("Failed to read CAPTCHA response: %s", err)
  34. }
  35. var jsonResponse Response
  36. err = json.Unmarshal(body, &jsonResponse)
  37. if err != nil {
  38. return false, fmt.Errorf("Failed to parse CAPTCHA response: %s", err)
  39. }
  40. return jsonResponse.Success, nil
  41. }