feat: hash user password and update by username

This commit is contained in:
Leon
2025-12-05 13:10:19 +08:00
parent f7389ff778
commit df30d7b549
2 changed files with 15 additions and 3 deletions

View File

@@ -29,8 +29,19 @@ func (us *UserService) RenameByID(id uint, newUsername string) error {
return nil
}
func (us *UserService) ChangePassword(id uint, newPassword string) error {
if err := us.userRepository.ChangePassword(id, newPassword); err != nil {
func (us *UserService) ChangePassword(username, oldPassword, newPassword string) error {
user, err := us.FindByUsername(username)
if err != nil {
return err
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(oldPassword)); err != nil {
return err
}
passwordHash, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
if err != nil {
return err
}
if err := us.userRepository.ChangePassword(user.ID, string(passwordHash)); err != nil {
return err
}
return nil

View File

@@ -45,7 +45,8 @@ type FindByUsernameResponse struct {
}
type ChangePasswordRequest struct {
ID uint `json:"id"`
Username string `json:"username"`
OldPassword string `json:"old_password"`
NewPassword string `json:"new_password"`
}