Files
backend/internal/handler/captcha_handler.go
lan 4b4980820f
Some checks failed
SonarQube Analysis / sonarqube (push) Has been cancelled
Test / test (push) Has been cancelled
Test / lint (push) Has been cancelled
Test / build (push) Has been cancelled
chore: 初始化仓库,排除二进制文件和覆盖率文件
2025-11-28 23:30:49 +08:00

77 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package handler
import (
"carrotskin/internal/service"
"carrotskin/pkg/redis"
"net/http"
"github.com/gin-gonic/gin"
)
// Generate 生成验证码
func Generate(c *gin.Context) {
// 调用验证码服务生成验证码数据
redisClient := redis.MustGetClient()
masterImg, tileImg, captchaID, y, err := service.GenerateCaptchaData(c.Request.Context(), redisClient)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"code": 500,
"msg": "生成验证码失败: " + err.Error(),
})
return
}
// 返回验证码数据给前端
c.JSON(http.StatusOK, gin.H{
"code": 200,
"data": gin.H{
"masterImage": masterImg, // 主图base64格式
"tileImage": tileImg, // 滑块图base64格式
"captchaId": captchaID, // 验证码唯一标识(用于后续验证)
"y": y, // 滑块Y坐标前端可用于定位滑块初始位置
},
})
}
// Verify 验证验证码
func Verify(c *gin.Context) {
// 定义请求参数结构体
var req struct {
CaptchaID string `json:"captchaId" binding:"required"` // 验证码唯一标识
Dx int `json:"dx" binding:"required"` // 用户滑动的X轴偏移量
}
// 解析并校验请求参数
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"msg": "参数错误: " + err.Error(),
})
return
}
// 调用验证码服务验证偏移量
redisClient := redis.MustGetClient()
valid, err := service.VerifyCaptchaData(c.Request.Context(), redisClient, req.Dx, req.CaptchaID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"code": 500,
"msg": "验证失败: " + err.Error(),
})
return
}
// 根据验证结果返回响应
if valid {
c.JSON(http.StatusOK, gin.H{
"code": 200,
"msg": "验证成功",
})
} else {
c.JSON(http.StatusOK, gin.H{
"code": 400,
"msg": "验证失败,请重试",
})
}
}