77 lines
1.9 KiB
Go
77 lines
1.9 KiB
Go
|
|
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": "验证失败,请重试",
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
}
|