changePasswordLogic.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package auth
  2. import (
  3. "context"
  4. "time"
  5. "perms-system-server/internal/consts"
  6. "perms-system-server/internal/middleware"
  7. "perms-system-server/internal/response"
  8. "perms-system-server/internal/svc"
  9. "perms-system-server/internal/types"
  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 len(req.NewPassword) < 6 {
  27. return response.ErrBadRequest("密码长度不能少于6个字符")
  28. }
  29. if len(req.NewPassword) > 72 {
  30. return response.ErrBadRequest("密码长度不能超过72个字符")
  31. }
  32. userId := middleware.GetUserId(l.ctx)
  33. user, err := l.svcCtx.SysUserModel.FindOne(l.ctx, userId)
  34. if err != nil {
  35. return response.ErrNotFound("用户不存在")
  36. }
  37. if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
  38. return response.ErrBadRequest("原密码错误")
  39. }
  40. if req.OldPassword == req.NewPassword {
  41. return response.ErrBadRequest("新密码不能与原密码相同")
  42. }
  43. hashed, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
  44. if err != nil {
  45. return err
  46. }
  47. user.Password = string(hashed)
  48. user.MustChangePassword = consts.MustChangePasswordNo
  49. user.UpdateTime = time.Now().Unix()
  50. if err := l.svcCtx.SysUserModel.Update(l.ctx, user); err != nil {
  51. return err
  52. }
  53. l.svcCtx.UserDetailsLoader.Clean(l.ctx, userId)
  54. return nil
  55. }