支持用手机号等信息代替用户名登录

This commit is contained in:
2025-09-27 23:28:06 +08:00
parent 6d9d4ff91b
commit b177781fa1
2 changed files with 25 additions and 6 deletions

View File

@@ -34,8 +34,9 @@ type CreateUserRequest struct {
// LoginRequest 定义登录请求的结构体
type LoginRequest struct {
Username string `json:"username" binding:"required" example:"testuser"`
Password string `json:"password" binding:"required" example:"password123"`
// Identifier 可以是用户名、邮箱、手机号、微信号或飞书账号
Identifier string `json:"identifier" binding:"required" example:"testuser"`
Password string `json:"password" binding:"required" example:"password123"`
}
// CreateUserResponse 定义创建用户成功响应的结构体
@@ -96,7 +97,7 @@ func (c *Controller) CreateUser(ctx *gin.Context) {
// Login godoc
// @Summary 用户登录
// @Description 用户使用用户名和密码登录,成功后返回 JWT 令牌。
// @Description 用户可以使用用户名、邮箱、手机号、微信号或飞书账号进行登录,成功后返回 JWT 令牌。
// @Tags 用户管理
// @Accept json
// @Produce json
@@ -111,10 +112,11 @@ func (c *Controller) Login(ctx *gin.Context) {
return
}
user, err := c.userRepo.FindByUsername(req.Username)
// 使用新的方法,通过唯一标识符(用户名、邮箱等)查找用户
user, err := c.userRepo.FindUserForLogin(req.Identifier)
if err != nil {
if err == gorm.ErrRecordNotFound {
controller.SendErrorResponse(ctx, controller.CodeUnauthorized, "用户名或密码不正确")
controller.SendErrorResponse(ctx, controller.CodeUnauthorized, "登录凭证不正确")
return
}
c.logger.Errorf("登录: 查询用户失败: %v", err)
@@ -123,7 +125,7 @@ func (c *Controller) Login(ctx *gin.Context) {
}
if !user.CheckPassword(req.Password) {
controller.SendErrorResponse(ctx, controller.CodeUnauthorized, "用户名或密码不正确")
controller.SendErrorResponse(ctx, controller.CodeUnauthorized, "登录凭证不正确")
return
}