changePasswordLogic.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. // ChangePassword 修改密码。已登录用户验证原密码后设置新密码,同时递增 tokenVersion 使所有已签发令牌失效,强制重新登录。
  26. func (l *ChangePasswordLogic) ChangePassword(req *types.ChangePasswordReq) error {
  27. if msg := util.ValidatePassword(req.NewPassword); msg != "" {
  28. return response.ErrBadRequest(msg)
  29. }
  30. userId := middleware.GetUserId(l.ctx)
  31. user, err := l.svcCtx.SysUserModel.FindOne(l.ctx, userId)
  32. if err != nil {
  33. return response.ErrNotFound("用户不存在")
  34. }
  35. if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
  36. return response.ErrBadRequest("原密码错误")
  37. }
  38. if req.OldPassword == req.NewPassword {
  39. return response.ErrBadRequest("新密码不能与原密码相同")
  40. }
  41. hashed, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
  42. if err != nil {
  43. return err
  44. }
  45. if err := l.svcCtx.SysUserModel.UpdatePassword(l.ctx, userId, string(hashed), consts.MustChangePasswordNo); err != nil {
  46. return err
  47. }
  48. l.svcCtx.UserDetailsLoader.Clean(l.ctx, userId)
  49. return nil
  50. }