changePasswordLogic.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. "github.com/zeromicro/go-zero/core/logx"
  10. "golang.org/x/crypto/bcrypt"
  11. )
  12. type ChangePasswordLogic struct {
  13. logx.Logger
  14. ctx context.Context
  15. svcCtx *svc.ServiceContext
  16. }
  17. func NewChangePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangePasswordLogic {
  18. return &ChangePasswordLogic{
  19. Logger: logx.WithContext(ctx),
  20. ctx: ctx,
  21. svcCtx: svcCtx,
  22. }
  23. }
  24. func (l *ChangePasswordLogic) ChangePassword(req *types.ChangePasswordReq) error {
  25. if len(req.NewPassword) < 6 {
  26. return response.ErrBadRequest("密码长度不能少于6个字符")
  27. }
  28. if len(req.NewPassword) > 72 {
  29. return response.ErrBadRequest("密码长度不能超过72个字符")
  30. }
  31. userId := middleware.GetUserId(l.ctx)
  32. user, err := l.svcCtx.SysUserModel.FindOne(l.ctx, userId)
  33. if err != nil {
  34. return response.ErrNotFound("用户不存在")
  35. }
  36. if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
  37. return response.ErrBadRequest("原密码错误")
  38. }
  39. if req.OldPassword == req.NewPassword {
  40. return response.ErrBadRequest("新密码不能与原密码相同")
  41. }
  42. hashed, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
  43. if err != nil {
  44. return err
  45. }
  46. if err := l.svcCtx.SysUserModel.UpdatePassword(l.ctx, userId, string(hashed), consts.MustChangePasswordNo); err != nil {
  47. return err
  48. }
  49. l.svcCtx.UserDetailsLoader.Clean(l.ctx, userId)
  50. return nil
  51. }