feat: 实现邮箱验证码登录功能,支持新用户自动注册并记录登录日志
Build docker and publish / build (20.15.1) (push) Successful in 5m40s
Build docker and publish / build (20.15.1) (push) Successful in 5m40s
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/auth"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func EmailLoginHandler(svcCtx *svc.ServiceContext) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var req types.EmailLoginRequest
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
req.IP = c.ClientIP()
|
||||
req.UserAgent = c.Request.UserAgent()
|
||||
|
||||
if err := svcCtx.Validate(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
l := auth.NewEmailLoginLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.EmailLogin(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -597,6 +597,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
// User login
|
||||
authGroupRouter.POST("/login", auth.UserLoginHandler(serverCtx))
|
||||
|
||||
// Email login
|
||||
authGroupRouter.POST("/login/email", auth.EmailLoginHandler(serverCtx))
|
||||
|
||||
// Device Login
|
||||
authGroupRouter.POST("/login/device", auth.DeviceLoginHandler(serverCtx))
|
||||
|
||||
|
||||
@@ -54,9 +54,21 @@ func (l *DeleteUserDeviceLogic) DeleteUserDevice(req *types.DeleteUserDeivceRequ
|
||||
_ = l.svcCtx.Redis.ZRem(ctx, sessionsKey, sessionId).Err()
|
||||
}
|
||||
|
||||
// 最后删除数据库记录
|
||||
if err := l.svcCtx.UserModel.DeleteDevice(l.ctx, req.Id); err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete user error: %v", err.Error())
|
||||
// 使用事务同时删除设备记录和关联的认证方式
|
||||
err := l.svcCtx.UserModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
||||
// 删除设备记录
|
||||
if err := l.svcCtx.UserModel.DeleteDevice(l.ctx, req.Id, db); err != nil {
|
||||
return err
|
||||
}
|
||||
// 删除关联的 AuthMethod (type="device", identifier=device.Identifier)
|
||||
if err := l.svcCtx.UserModel.DeleteUserAuthMethodByIdentifier(l.ctx, device.UserId, "device", device.Identifier, db); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete user device transaction error: %v", err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
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.
|
||||
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeCacheKey, constant.Security, req.Email)
|
||||
value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
||||
if err != nil {
|
||||
l.Errorw("Verification code error (Redis get)", logger.Field("cacheKey", cacheKey), logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verification code error or expired")
|
||||
}
|
||||
|
||||
var payload common.CacheKeyPayload
|
||||
if err := json.Unmarshal([]byte(value), &payload); err != nil {
|
||||
l.Errorw("Unmarshal error", logger.Field("error", err.Error()), logger.Field("value", value))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verification code error")
|
||||
}
|
||||
if payload.Code != req.Code {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verification code mismatch")
|
||||
}
|
||||
// Delete code after use? Or keep it? Usually delete.
|
||||
l.svcCtx.Redis.Del(l.ctx, cacheKey)
|
||||
|
||||
|
||||
// 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),
|
||||
})
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// 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),
|
||||
)
|
||||
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
|
||||
}
|
||||
@@ -84,6 +84,29 @@ func (m *defaultUserModel) DeleteUserAuthMethods(ctx context.Context, userId int
|
||||
})
|
||||
}
|
||||
|
||||
func (m *defaultUserModel) DeleteUserAuthMethodByIdentifier(ctx context.Context, userId int64, platform, identifier string, tx ...*gorm.DB) error {
|
||||
u, err := m.FindOne(ctx, userId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err = m.ClearUserCache(context.Background(), u); err != nil {
|
||||
logger.Errorf("[UserModel] clear user cache failed: %v", err.Error())
|
||||
}
|
||||
}()
|
||||
|
||||
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
|
||||
if len(tx) > 0 {
|
||||
conn = tx[0]
|
||||
}
|
||||
// Delete by user_id, auth_type AND auth_identifier
|
||||
return conn.Model(&AuthMethods{}).
|
||||
Where("user_id = ? AND auth_type = ? AND auth_identifier = ?", userId, platform, identifier).
|
||||
Delete(&AuthMethods{}).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (m *defaultUserModel) FindUserAuthMethodByUserId(ctx context.Context, method string, userId int64) (*AuthMethods, error) {
|
||||
var data AuthMethods
|
||||
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
|
||||
|
||||
@@ -96,6 +96,7 @@ type customUserLogicModel interface {
|
||||
FindUserAuthMethodByOpenID(ctx context.Context, method, openID string) (*AuthMethods, error)
|
||||
FindUserAuthMethodByUserId(ctx context.Context, method string, userId int64) (*AuthMethods, error)
|
||||
FindUserAuthMethodByPlatform(ctx context.Context, userId int64, platform string) (*AuthMethods, error)
|
||||
DeleteUserAuthMethodByIdentifier(ctx context.Context, userId int64, platform, identifier string, tx ...*gorm.DB) error
|
||||
FindOneByEmail(ctx context.Context, email string) (*User, error)
|
||||
FindOneDevice(ctx context.Context, id int64) (*Device, error)
|
||||
QueryDeviceList(ctx context.Context, userid int64) ([]*Device, int64, error)
|
||||
@@ -134,27 +135,27 @@ func (m *customUserModel) QueryPageList(ctx context.Context, page, size int, fil
|
||||
var list []*User
|
||||
var total int64
|
||||
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
|
||||
if filter != nil {
|
||||
if filter.UserId != nil {
|
||||
conn = conn.Where("user.id =?", *filter.UserId)
|
||||
}
|
||||
if filter.Search != "" {
|
||||
conn = conn.Joins("LEFT JOIN user_auth_methods ON user.id = user_auth_methods.user_id").
|
||||
Where("user_auth_methods.auth_identifier LIKE ?", "%"+filter.Search+"%").Or("user.refer_code like ?", "%"+filter.Search+"%")
|
||||
}
|
||||
if filter.DeviceId != "" {
|
||||
conn = conn.Joins("LEFT JOIN user_device ON user.id = user_device.user_id")
|
||||
if id, err := strconv.ParseInt(filter.DeviceId, 10, 64); err == nil {
|
||||
conn = conn.Where("user_device.id = ? OR user_device.identifier = ?", id, filter.DeviceId)
|
||||
} else {
|
||||
conn = conn.Where("user_device.identifier = ?", filter.DeviceId)
|
||||
if filter != nil {
|
||||
if filter.UserId != nil {
|
||||
conn = conn.Where("user.id =?", *filter.UserId)
|
||||
}
|
||||
}
|
||||
if filter.UserSubscribeId != nil {
|
||||
conn = conn.Joins("LEFT JOIN user_subscribe ON user.id = user_subscribe.user_id").
|
||||
Where("user_subscribe.id =? and `status` IN (0,1)", *filter.UserSubscribeId)
|
||||
}
|
||||
if filter.SubscribeId != nil {
|
||||
if filter.Search != "" {
|
||||
conn = conn.Joins("LEFT JOIN user_auth_methods ON user.id = user_auth_methods.user_id").
|
||||
Where("user_auth_methods.auth_identifier LIKE ?", "%"+filter.Search+"%").Or("user.refer_code like ?", "%"+filter.Search+"%")
|
||||
}
|
||||
if filter.DeviceId != "" {
|
||||
conn = conn.Joins("LEFT JOIN user_device ON user.id = user_device.user_id")
|
||||
if id, err := strconv.ParseInt(filter.DeviceId, 10, 64); err == nil {
|
||||
conn = conn.Where("user_device.id = ? OR user_device.identifier = ?", id, filter.DeviceId)
|
||||
} else {
|
||||
conn = conn.Where("user_device.identifier = ?", filter.DeviceId)
|
||||
}
|
||||
}
|
||||
if filter.UserSubscribeId != nil {
|
||||
conn = conn.Joins("LEFT JOIN user_subscribe ON user.id = user_subscribe.user_id").
|
||||
Where("user_subscribe.id =? and `status` IN (0,1)", *filter.UserSubscribeId)
|
||||
}
|
||||
if filter.SubscribeId != nil {
|
||||
conn = conn.Joins("LEFT JOIN user_subscribe ON user.id = user_subscribe.user_id").
|
||||
Where("user_subscribe.subscribe_id =? and `status` IN (0,1)", *filter.SubscribeId)
|
||||
}
|
||||
|
||||
@@ -595,6 +595,16 @@ type EmailAuthticateConfig struct {
|
||||
DomainSuffixList string `json:"domain_suffix_list"`
|
||||
}
|
||||
|
||||
type EmailLoginRequest struct {
|
||||
Email string `json:"email" validate:"required"`
|
||||
Code string `json:"code" validate:"required"`
|
||||
Invite string `json:"invite,optional"`
|
||||
IP string `header:"X-Original-Forwarded-For"`
|
||||
UserAgent string `header:"User-Agent"`
|
||||
LoginType string `header:"Login-Type"`
|
||||
CfToken string `json:"cf_token,optional"`
|
||||
}
|
||||
|
||||
type FilterBalanceLogRequest struct {
|
||||
FilterLogParams
|
||||
UserId int64 `form:"user_id,optional"`
|
||||
|
||||
Reference in New Issue
Block a user