You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
1.7 KiB
73 lines
1.7 KiB
package profile
|
|
|
|
import (
|
|
"context"
|
|
"crypto/md5"
|
|
"fmt"
|
|
|
|
"github.com/youruser/base/internal/svc"
|
|
"github.com/youruser/base/internal/types"
|
|
"github.com/youruser/base/model"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
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.ChangePasswordRequest) (resp *types.Response, err error) {
|
|
// 从上下文中获取当前用户ID
|
|
userIdValue := l.ctx.Value("userId")
|
|
if userIdValue == nil {
|
|
return nil, fmt.Errorf("未获取到用户信息,请先登录")
|
|
}
|
|
userId, ok := userIdValue.(int64)
|
|
if !ok {
|
|
return nil, fmt.Errorf("用户ID格式错误")
|
|
}
|
|
|
|
// 查询用户
|
|
user, err := model.FindOne(l.ctx, l.svcCtx.DB, userId)
|
|
if err != nil {
|
|
if err == model.ErrNotFound {
|
|
return nil, fmt.Errorf("用户不存在")
|
|
}
|
|
return nil, fmt.Errorf("查询用户失败: %v", err)
|
|
}
|
|
|
|
// 加密旧密码
|
|
oldEncrypted := fmt.Sprintf("%x", md5.Sum([]byte(req.OldPassword)))
|
|
if user.Password != oldEncrypted {
|
|
return &types.Response{
|
|
Code: 400,
|
|
Message: "旧密码错误",
|
|
}, nil
|
|
}
|
|
|
|
// 加密新密码
|
|
newEncrypted := fmt.Sprintf("%x", md5.Sum([]byte(req.NewPassword)))
|
|
user.Password = newEncrypted
|
|
|
|
// 更新数据库
|
|
err = model.Update(l.ctx, l.svcCtx.DB, user)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("修改密码失败: %v", err)
|
|
}
|
|
|
|
return &types.Response{
|
|
Code: 200,
|
|
Message: "修改密码成功",
|
|
}, nil
|
|
}
|
|
|