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

新增绑定邮箱和密码的接口,用于设备用户绑定已有邮箱账户
新增绑定邀请码接口,绑定成功后会为双方赠送订阅天数
修复API定义中的格式问题,统一缩进和对齐
移除不再使用的WebSocket路由
This commit is contained in:
shanshanzhong 2025-10-22 03:45:07 -07:00
parent b0cf0c4e3c
commit b0a03401b8
15 changed files with 410 additions and 98 deletions

View File

@ -19,8 +19,8 @@ type (
Periods []TimePeriod `json:"periods"`
}
PreViewNodeMultiplierResponse {
CurrentTime string `json:"current_time"`
Ratio float32 `json:"ratio"`
CurrentTime string `json:"current_time"`
Ratio float32 `json:"ratio"`
}
)

View File

@ -16,7 +16,7 @@ type (
Password string `json:"password" validate:"required"`
IP string `header:"X-Original-Forwarded-For"`
UserAgent string `header:"User-Agent"`
LoginType string `header:"Login-Type"`
LoginType string `header:"Login-Type"`
CfToken string `json:"cf_token,optional"`
}
// Check user is exist request
@ -36,19 +36,19 @@ type (
Code string `json:"code,optional"`
IP string `header:"X-Original-Forwarded-For"`
UserAgent string `header:"User-Agent"`
LoginType string `header:"Login-Type"`
LoginType string `header:"Login-Type"`
CfToken string `json:"cf_token,optional"`
}
// User login response
ResetPasswordRequest {
Identifier string `json:"identifier"`
Email string `json:"email" validate:"required"`
Password string `json:"password" validate:"required"`
Code string `json:"code,optional"`
IP string `header:"X-Original-Forwarded-For"`
UserAgent string `header:"User-Agent"`
LoginType string `header:"Login-Type"`
CfToken string `json:"cf_token,optional"`
Identifier string `json:"identifier"`
Email string `json:"email" validate:"required"`
Password string `json:"password" validate:"required"`
Code string `json:"code,optional"`
IP string `header:"X-Original-Forwarded-For"`
UserAgent string `header:"User-Agent"`
LoginType string `header:"Login-Type"`
CfToken string `json:"cf_token,optional"`
}
LoginResponse {
Token string `json:"token"`
@ -73,7 +73,7 @@ type (
Password string `json:"password"`
IP string `header:"X-Original-Forwarded-For"`
UserAgent string `header:"User-Agent"`
LoginType string `header:"Login-Type"`
LoginType string `header:"Login-Type"`
CfToken string `json:"cf_token,optional"`
}
// Check user is exist request
@ -95,19 +95,19 @@ type (
Code string `json:"code,optional"`
IP string `header:"X-Original-Forwarded-For"`
UserAgent string `header:"User-Agent"`
LoginType string `header:"Login-Type,optional"`
LoginType string `header:"Login-Type,optional"`
CfToken string `json:"cf_token,optional"`
}
// User login response
TelephoneResetPasswordRequest {
Identifier string `json:"identifier"`
Identifier string `json:"identifier"`
Telephone string `json:"telephone" validate:"required"`
TelephoneAreaCode string `json:"telephone_area_code" validate:"required"`
Password string `json:"password" validate:"required"`
Code string `json:"code,optional"`
IP string `header:"X-Original-Forwarded-For"`
UserAgent string `header:"User-Agent"`
LoginType string `header:"Login-Type,optional"`
LoginType string `header:"Login-Type,optional"`
CfToken string `json:"cf_token,optional"`
}
AppleLoginCallbackRequest {
@ -128,9 +128,9 @@ type (
)
@server (
prefix: v1/auth
group: auth
middleware: DeviceMiddleware
prefix: v1/auth
group: auth
middleware: DeviceMiddleware
)
service ppanel {
@doc "User login"

View File

@ -90,9 +90,9 @@ type (
)
@server (
prefix: v1/common
group: common
middleware: DeviceMiddleware
prefix: v1/common
group: common
middleware: DeviceMiddleware
)
service ppanel {
@doc "Get global config"

View File

@ -68,9 +68,9 @@ type (
)
@server (
prefix: v1/public/portal
group: public/portal
middleware: DeviceMiddleware
prefix: v1/public/portal
group: public/portal
middleware: DeviceMiddleware
)
service ppanel {
@doc "Get available payment methods"

View File

@ -14,43 +14,40 @@ type (
QuerySubscribeListRequest {
Language string `form:"language"`
}
QueryUserSubscribeNodeListResponse {
List []UserSubscribeInfo `json:"list"`
}
UserSubscribeInfo {
Id int64 `json:"id"`
UserId int64 `json:"user_id"`
OrderId int64 `json:"order_id"`
SubscribeId int64 `json:"subscribe_id"`
StartTime int64 `json:"start_time"`
ExpireTime int64 `json:"expire_time"`
FinishedAt int64 `json:"finished_at"`
ResetTime int64 `json:"reset_time"`
Traffic int64 `json:"traffic"`
Download int64 `json:"download"`
Upload int64 `json:"upload"`
Token string `json:"token"`
Status uint8 `json:"status"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
IsTryOut bool `json:"is_try_out"`
Nodes []*UserSubscribeNodeInfo `json:"nodes"`
}
UserSubscribeNodeInfo{
Id int64 `json:"id"`
Name string `json:"name"`
Uuid string `json:"uuid"`
Protocol string `json:"protocol"`
Port uint16 `json:"port"`
Address string `json:"address"`
Tags []string `json:"tags"`
Country string `json:"country"`
City string `json:"city"`
CreatedAt int64 `json:"created_at"`
}
QueryUserSubscribeNodeListResponse {
List []UserSubscribeInfo `json:"list"`
}
UserSubscribeInfo {
Id int64 `json:"id"`
UserId int64 `json:"user_id"`
OrderId int64 `json:"order_id"`
SubscribeId int64 `json:"subscribe_id"`
StartTime int64 `json:"start_time"`
ExpireTime int64 `json:"expire_time"`
FinishedAt int64 `json:"finished_at"`
ResetTime int64 `json:"reset_time"`
Traffic int64 `json:"traffic"`
Download int64 `json:"download"`
Upload int64 `json:"upload"`
Token string `json:"token"`
Status uint8 `json:"status"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
IsTryOut bool `json:"is_try_out"`
Nodes []*UserSubscribeNodeInfo `json:"nodes"`
}
UserSubscribeNodeInfo {
Id int64 `json:"id"`
Name string `json:"name"`
Uuid string `json:"uuid"`
Protocol string `json:"protocol"`
Port uint16 `json:"port"`
Address string `json:"address"`
Tags []string `json:"tags"`
Country string `json:"country"`
City string `json:"city"`
CreatedAt int64 `json:"created_at"`
}
)
@server (
@ -63,8 +60,8 @@ service ppanel {
@handler QuerySubscribeList
get /list (QuerySubscribeListRequest) returns (QuerySubscribeListResponse)
@doc "Get user subscribe node info"
@handler QueryUserSubscribeNodeList
get /node/list returns (QueryUserSubscribeNodeListResponse)
@doc "Get user subscribe node info"
@handler QueryUserSubscribeNodeList
get /node/list returns (QueryUserSubscribeNodeListResponse)
}

View File

@ -93,19 +93,24 @@ type (
UpdateBindEmailRequest {
Email string `json:"email" validate:"required"`
}
BindEmailWithPasswordRequest {
Email string `json:"email" validate:"required"`
Password string `json:"password" validate:"required"`
}
BindInviteCodeRequest {
InviteCode string `json:"invite_code" validate:"required"`
}
VerifyEmailRequest {
Email string `json:"email" validate:"required"`
Code string `json:"code" validate:"required"`
}
GetDeviceListResponse {
List []UserDevice `json:"list"`
Total int64 `json:"total"`
}
UnbindDeviceRequest {
Id int64 `json:"id" validate:"required"`
}
GetDeviceListResponse {
List []UserDevice `json:"list"`
Total int64 `json:"total"`
}
UnbindDeviceRequest {
Id int64 `json:"id" validate:"required"`
}
)
@server (
@ -202,12 +207,20 @@ service ppanel {
@handler UpdateBindEmail
put /bind_email (UpdateBindEmailRequest)
@doc "Get Device List"
@handler GetDeviceList
get /devices returns (GetDeviceListResponse)
@doc "Bind Email With Password"
@handler BindEmailWithPassword
post /bind_email_with_password (BindEmailWithPasswordRequest)
@doc "Unbind Device"
@handler UnbindDevice
put /unbind_device (UnbindDeviceRequest)
@doc "Bind Invite Code"
@handler BindInviteCode
post /bind_invite_code (BindInviteCodeRequest)
@doc "Get Device List"
@handler GetDeviceList
get /devices returns (GetDeviceListResponse)
@doc "Unbind Device"
@handler UnbindDevice
put /unbind_device (UnbindDeviceRequest)
}

View File

@ -115,7 +115,7 @@ type (
AuthConfig {
Mobile MobileAuthenticateConfig `json:"mobile"`
Email EmailAuthticateConfig `json:"email"`
Device DeviceAuthticateConfig `json:"device"`
Device DeviceAuthticateConfig `json:"device"`
Register PubilcRegisterConfig `json:"register"`
}
PubilcRegisterConfig {
@ -135,14 +135,12 @@ type (
EnableDomainSuffix bool `json:"enable_domain_suffix"`
DomainSuffixList string `json:"domain_suffix_list"`
}
DeviceAuthticateConfig {
Enable bool `json:"enable"`
ShowAds bool `json:"show_ads"`
EnableSecurity bool `json:"enable_security"`
OnlyRealDevice bool `json:"only_real_device"`
}
DeviceAuthticateConfig {
Enable bool `json:"enable"`
ShowAds bool `json:"show_ads"`
EnableSecurity bool `json:"enable_security"`
OnlyRealDevice bool `json:"only_real_device"`
}
RegisterConfig {
StopRegister bool `json:"stop_register"`
EnableTrial bool `json:"enable_trial"`
@ -674,7 +672,6 @@ type (
List []SubscribeGroup `json:"list"`
Total int64 `json:"total"`
}
GetUserSubscribeTrafficLogsRequest {
Page int `form:"page"`
Size int `form:"size"`

View File

@ -0,0 +1,26 @@
package user
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/public/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// Bind Email With Password
func BindEmailWithPasswordHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.BindEmailWithPasswordRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := user.NewBindEmailWithPasswordLogic(c.Request.Context(), svcCtx)
err := l.BindEmailWithPassword(&req)
result.HttpResult(c, nil, err)
}
}

View File

@ -0,0 +1,26 @@
package user
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/public/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// Bind Invite Code
func BindInviteCodeHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.BindInviteCodeRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := user.NewBindInviteCodeLogic(c.Request.Context(), svcCtx)
err := l.BindInviteCode(&req)
result.HttpResult(c, nil, err)
}
}

View File

@ -22,7 +22,6 @@ import (
adminTicket "github.com/perfect-panel/server/internal/handler/admin/ticket"
adminTool "github.com/perfect-panel/server/internal/handler/admin/tool"
adminUser "github.com/perfect-panel/server/internal/handler/admin/user"
app "github.com/perfect-panel/server/internal/handler/app"
auth "github.com/perfect-panel/server/internal/handler/auth"
authOauth "github.com/perfect-panel/server/internal/handler/auth/oauth"
common "github.com/perfect-panel/server/internal/handler/common"
@ -781,6 +780,12 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Update Bind Email
publicUserGroupRouter.PUT("/bind_email", publicUser.UpdateBindEmailHandler(serverCtx))
// Bind Email With Password
publicUserGroupRouter.POST("/bind_email_with_password", publicUser.BindEmailWithPasswordHandler(serverCtx))
// Bind Invite Code
publicUserGroupRouter.POST("/bind_invite_code", publicUser.BindInviteCodeHandler(serverCtx))
// Update Bind Mobile
publicUserGroupRouter.PUT("/bind_mobile", publicUser.UpdateBindMobileHandler(serverCtx))
@ -868,11 +873,4 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Get Server Protocol Config
serverGroupRouterV2.GET("/:server_id", server.QueryServerProtocolConfigHandler(serverCtx))
}
// App WebSocket routes
appGroupRouter := router.Group("/v1/app")
{
// Device WebSocket connection
appGroupRouter.GET("/ws/:userid/:device_number", app.DeviceWebSocketHandler(serverCtx))
}
}

View File

@ -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
}

View File

@ -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
}

View File

@ -178,6 +178,15 @@ type BatchSendEmailTask struct {
UpdatedAt int64 `json:"updated_at"`
}
type BindEmailWithPasswordRequest struct {
Email string `json:"email" validate:"required"`
Password string `json:"password" validate:"required"`
}
type BindInviteCodeRequest struct {
InviteCode string `json:"invite_code" validate:"required"`
}
type BindOAuthCallbackRequest struct {
Method string `json:"method"`
Callback interface{} `json:"callback"`

Binary file not shown.

BIN
server Executable file

Binary file not shown.