feat: 新增 models.go 定义基础模型和枚举类型,并创建 auth_service.go 文件。

This commit is contained in:
2026-01-31 13:47:06 +08:00
parent 4faacd5248
commit 71726ac933
2 changed files with 13 additions and 4 deletions

View File

@@ -711,6 +711,7 @@ type User struct {
Username string `gorm:"size:100" json:"username"` Username string `gorm:"size:100" json:"username"`
Avatar string `gorm:"size:500" json:"avatar,omitempty"` Avatar string `gorm:"size:500" json:"avatar,omitempty"`
IsActive bool `gorm:"default:true" json:"is_active"` IsActive bool `gorm:"default:true" json:"is_active"`
HasPassword bool `gorm:"-" json:"has_password"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"` DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`

View File

@@ -171,6 +171,7 @@ func (s *AuthService) Login(input LoginInput) (*models.User, *TokenPair, error)
return nil, nil, err return nil, nil, err
} }
user.HasPassword = true
return user, tokens, nil return user, tokens, nil
} }
@@ -231,7 +232,12 @@ func (s *AuthService) ValidateEmail(email string) bool {
// GetUserByID retrieves a user by ID // GetUserByID retrieves a user by ID
func (s *AuthService) GetUserByID(id uint) (*models.User, error) { func (s *AuthService) GetUserByID(id uint) (*models.User, error) {
return s.userRepo.GetByID(id) user, err := s.userRepo.GetByID(id)
if err != nil {
return nil, err
}
user.HasPassword = user.PasswordHash != ""
return user, nil
} }
// generateTokenPair generates access and refresh tokens // generateTokenPair generates access and refresh tokens
@@ -286,9 +292,11 @@ func (s *AuthService) UpdatePassword(userID uint, oldPassword, newPassword strin
return err return err
} }
// Verify old password // Verify old password only if user has a password set
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(oldPassword)); err != nil { if user.PasswordHash != "" {
return ErrInvalidCredentials if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(oldPassword)); err != nil {
return ErrInvalidCredentials
}
} }
// Validate new password // Validate new password