package auth import ( "context" "encoding/json" "fmt" "time" "github.com/perfect-panel/server/internal/config" "github.com/perfect-panel/server/internal/logic/common" "github.com/perfect-panel/server/internal/model/log" "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/jwt" "github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/tool" "github.com/perfect-panel/server/pkg/uuidx" "github.com/perfect-panel/server/pkg/xerr" "github.com/pkg/errors" "gorm.io/gorm" ) type EmailLoginLogic struct { logger.Logger ctx context.Context svcCtx *svc.ServiceContext } // NewEmailLoginLogic Email verify code login func NewEmailLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EmailLoginLogic { return &EmailLoginLogic{ Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *EmailLoginLogic) EmailLogin(req *types.EmailLoginRequest) (resp *types.LoginResponse, err error) { loginStatus := false var userInfo *user.User var isNewUser bool // Verify Code // Using "Security" type or "Register"? Since it can be used for both, we need to know what the frontend requested. // But usually, the "Get Code" interface requires a "type". // If the user doesn't exist, they probably requested "Register" code or "Login" code? // Let's assume the frontend requests a "Security" code or a specific "Login" code. // However, looking at resetPasswordLogic, it uses `constant.Security`. // Looking at userRegisterLogic, it uses `constant.Register`. // Since this is a "Login" interface, but implicitly registers, we might need to check which code was sent. // Or, more robustly, we check both? Or we decide on one. // Usually "Login" implies "Security" or "Login" type. // If we assume the user calls `/verify/email` with type "login" (if it exists) or "register". // For simplicity, let's assume `constant.Security` (Common for login) or we need to support `constant.Register` if it's a new user flow? // User flow: // 1. Enter Email -> Click "Get Code". The type sent to "Get Code" determines the Redis key. // DOES the frontend know if the user exists? Probably not (Privacy). // So the frontend probably sends type="login" (or similar). // Let's check `constant` package for available types? I don't see it. // Assuming `constant.Security` for generic verification. scenes := []string{constant.Security.String(), constant.Register.String()} var verified bool var cacheKeyUsed string var payload common.CacheKeyPayload for _, scene := range scenes { cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeCacheKey, scene, req.Email) value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result() if err != nil || value == "" { continue } if err := json.Unmarshal([]byte(value), &payload); err != nil { continue } if payload.Code == req.Code && time.Now().Unix()-payload.LastAt <= l.svcCtx.Config.VerifyCode.ExpireTime { verified = true cacheKeyUsed = cacheKey break } } if !verified { return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verification code error or expired") } l.svcCtx.Redis.Del(l.ctx, cacheKeyUsed) // Check User userInfo, err = l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email) if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user info failed: %v", err.Error()) } if userInfo == nil || errors.Is(err, gorm.ErrRecordNotFound) { // Auto Register isNewUser = true c := l.svcCtx.Config.Register if c.StopRegister { return nil, errors.Wrapf(xerr.NewErrCode(xerr.StopRegister), "user not found and registration is stopped") } var referer *user.User if req.Invite == "" { if l.svcCtx.Config.Invite.ForcedInvite { return nil, errors.Wrapf(xerr.NewErrCode(xerr.InviteCodeError), "invite code is required for new user") } } else { referer, err = l.svcCtx.UserModel.FindOneByReferCode(l.ctx, req.Invite) if err != nil { return nil, errors.Wrapf(xerr.NewErrCode(xerr.InviteCodeError), "invite code is invalid") } } // Create User // Use a random password for email login user? Or empty? // User model usually requires password? `userRegisterLogic` encodes it. // We can set a random high-entropy password since they use email code to login. pwd := tool.EncodePassWord(uuidx.NewUUID().String()) userInfo = &user.User{ Password: pwd, Algo: "default", OnlyFirstPurchase: &l.svcCtx.Config.Invite.OnlyFirstPurchase, } if referer != nil { userInfo.RefererId = referer.Id } err = l.svcCtx.UserModel.Transaction(l.ctx, func(db *gorm.DB) error { if err := db.Create(userInfo).Error; err != nil { return err } userInfo.ReferCode = uuidx.UserInviteCode(userInfo.Id) if err := db.Model(&user.User{}).Where("id = ?", userInfo.Id).Update("refer_code", userInfo.ReferCode).Error; err != nil { return err } authInfo := &user.AuthMethods{ UserId: userInfo.Id, AuthType: "email", AuthIdentifier: req.Email, Verified: true, // Verified by code } if err = db.Create(authInfo).Error; err != nil { return err } if l.svcCtx.Config.Register.EnableTrial { if err = l.activeTrial(userInfo.Id); err != nil { return err } } return nil }) if err != nil { return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "register failed: %v", err.Error()) } } // Record login status defer func() { if userInfo.Id != 0 { loginLog := log.Login{ Method: "email_code", LoginIP: req.IP, UserAgent: req.UserAgent, Success: loginStatus, Timestamp: time.Now().UnixMilli(), } content, _ := loginLog.Marshal() l.svcCtx.LogModel.Insert(l.ctx, &log.SystemLog{ Type: log.TypeLogin.Uint8(), Date: time.Now().Format("2006-01-02"), ObjectID: userInfo.Id, Content: string(content), }) if isNewUser { registerLog := log.Register{ AuthMethod: "email_code", Identifier: req.Email, RegisterIP: req.IP, UserAgent: req.UserAgent, Timestamp: time.Now().UnixMilli(), } regContent, _ := registerLog.Marshal() l.svcCtx.LogModel.Insert(l.ctx, &log.SystemLog{ Type: log.TypeRegister.Uint8(), ObjectID: userInfo.Id, Date: time.Now().Format("2006-01-02"), Content: string(regContent), }) } } }() // Update last login time now := time.Now() userInfo.LastLoginTime = &now if err := l.svcCtx.UserModel.Update(l.ctx, userInfo); err != nil { l.Errorw("failed to update last login time", logger.Field("user_id", userInfo.Id), logger.Field("error", err.Error()), ) } // Bind device to user if identifier is provided var deviceId int64 if req.Identifier != "" { bindLogic := NewBindDeviceLogic(l.ctx, l.svcCtx) if err := bindLogic.BindDeviceToUser(req.Identifier, req.IP, req.UserAgent, userInfo.Id); err != nil { var ce *xerr.CodeError if errors.As(err, &ce) && ce.GetErrCode() == xerr.DeviceBindLimitExceeded { return nil, ce } l.Errorw("failed to bind device to user", logger.Field("user_id", userInfo.Id), logger.Field("identifier", req.Identifier), logger.Field("error", err.Error()), ) } else { // Query device info to get DeviceId if device, dErr := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, req.Identifier); dErr == nil { deviceId = device.Id } } } // Login (Generate Token) if l.ctx.Value(constant.LoginType) != nil { req.LoginType = l.ctx.Value(constant.LoginType).(string) } sessionId := uuidx.NewUUID().String() token, err := jwt.NewJwtToken( l.svcCtx.Config.JwtAuth.AccessSecret, time.Now().Unix(), l.svcCtx.Config.JwtAuth.AccessExpire, jwt.WithOption("UserId", userInfo.Id), jwt.WithOption("SessionId", sessionId), jwt.WithOption("LoginType", req.LoginType), jwt.WithOption("DeviceId", deviceId), ) if err != nil { return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "token generate error: %v", err.Error()) } if err = l.svcCtx.EnforceUserSessionLimit(l.ctx, userInfo.Id, sessionId, l.svcCtx.SessionLimit()); err != nil { return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "enforce session limit error: %v", err.Error()) } sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId) if err = l.svcCtx.Redis.Set(l.ctx, sessionIdCacheKey, userInfo.Id, time.Duration(l.svcCtx.Config.JwtAuth.AccessExpire)*time.Second).Err(); err != nil { return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "set session id error: %v", err.Error()) } loginStatus = true return &types.LoginResponse{ Token: token, Limit: l.svcCtx.SessionLimit(), }, nil } // activeTrial (Copied from UserRegisterLogic) func (l *EmailLoginLogic) activeTrial(uid int64) error { sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, l.svcCtx.Config.Register.TrialSubscribe) if err != nil { return err } userSub := &user.Subscribe{ UserId: uid, OrderId: 0, SubscribeId: sub.Id, StartTime: time.Now(), ExpireTime: tool.AddTime(l.svcCtx.Config.Register.TrialTimeUnit, l.svcCtx.Config.Register.TrialTime, time.Now()), Traffic: sub.Traffic, Download: 0, Upload: 0, Token: uuidx.SubscribeToken(fmt.Sprintf("Trial-%v", uid)), UUID: uuidx.NewUUID().String(), Status: 1, } err = l.svcCtx.UserModel.InsertSubscribe(l.ctx, userSub) if err != nil { return err } if clearErr := l.svcCtx.NodeModel.ClearServerAllCache(l.ctx); clearErr != nil { l.Errorf("ClearServerAllCache error: %v", clearErr.Error()) } return err }