feat(用户): 添加通过密码绑定邮箱和邀请码功能
Build docker and publish / build (20.15.1) (push) Successful in 7m31s

新增绑定邮箱和密码的接口,用于设备用户绑定已有邮箱账户
新增绑定邀请码接口,绑定成功后会为双方赠送订阅天数
修复API定义中的格式问题,统一缩进和对齐
移除不再使用的WebSocket路由
This commit is contained in:
2025-10-22 03:45:07 -07:00
parent b0cf0c4e3c
commit b0a03401b8
15 changed files with 410 additions and 98 deletions
@@ -0,0 +1,126 @@
package user
import (
"context"
"github.com/perfect-panel/server/internal/logic/auth"
"github.com/perfect-panel/server/pkg/constant"
"github.com/perfect-panel/server/pkg/tool"
"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 BindEmailWithPasswordLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// NewBindEmailWithPasswordLogic Bind Email With Password
func NewBindEmailWithPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindEmailWithPasswordLogic {
return &BindEmailWithPasswordLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *BindEmailWithPasswordLogic) BindEmailWithPassword(req *types.BindEmailWithPasswordRequest) error {
// 获取当前设备用户
currentUser, 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")
}
// 验证邮箱和密码是否匹配现有用户
emailUser, err := l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "email not registered: %v", req.Email)
}
logger.WithContext(l.ctx).Error(err)
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user by email failed: %v", err.Error())
}
// 验证密码
if !tool.VerifyPassWord(req.Password, emailUser.Password) {
return errors.Wrapf(xerr.NewErrCode(xerr.UserPasswordError), "password incorrect")
}
// 检查当前用户是否已经绑定了邮箱
currentEmailMethod, err := l.svcCtx.UserModel.FindUserAuthMethodByUserId(l.ctx, "email", currentUser.Id)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindUserAuthMethodByUserId error")
}
// 如果当前用户已经绑定了邮箱,不允许重复绑定
if currentEmailMethod.Id > 0 {
return errors.Wrapf(xerr.NewErrCode(xerr.UserExist), "current user already has email bound")
}
// 检查该邮箱是否已经被其他用户绑定
existingEmailMethod, 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 existingEmailMethod.Id > 0 && existingEmailMethod.UserId != currentUser.Id {
// 调用设备绑定逻辑,这会触发数据迁移
bindLogic := auth.NewBindDeviceLogic(l.ctx, l.svcCtx)
// 获取当前用户的设备标识符
deviceMethod, err := l.svcCtx.UserModel.FindUserAuthMethodByUserId(l.ctx, "device", currentUser.Id)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindUserAuthMethodByUserId device error")
}
if deviceMethod.Id == 0 {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "current user has no device identifier")
}
// 执行设备重新绑定,这会触发数据迁移
if err := bindLogic.BindDeviceToUser(deviceMethod.AuthIdentifier, "", "", emailUser.Id); err != nil {
l.Errorw("failed to bind device to email user",
logger.Field("current_user_id", currentUser.Id),
logger.Field("email_user_id", emailUser.Id),
logger.Field("device_identifier", deviceMethod.AuthIdentifier),
logger.Field("error", err.Error()),
)
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "bind device to email user failed")
}
l.Infow("successfully bound device to email user with data migration",
logger.Field("current_user_id", currentUser.Id),
logger.Field("email_user_id", emailUser.Id),
logger.Field("device_identifier", deviceMethod.AuthIdentifier),
)
} else {
// 邮箱未被绑定,直接为当前用户创建邮箱绑定
emailMethod := &user.AuthMethods{
UserId: currentUser.Id,
AuthType: "email",
AuthIdentifier: req.Email,
Verified: true, // 通过密码验证,直接设为已验证
}
if err := l.svcCtx.UserModel.InsertUserAuthMethods(l.ctx, emailMethod); err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "InsertUserAuthMethods error")
}
l.Infow("successfully bound email to current user",
logger.Field("user_id", currentUser.Id),
logger.Field("email", req.Email),
)
}
return nil
}
@@ -0,0 +1,120 @@
package user
import (
"context"
"time"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/constant"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type BindInviteCodeLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// Bind Invite Code
func NewBindInviteCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindInviteCodeLogic {
return &BindInviteCodeLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *BindInviteCodeLogic) BindInviteCode(req *types.BindInviteCodeRequest) error {
// 获取当前用户
currentUser, 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")
}
// 检查用户是否已经绑定过邀请码
if currentUser.RefererId != 0 {
return errors.Wrapf(xerr.NewErrCode(xerr.UserExist), "user already bound invite code")
}
// 查找邀请人
referrer, err := l.svcCtx.UserModel.FindOneByReferCode(l.ctx, req.InviteCode)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "invite code not found")
}
logger.WithContext(l.ctx).Error(err)
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query referrer failed: %v", err.Error())
}
// 检查是否是自己的邀请码
if referrer.Id == currentUser.Id {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "cannot bind your own invite code")
}
// 更新用户的RefererId
currentUser.RefererId = referrer.Id
err = l.svcCtx.UserModel.Update(l.ctx, currentUser)
if err != nil {
logger.WithContext(l.ctx).Error(err)
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update referrer id failed: %v", err.Error())
}
// 给双方赠送天数
err = l.grantGiftDaysToBothParties(currentUser, referrer)
if err != nil {
logger.WithContext(l.ctx).Error(err)
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "grant gift days failed: %v", err.Error())
}
return nil
}
// grantGiftDaysToBothParties 给双方赠送天数
func (l *BindInviteCodeLogic) grantGiftDaysToBothParties(referee *user.User, referrer *user.User) error {
giftDays := l.svcCtx.Config.Invite.GiftDays
// 给被邀请人赠送天数
err := l.grantGiftDays(referee, int(giftDays))
if err != nil {
return err
}
// 给邀请人赠送天数
err = l.grantGiftDays(referrer, int(giftDays))
if err != nil {
return err
}
return nil
}
// grantGiftDays 给用户赠送天数
func (l *BindInviteCodeLogic) grantGiftDays(user *user.User, days int) error {
// 查找用户的活跃订阅
activeSubscribe, err := l.svcCtx.UserModel.FindActiveSubscribe(l.ctx, user.Id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
// 用户没有活跃订阅,跳过赠送
logger.WithContext(l.ctx).Infof("user %d has no active subscription, skip gift days", user.Id)
return nil
}
return err
}
// 延长订阅时间
newExpiredAt := activeSubscribe.ExpireTime.Add(time.Duration(days) * 24 * time.Hour)
activeSubscribe.ExpireTime = newExpiredAt
err = l.svcCtx.UserModel.UpdateSubscribe(l.ctx, activeSubscribe)
if err != nil {
return err
}
logger.WithContext(l.ctx).Infof("granted %d days to user %d, new expired at: %v", days, user.Id, newExpiredAt)
return nil
}