CaptchaRequired 验证请求签名
(enabled func(c *gin.Context) bool)
| 46 | |
| 47 | // CaptchaRequired 验证请求签名 |
| 48 | func CaptchaRequired(enabled func(c *gin.Context) bool) gin.HandlerFunc { |
| 49 | return func(c *gin.Context) { |
| 50 | if enabled(c) { |
| 51 | dep := dependency.FromContext(c) |
| 52 | settings := dep.SettingProvider() |
| 53 | l := logging.FromContext(c) |
| 54 | |
| 55 | var service req |
| 56 | bodyCopy := new(bytes.Buffer) |
| 57 | _, err := io.Copy(bodyCopy, c.Request.Body) |
| 58 | if err != nil { |
| 59 | c.JSON(200, serializer.ErrWithDetails(c, serializer.CodeCaptchaError, captchaNotMatch, err)) |
| 60 | c.Abort() |
| 61 | return |
| 62 | } |
| 63 | |
| 64 | bodyData := bodyCopy.Bytes() |
| 65 | err = json.Unmarshal(bodyData, &service) |
| 66 | if err != nil { |
| 67 | c.JSON(200, serializer.ErrWithDetails(c, serializer.CodeCaptchaError, captchaNotMatch, err)) |
| 68 | c.Abort() |
| 69 | return |
| 70 | } |
| 71 | |
| 72 | c.Request.Body = io.NopCloser(bytes.NewReader(bodyData)) |
| 73 | switch settings.CaptchaType(c) { |
| 74 | case setting.CaptchaNormal, setting.CaptchaTcaptcha: |
| 75 | if service.Ticket == "" || !base64Captcha.VerifyCaptcha(service.Ticket, service.Captcha) { |
| 76 | c.JSON(200, serializer.ErrWithDetails(c, serializer.CodeCaptchaError, captchaNotMatch, err)) |
| 77 | c.Abort() |
| 78 | return |
| 79 | } |
| 80 | |
| 81 | break |
| 82 | case setting.CaptchaReCaptcha: |
| 83 | captchaSetting := settings.ReCaptcha(c) |
| 84 | reCAPTCHA, err := recaptcha.NewReCAPTCHA(captchaSetting.Secret, recaptcha.V2, 10*time.Second) |
| 85 | if err != nil { |
| 86 | l.Warning("reCAPTCHA verification failed, %s", err) |
| 87 | c.Abort() |
| 88 | break |
| 89 | } |
| 90 | |
| 91 | err = reCAPTCHA.Verify(service.Captcha) |
| 92 | if err != nil { |
| 93 | l.Warning("reCAPTCHA verification failed, %s", err) |
| 94 | c.JSON(200, serializer.ErrWithDetails(c, serializer.CodeCaptchaError, captchaRefresh, err)) |
| 95 | c.Abort() |
| 96 | return |
| 97 | } |
| 98 | |
| 99 | break |
| 100 | case setting.CaptchaTurnstile: |
| 101 | captchaSetting := settings.TurnstileCaptcha(c) |
| 102 | r := dep.RequestClient( |
| 103 | request2.WithContext(c), |
| 104 | request2.WithLogger(logging.FromContext(c)), |
| 105 | request2.WithHeader(http.Header{"Content-Type": []string{"application/x-www-form-urlencoded"}}), |
no test coverage detected