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

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
}

View File

@@ -12,6 +12,7 @@ type UserRepository interface {
Create(user *models.User) error
FindByUsername(username string) (*models.User, error)
FindByID(id uint) (*models.User, error)
FindUserForLogin(identifier string) (*models.User, error)
}
// gormUserRepository 是 UserRepository 的 GORM 实现
@@ -39,6 +40,22 @@ func (r *gormUserRepository) FindByUsername(username string) (*models.User, erro
return &user, nil
}
// FindUserForLogin 根据提供的标识符查找用户,可用于登录验证
// 标识符可以是用户名、邮箱、手机号、微信号或飞书账号
func (r *gormUserRepository) FindUserForLogin(identifier string) (*models.User, error) {
var user models.User
// 使用 ->> 操作符来查询 JSONB 字段中的文本值
err := r.db.Where(
"username = ? OR contact ->> 'email' = ? OR contact ->> 'phone' = ? OR contact ->> 'wechat' = ? OR contact ->> 'feishu' = ?",
identifier, identifier, identifier, identifier, identifier,
).First(&user).Error
if err != nil {
return nil, err
}
return &user, nil
}
// FindByID 根据 ID 查找用户
func (r *gormUserRepository) FindByID(id uint) (*models.User, error) {
var user models.User