changePasswordLogic.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package auth
  2. import (
  3. "context"
  4. "perms-system-server/internal/consts"
  5. "perms-system-server/internal/middleware"
  6. "perms-system-server/internal/response"
  7. "perms-system-server/internal/svc"
  8. "perms-system-server/internal/types"
  9. "perms-system-server/internal/util"
  10. "github.com/zeromicro/go-zero/core/logx"
  11. "golang.org/x/crypto/bcrypt"
  12. )
  13. type ChangePasswordLogic struct {
  14. logx.Logger
  15. ctx context.Context
  16. svcCtx *svc.ServiceContext
  17. }
  18. func NewChangePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangePasswordLogic {
  19. return &ChangePasswordLogic{
  20. Logger: logx.WithContext(ctx),
  21. ctx: ctx,
  22. svcCtx: svcCtx,
  23. }
  24. }
  25. func (l *ChangePasswordLogic) ChangePassword(req *types.ChangePasswordReq) error {
  26. if msg := util.ValidatePassword(req.NewPassword); msg != "" {
  27. return response.ErrBadRequest(msg)
  28. }
  29. userId := middleware.GetUserId(l.ctx)
  30. user, err := l.svcCtx.SysUserModel.FindOne(l.ctx, userId)
  31. if err != nil {
  32. return response.ErrNotFound("用户不存在")
  33. }
  34. if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
  35. return response.ErrBadRequest("原密码错误")
  36. }
  37. if req.OldPassword == req.NewPassword {
  38. return response.ErrBadRequest("新密码不能与原密码相同")
  39. }
  40. hashed, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
  41. if err != nil {
  42. return err
  43. }
  44. if err := l.svcCtx.SysUserModel.UpdatePassword(l.ctx, userId, string(hashed), consts.MustChangePasswordNo); err != nil {
  45. return err
  46. }
  47. l.svcCtx.UserDetailsLoader.Clean(l.ctx, userId)
  48. return nil
  49. }