package handler import ( "carrotskin/internal/container" "net/http" "github.com/gin-gonic/gin" "go.uber.org/zap" ) // CaptchaHandler 验证码处理器 type CaptchaHandler struct { container *container.Container logger *zap.Logger } // NewCaptchaHandler 创建CaptchaHandler实例 func NewCaptchaHandler(c *container.Container) *CaptchaHandler { return &CaptchaHandler{ container: c, logger: c.Logger, } } // CaptchaVerifyRequest 验证码验证请求 type CaptchaVerifyRequest struct { CaptchaID string `json:"captchaId" binding:"required"` Dx int `json:"dx" binding:"required"` } // Generate 生成验证码 // @Summary 生成滑动验证码 // @Description 生成滑动验证码图片 // @Tags captcha // @Accept json // @Produce json // @Success 200 {object} map[string]interface{} "生成成功" // @Failure 500 {object} map[string]interface{} "生成失败" // @Router /api/v1/captcha/generate [get] func (h *CaptchaHandler) Generate(c *gin.Context) { masterImg, tileImg, captchaID, y, err := h.container.CaptchaService.Generate(c.Request.Context()) if err != nil { h.logger.Error("生成验证码失败", zap.Error(err)) c.JSON(http.StatusInternalServerError, gin.H{ "code": 500, "msg": "生成验证码失败", }) return } c.JSON(http.StatusOK, gin.H{ "code": 200, "data": gin.H{ "masterImage": masterImg, "tileImage": tileImg, "captchaId": captchaID, "y": y, }, }) } // Verify 验证验证码 // @Summary 验证滑动验证码 // @Description 验证用户滑动的偏移量是否正确 // @Tags captcha // @Accept json // @Produce json // @Param request body CaptchaVerifyRequest true "验证请求" // @Success 200 {object} map[string]interface{} "验证结果" // @Failure 400 {object} map[string]interface{} "参数错误" // @Router /api/v1/captcha/verify [post] func (h *CaptchaHandler) Verify(c *gin.Context) { var req CaptchaVerifyRequest if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{ "code": 400, "msg": "参数错误: " + err.Error(), }) return } valid, err := h.container.CaptchaService.Verify(c.Request.Context(), req.Dx, req.CaptchaID) if err != nil { h.logger.Error("验证码验证失败", zap.String("captcha_id", req.CaptchaID), zap.Error(err), ) c.JSON(http.StatusInternalServerError, gin.H{ "code": 500, "msg": "验证失败", }) return } if valid { c.JSON(http.StatusOK, gin.H{ "code": 200, "msg": "验证成功", }) } else { c.JSON(http.StatusOK, gin.H{ "code": 400, "msg": "验证失败,请重试", }) } }