captcha.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package dao
  2. import (
  3. "context"
  4. "net/url"
  5. "go-common/library/ecode"
  6. "go-common/library/log"
  7. "go-common/library/net/metadata"
  8. )
  9. // Captcha Captcha.
  10. func (d *Dao) Captcha(c context.Context) (string, string, error) {
  11. params := url.Values{}
  12. params.Set("bid", "answer")
  13. res := &struct {
  14. Code int `json:"code"`
  15. Data struct {
  16. Token string `json:"token"`
  17. URL string `json:"url"`
  18. } `json:"data"`
  19. Msg string `json:"message"`
  20. TTL int `json:"ttl"`
  21. }{}
  22. ip := metadata.String(c, metadata.RemoteIP)
  23. if err := d.captcha.Get(c, d.c.Answer.CaptchaTokenURL, ip, params, res); err != nil {
  24. log.Error("s.captcha.Get(%s) error(%v)", d.c.Answer.CaptchaTokenURL+"?"+params.Encode(), err)
  25. return "", "", err
  26. }
  27. if res.Code != 0 {
  28. log.Error("s.captcha.Get(%s?%s) code:%d", d.c.Answer.CaptchaTokenURL, params.Encode(), res.Code)
  29. return "", "", ecode.Int(res.Code)
  30. }
  31. return res.Data.Token, res.Data.URL, nil
  32. }
  33. // Verify Verify.
  34. func (d *Dao) Verify(c context.Context, token, code, ip string) error {
  35. params := url.Values{}
  36. params.Set("token", token)
  37. params.Set("code", code)
  38. res := &struct {
  39. Code int `json:"code"`
  40. Msg string `json:"message"`
  41. TTL int `json:"ttl"`
  42. }{}
  43. if err := d.captcha.Post(c, d.c.Answer.CaptchaVerifyURL, ip, params, res); err != nil {
  44. log.Error("s.captcha.POST(%s) error(%v)", d.c.Answer.CaptchaVerifyURL+"?"+params.Encode(), err)
  45. return err
  46. }
  47. if res.Code != 0 {
  48. log.Error("s.captcha.POST(%s?%s) code:%d", d.c.Answer.CaptchaVerifyURL, params.Encode(), res.Code)
  49. return ecode.Int(res.Code)
  50. }
  51. return nil
  52. }