geetest.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package service
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "encoding/hex"
  6. "go-common/app/common/openplatform/geetest/dao"
  7. "go-common/app/common/openplatform/geetest/model"
  8. "math/rand"
  9. "strconv"
  10. )
  11. // PreProcess preprocessing the geetest and get to challenge
  12. func PreProcess(c context.Context, mid int64, newCaptcha int, ip, clientType, captchaID, privateKey string) (res *model.ProcessRes, err error) {
  13. var pre string
  14. res = &model.ProcessRes{}
  15. res.CaptchaID = captchaID
  16. res.NewCaptcha = newCaptcha
  17. if pre, err = dao.PreProcess(c, mid, ip, clientType, newCaptcha, captchaID); err != nil || pre == "" {
  18. randOne := md5.Sum([]byte(strconv.Itoa(rand.Intn(100))))
  19. randTwo := md5.Sum([]byte(strconv.Itoa(rand.Intn(100))))
  20. challenge := hex.EncodeToString(randOne[:]) + hex.EncodeToString(randTwo[:])[0:2]
  21. res.Challenge = challenge
  22. return
  23. }
  24. res.Success = 1
  25. slice := md5.Sum([]byte(pre + privateKey))
  26. res.Challenge = hex.EncodeToString(slice[:])
  27. return
  28. }
  29. // Validate recheck the challenge code and get to seccode
  30. func Validate(c context.Context, challenge, validate, seccode, clientType, ip, captchaID, privateKey string, success int, mid int64) (stat bool) {
  31. if len(validate) != 32 {
  32. return
  33. }
  34. if success != 1 {
  35. slice := md5.Sum([]byte(challenge))
  36. stat = hex.EncodeToString(slice[:]) == validate
  37. return
  38. }
  39. slice := md5.Sum([]byte(privateKey + "geetest" + challenge))
  40. if hex.EncodeToString(slice[:]) != validate {
  41. return
  42. }
  43. res, err := dao.Validate(c, challenge, seccode, clientType, ip, captchaID, mid)
  44. if err != nil {
  45. return
  46. }
  47. slice = md5.Sum([]byte(seccode))
  48. stat = hex.EncodeToString(slice[:]) == res.Seccode
  49. return
  50. }