From 71726ac9339a6e181890dc7bc3645a718bd8e1dd Mon Sep 17 00:00:00 2001 From: 12975 <1297598740@qq.com> Date: Sat, 31 Jan 2026 13:47:06 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=20`models.go`=20?= =?UTF-8?q?=E5=AE=9A=E4=B9=89=E5=9F=BA=E7=A1=80=E6=A8=A1=E5=9E=8B=E5=92=8C?= =?UTF-8?q?=E6=9E=9A=E4=B8=BE=E7=B1=BB=E5=9E=8B=EF=BC=8C=E5=B9=B6=E5=88=9B?= =?UTF-8?q?=E5=BB=BA=20`auth=5Fservice.go`=20=E6=96=87=E4=BB=B6=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/models/models.go | 1 + internal/service/auth_service.go | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/internal/models/models.go b/internal/models/models.go index 626a00e..2dea65f 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -711,6 +711,7 @@ type User struct { Username string `gorm:"size:100" json:"username"` Avatar string `gorm:"size:500" json:"avatar,omitempty"` IsActive bool `gorm:"default:true" json:"is_active"` + HasPassword bool `gorm:"-" json:"has_password"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeletedAt gorm.DeletedAt `gorm:"index" json:"-"` diff --git a/internal/service/auth_service.go b/internal/service/auth_service.go index c8dedef..952da85 100644 --- a/internal/service/auth_service.go +++ b/internal/service/auth_service.go @@ -171,6 +171,7 @@ func (s *AuthService) Login(input LoginInput) (*models.User, *TokenPair, error) return nil, nil, err } + user.HasPassword = true return user, tokens, nil } @@ -231,7 +232,12 @@ func (s *AuthService) ValidateEmail(email string) bool { // GetUserByID retrieves a user by ID 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 @@ -286,9 +292,11 @@ func (s *AuthService) UpdatePassword(userID uint, oldPassword, newPassword strin return err } - // Verify old password - if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(oldPassword)); err != nil { - return ErrInvalidCredentials + // Verify old password only if user has a password set + if user.PasswordHash != "" { + if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(oldPassword)); err != nil { + return ErrInvalidCredentials + } } // Validate new password