| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package auth
- import (
- "context"
- "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"
- "perms-system-server/internal/util"
- "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 msg := util.ValidatePassword(req.NewPassword); msg != "" {
- return response.ErrBadRequest(msg)
- }
- 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
- }
- if err := l.svcCtx.SysUserModel.UpdatePassword(l.ctx, userId, string(hashed), consts.MustChangePasswordNo); err != nil {
- return err
- }
- l.svcCtx.UserDetailsLoader.Clean(l.ctx, userId)
- return nil
- }
|