From df30d7b549ae36b9e69b20149db18843308e7d37 Mon Sep 17 00:00:00 2001 From: Leon <147289645+LeoninCS@users.noreply.github.com> Date: Fri, 5 Dec 2025 13:10:19 +0800 Subject: [PATCH] feat: hash user password and update by username --- internal/account/service.go | 15 +++++++++++++-- internal/http/account_handler.go | 3 ++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/internal/account/service.go b/internal/account/service.go index 0e4c3ce..59b609b 100644 --- a/internal/account/service.go +++ b/internal/account/service.go @@ -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 diff --git a/internal/http/account_handler.go b/internal/http/account_handler.go index 7e54b40..baf386e 100644 --- a/internal/http/account_handler.go +++ b/internal/http/account_handler.go @@ -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"` }