All checks were successful
Build docker and publish / build (20.15.1) (push) Successful in 7m41s
修改绑定邮箱接口返回登录凭证,优化用户数据迁移流程 添加用户缓存清理逻辑,确保设备绑定后数据一致性 完善邮箱验证和绑定逻辑的注释和错误处理
83 lines
2.9 KiB
Go
83 lines
2.9 KiB
Go
package user
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/perfect-panel/server/pkg/constant"
|
|
|
|
"github.com/perfect-panel/server/internal/model/user"
|
|
"github.com/perfect-panel/server/pkg/xerr"
|
|
"github.com/pkg/errors"
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/perfect-panel/server/internal/svc"
|
|
"github.com/perfect-panel/server/internal/types"
|
|
"github.com/perfect-panel/server/pkg/logger"
|
|
)
|
|
|
|
type UpdateBindEmailLogic struct {
|
|
logger.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
// NewUpdateBindEmailLogic Update Bind Email
|
|
func NewUpdateBindEmailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateBindEmailLogic {
|
|
return &UpdateBindEmailLogic{
|
|
Logger: logger.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
// UpdateBindEmail 更新用户绑定的邮箱地址
|
|
// 该方法用于用户更新或绑定新的邮箱地址,支持首次绑定和修改已绑定邮箱
|
|
func (l *UpdateBindEmailLogic) UpdateBindEmail(req *types.UpdateBindEmailRequest) error {
|
|
// 从上下文中获取当前用户信息
|
|
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
|
|
if !ok {
|
|
logger.Error("current user is not found in context")
|
|
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
|
}
|
|
|
|
// 查询当前用户是否已有邮箱认证方式
|
|
method, err := l.svcCtx.UserModel.FindUserAuthMethodByUserId(l.ctx, "email", u.Id)
|
|
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindUserAuthMethodByOpenID error")
|
|
}
|
|
|
|
// 检查要绑定的邮箱是否已被其他用户使用
|
|
m, err := l.svcCtx.UserModel.FindUserAuthMethodByOpenID(l.ctx, "email", req.Email)
|
|
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindUserAuthMethodByOpenID error")
|
|
}
|
|
|
|
// 如果邮箱已被绑定,返回错误
|
|
if m.Id > 0 {
|
|
return errors.Wrapf(xerr.NewErrCode(xerr.UserExist), "email already bind")
|
|
}
|
|
|
|
// 如果用户还没有邮箱认证方式,创建新的认证记录
|
|
if method.Id == 0 {
|
|
method = &user.AuthMethods{
|
|
UserId: u.Id, // 用户ID
|
|
AuthType: "email", // 认证类型为邮箱
|
|
AuthIdentifier: req.Email, // 邮箱地址
|
|
Verified: false, // 初始状态为未验证
|
|
}
|
|
// 插入新的认证方式记录
|
|
if err := l.svcCtx.UserModel.InsertUserAuthMethods(l.ctx, method); err != nil {
|
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "InsertUserAuthMethods error")
|
|
}
|
|
} else {
|
|
// 如果用户已有邮箱认证方式,更新邮箱地址
|
|
method.Verified = false // 重置验证状态
|
|
method.AuthIdentifier = req.Email // 更新邮箱地址
|
|
// 更新认证方式记录
|
|
if err := l.svcCtx.UserModel.UpdateUserAuthMethods(l.ctx, method); err != nil {
|
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "UpdateUserAuthMethods error")
|
|
}
|
|
}
|
|
return nil
|
|
}
|