changePasswordLogic.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package auth
  2. import (
  3. "context"
  4. "fmt"
  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. "perms-system-server/internal/util"
  11. "github.com/zeromicro/go-zero/core/limit"
  12. "github.com/zeromicro/go-zero/core/logx"
  13. "golang.org/x/crypto/bcrypt"
  14. )
  15. type ChangePasswordLogic struct {
  16. logx.Logger
  17. ctx context.Context
  18. svcCtx *svc.ServiceContext
  19. }
  20. func NewChangePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangePasswordLogic {
  21. return &ChangePasswordLogic{
  22. Logger: logx.WithContext(ctx),
  23. ctx: ctx,
  24. svcCtx: svcCtx,
  25. }
  26. }
  27. // ChangePassword 修改密码。已登录用户验证原密码后设置新密码,同时递增 tokenVersion 使所有已签发令牌失效,强制重新登录。
  28. func (l *ChangePasswordLogic) ChangePassword(req *types.ChangePasswordReq) error {
  29. if msg := util.ValidatePassword(req.NewPassword); msg != "" {
  30. return response.ErrBadRequest(msg)
  31. }
  32. userId := middleware.GetUserId(l.ctx)
  33. if l.svcCtx.TokenOpLimiter != nil {
  34. code, _ := l.svcCtx.TokenOpLimiter.Take(fmt.Sprintf("chpwd:%d", userId))
  35. if code == limit.OverQuota {
  36. return response.ErrTooManyRequests("操作过于频繁,请稍后再试")
  37. }
  38. }
  39. user, err := l.svcCtx.SysUserModel.FindOne(l.ctx, userId)
  40. if err != nil {
  41. return response.ErrNotFound("用户不存在")
  42. }
  43. if user.Status != consts.StatusEnabled {
  44. return response.ErrForbidden("账号已被冻结")
  45. }
  46. if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
  47. logx.WithContext(l.ctx).Infof("change-password old-password mismatch userId=%d", userId)
  48. return response.ErrBadRequest("原密码错误")
  49. }
  50. if req.OldPassword == req.NewPassword {
  51. return response.ErrBadRequest("新密码不能与原密码相同")
  52. }
  53. hashed, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
  54. if err != nil {
  55. return err
  56. }
  57. if err := l.svcCtx.SysUserModel.UpdatePassword(l.ctx, userId, string(hashed), consts.MustChangePasswordNo); err != nil {
  58. return err
  59. }
  60. l.svcCtx.UserDetailsLoader.Clean(l.ctx, userId)
  61. return nil
  62. }