| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package auth
- import (
- "context"
- "time"
- "perms-system-server/internal/consts"
- "perms-system-server/internal/middleware"
- "perms-system-server/internal/response"
- "perms-system-server/internal/svc"
- "perms-system-server/internal/types"
- "github.com/zeromicro/go-zero/core/logx"
- "golang.org/x/crypto/bcrypt"
- )
- type ChangePasswordLogic struct {
- logx.Logger
- ctx context.Context
- svcCtx *svc.ServiceContext
- }
- func NewChangePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangePasswordLogic {
- return &ChangePasswordLogic{
- Logger: logx.WithContext(ctx),
- ctx: ctx,
- svcCtx: svcCtx,
- }
- }
- func (l *ChangePasswordLogic) ChangePassword(req *types.ChangePasswordReq) error {
- if len(req.NewPassword) < 6 {
- return response.ErrBadRequest("密码长度不能少于6个字符")
- }
- if len(req.NewPassword) > 72 {
- return response.ErrBadRequest("密码长度不能超过72个字符")
- }
- userId := middleware.GetUserId(l.ctx)
- user, err := l.svcCtx.SysUserModel.FindOne(l.ctx, userId)
- if err != nil {
- return response.ErrNotFound("用户不存在")
- }
- if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
- return response.ErrBadRequest("原密码错误")
- }
- if req.OldPassword == req.NewPassword {
- return response.ErrBadRequest("新密码不能与原密码相同")
- }
- hashed, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
- if err != nil {
- return err
- }
- user.Password = string(hashed)
- user.MustChangePassword = consts.MustChangePasswordNo
- user.UpdateTime = time.Now().Unix()
- if err := l.svcCtx.SysUserModel.Update(l.ctx, user); err != nil {
- return err
- }
- l.svcCtx.UserDetailsLoader.Clean(l.ctx, userId)
- return nil
- }
|