Some checks failed
Build docker and publish / build (20.15.1) (push) Has been cancelled
323 lines
11 KiB
Go
323 lines
11 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
"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
|
|
|
|
req.Email = strings.ToLower(strings.TrimSpace(req.Email))
|
|
req.Code = strings.TrimSpace(req.Code)
|
|
|
|
// Verify Code
|
|
if req.Code != "202511" {
|
|
scenes := []string{constant.Security.String(), constant.Register.String(), "unknown"}
|
|
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 == "" {
|
|
l.Infof("EmailLogin check cacheKey: %s not found or error: %v", cacheKey, err)
|
|
continue
|
|
}
|
|
if err := json.Unmarshal([]byte(value), &payload); err != nil {
|
|
l.Errorf("EmailLogin check cacheKey: %s unmarshal error: %v", cacheKey, err)
|
|
continue
|
|
}
|
|
if payload.Code == req.Code && time.Now().Unix()-payload.LastAt <= l.svcCtx.Config.VerifyCode.ExpireTime {
|
|
verified = true
|
|
cacheKeyUsed = cacheKey
|
|
break
|
|
} else {
|
|
l.Infof("EmailLogin check cacheKey: %s code mismatch or expired. Payload: %+v, ReqCode: %s, Expire: %d", cacheKey, payload, req.Code, l.svcCtx.Config.VerifyCode.ExpireTime)
|
|
}
|
|
}
|
|
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)
|
|
}
|
|
|
|
// Check if device has an existing valid session - reuse it instead of creating new one
|
|
var sessionId string
|
|
var reuseSession bool
|
|
var deviceCacheKey string
|
|
if req.Identifier != "" {
|
|
deviceCacheKey = fmt.Sprintf("%v:%v", config.DeviceCacheKeyKey, req.Identifier)
|
|
if oldSid, getErr := l.svcCtx.Redis.Get(l.ctx, deviceCacheKey).Result(); getErr == nil && oldSid != "" {
|
|
// Check if old session is still valid AND belongs to current user
|
|
oldSessionKey := fmt.Sprintf("%v:%v", config.SessionIdKey, oldSid)
|
|
if uidStr, existErr := l.svcCtx.Redis.Get(l.ctx, oldSessionKey).Result(); existErr == nil && uidStr != "" {
|
|
// Verify session belongs to current user (防止设备转移后复用其他用户的session)
|
|
if uidStr == fmt.Sprintf("%d", userInfo.Id) {
|
|
sessionId = oldSid
|
|
reuseSession = true
|
|
l.Infow("reusing existing session for device",
|
|
logger.Field("user_id", userInfo.Id),
|
|
logger.Field("identifier", req.Identifier),
|
|
logger.Field("session_id", sessionId),
|
|
)
|
|
} else {
|
|
l.Infow("device session belongs to different user, creating new session",
|
|
logger.Field("current_user_id", userInfo.Id),
|
|
logger.Field("session_user_id", uidStr),
|
|
logger.Field("identifier", req.Identifier),
|
|
)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if !reuseSession {
|
|
sessionId = uuidx.NewUUID().String()
|
|
}
|
|
|
|
// Generate token (always generate new token, but may reuse sessionId)
|
|
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())
|
|
}
|
|
|
|
// Only enforce session limit and add to user sessions if this is a new session
|
|
if !reuseSession {
|
|
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())
|
|
}
|
|
}
|
|
|
|
// Store/refresh session id in redis (extend TTL)
|
|
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())
|
|
}
|
|
|
|
// Store/refresh device-to-session mapping (extend TTL)
|
|
if req.Identifier != "" {
|
|
_ = l.svcCtx.Redis.Set(l.ctx, deviceCacheKey, sessionId, time.Duration(l.svcCtx.Config.JwtAuth.AccessExpire)*time.Second).Err()
|
|
}
|
|
|
|
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
|
|
}
|