Merge remote-tracking branch 'origin/master' into internal
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/captcha"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type AdminGenerateCaptchaLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Generate captcha
|
||||
func NewAdminGenerateCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGenerateCaptchaLogic {
|
||||
return &AdminGenerateCaptchaLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *AdminGenerateCaptchaLogic) AdminGenerateCaptcha() (resp *types.GenerateCaptchaResponse, err error) {
|
||||
resp = &types.GenerateCaptchaResponse{}
|
||||
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminGenerateCaptchaLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
TurnstileSiteKey string `json:"turnstile_site_key"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
|
||||
resp.Type = config.CaptchaType
|
||||
|
||||
// If captcha type is local, generate captcha image
|
||||
if config.CaptchaType == "local" {
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
})
|
||||
|
||||
id, image, err := captchaService.Generate(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminGenerateCaptchaLogic] Generate captcha error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Generate captcha error: %v", err.Error())
|
||||
}
|
||||
|
||||
resp.Id = id
|
||||
resp.Image = image
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
// For Turnstile, just return the site key
|
||||
resp.Id = config.TurnstileSiteKey
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/logic/auth"
|
||||
"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/captcha"
|
||||
"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 AdminLoginLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Admin login
|
||||
func NewAdminLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminLoginLogic {
|
||||
return &AdminLoginLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *AdminLoginLogic) AdminLogin(req *types.UserLoginRequest) (resp *types.LoginResponse, err error) {
|
||||
loginStatus := false
|
||||
var userInfo *user.User
|
||||
// Record login status
|
||||
defer func(svcCtx *svc.ServiceContext) {
|
||||
if userInfo != nil && userInfo.Id != 0 {
|
||||
loginLog := log.Login{
|
||||
Method: "email",
|
||||
LoginIP: req.IP,
|
||||
UserAgent: req.UserAgent,
|
||||
Success: loginStatus,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
}
|
||||
content, _ := loginLog.Marshal()
|
||||
if err := 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),
|
||||
}); err != nil {
|
||||
l.Errorw("failed to insert login log",
|
||||
logger.Field("user_id", userInfo.Id),
|
||||
logger.Field("ip", req.IP),
|
||||
logger.Field("error", err.Error()),
|
||||
)
|
||||
}
|
||||
}
|
||||
}(l.svcCtx)
|
||||
|
||||
// Verify captcha
|
||||
if err := l.verifyCaptcha(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userInfo, err = l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
|
||||
|
||||
if userInfo.DeletedAt.Valid {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "user email deleted: %v", req.Email)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if errors.As(err, &gorm.ErrRecordNotFound) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "user email not exist: %v", req.Email)
|
||||
}
|
||||
logger.WithContext(l.ctx).Error(err)
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user info failed: %v", err.Error())
|
||||
}
|
||||
|
||||
// Check if user is admin
|
||||
if userInfo.IsAdmin == nil || !*userInfo.IsAdmin {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.PermissionDenied), "user is not admin")
|
||||
}
|
||||
|
||||
// Verify password
|
||||
if !tool.MultiPasswordVerify(userInfo.Algo, userInfo.Salt, req.Password, userInfo.Password) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserPasswordError), "user password")
|
||||
}
|
||||
|
||||
// Bind device to user if identifier is provided
|
||||
if req.Identifier != "" {
|
||||
bindLogic := auth.NewBindDeviceLogic(l.ctx, l.svcCtx)
|
||||
if err := bindLogic.BindDeviceToUser(req.Identifier, req.IP, req.UserAgent, userInfo.Id); err != nil {
|
||||
l.Errorw("failed to bind device to user",
|
||||
logger.Field("user_id", userInfo.Id),
|
||||
logger.Field("identifier", req.Identifier),
|
||||
logger.Field("error", err.Error()),
|
||||
)
|
||||
// Don't fail login if device binding fails, just log the error
|
||||
}
|
||||
}
|
||||
if l.ctx.Value(constant.CtxLoginType) != nil {
|
||||
req.LoginType = l.ctx.Value(constant.CtxLoginType).(string)
|
||||
}
|
||||
// Generate session id
|
||||
sessionId := uuidx.NewUUID().String()
|
||||
// Generate token
|
||||
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("identifier", req.Identifier),
|
||||
jwt.WithOption("CtxLoginType", req.LoginType),
|
||||
)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminLogin] token generate error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "token generate 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,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l *AdminLoginLogic) verifyCaptcha(req *types.UserLoginRequest) error {
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminLoginLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
|
||||
// Check if captcha is enabled for admin login
|
||||
if !config.EnableAdminLoginCaptcha {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify based on captcha type
|
||||
if config.CaptchaType == "local" {
|
||||
if req.CaptchaId == "" || req.CaptchaCode == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CaptchaId, req.CaptchaCode, req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminLoginLogic] Verify captcha error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
if req.CfToken == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeTurnstile,
|
||||
TurnstileSecret: config.TurnstileSecret,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CfToken, "", req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminLoginLogic] Verify turnstile error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/logic/auth"
|
||||
"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/captcha"
|
||||
"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 AdminResetPasswordLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
type CacheKeyPayload struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
// Admin reset password
|
||||
func NewAdminResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminResetPasswordLogic {
|
||||
return &AdminResetPasswordLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *AdminResetPasswordLogic) AdminResetPassword(req *types.ResetPasswordRequest) (resp *types.LoginResponse, err error) {
|
||||
var userInfo *user.User
|
||||
loginStatus := false
|
||||
|
||||
defer func() {
|
||||
if userInfo != nil && userInfo.Id != 0 && loginStatus {
|
||||
loginLog := log.Login{
|
||||
Method: "email",
|
||||
LoginIP: req.IP,
|
||||
UserAgent: req.UserAgent,
|
||||
Success: loginStatus,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
}
|
||||
content, _ := loginLog.Marshal()
|
||||
if err := l.svcCtx.LogModel.Insert(l.ctx, &log.SystemLog{
|
||||
Id: 0,
|
||||
Type: log.TypeLogin.Uint8(),
|
||||
Date: time.Now().Format("2006-01-02"),
|
||||
ObjectID: userInfo.Id,
|
||||
Content: string(content),
|
||||
}); err != nil {
|
||||
l.Errorw("failed to insert login log",
|
||||
logger.Field("user_id", userInfo.Id),
|
||||
logger.Field("ip", req.IP),
|
||||
logger.Field("error", err.Error()),
|
||||
)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeCacheKey, constant.Security, req.Email)
|
||||
// Check the verification code
|
||||
if value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result(); err != nil {
|
||||
l.Errorw("Verification code error", logger.Field("cacheKey", cacheKey), logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "Verification code error")
|
||||
} else {
|
||||
var payload CacheKeyPayload
|
||||
if err := json.Unmarshal([]byte(value), &payload); err != nil {
|
||||
l.Errorw("Unmarshal errors", logger.Field("cacheKey", cacheKey), 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 {
|
||||
l.Errorw("Verification code error", logger.Field("cacheKey", cacheKey), logger.Field("error", "Verification code error"), logger.Field("reqCode", req.Code), logger.Field("payloadCode", payload.Code))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "Verification code error")
|
||||
}
|
||||
}
|
||||
|
||||
// Verify captcha
|
||||
if err := l.verifyCaptcha(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check user
|
||||
authMethod, err := l.svcCtx.UserModel.FindUserAuthMethodByOpenID(l.ctx, "email", req.Email)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "user email not exist: %v", req.Email)
|
||||
}
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user by email error: %v", err.Error())
|
||||
}
|
||||
|
||||
userInfo, err = l.svcCtx.UserModel.FindOne(l.ctx, authMethod.UserId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "user email not exist: %v", req.Email)
|
||||
}
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user info failed: %v", err.Error())
|
||||
}
|
||||
|
||||
// Check if user is admin
|
||||
if userInfo.IsAdmin == nil || !*userInfo.IsAdmin {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.PermissionDenied), "user is not admin")
|
||||
}
|
||||
|
||||
// Update password
|
||||
userInfo.Password = tool.EncodePassWord(req.Password)
|
||||
userInfo.Algo = "default"
|
||||
if err = l.svcCtx.UserModel.Update(l.ctx, userInfo); err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update user info failed: %v", err.Error())
|
||||
}
|
||||
|
||||
// Bind device to user if identifier is provided
|
||||
if req.Identifier != "" {
|
||||
bindLogic := auth.NewBindDeviceLogic(l.ctx, l.svcCtx)
|
||||
if err := bindLogic.BindDeviceToUser(req.Identifier, req.IP, req.UserAgent, userInfo.Id); err != nil {
|
||||
l.Errorw("failed to bind device to user",
|
||||
logger.Field("user_id", userInfo.Id),
|
||||
logger.Field("identifier", req.Identifier),
|
||||
logger.Field("error", err.Error()),
|
||||
)
|
||||
// Don't fail register if device binding fails, just log the error
|
||||
}
|
||||
}
|
||||
if l.ctx.Value(constant.CtxLoginType) != nil {
|
||||
req.LoginType = l.ctx.Value(constant.CtxLoginType).(string)
|
||||
}
|
||||
// Generate session id
|
||||
sessionId := uuidx.NewUUID().String()
|
||||
// Generate token
|
||||
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("identifier", req.Identifier),
|
||||
jwt.WithOption("CtxLoginType", req.LoginType),
|
||||
)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminResetPassword] token generate error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "token generate 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,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l *AdminResetPasswordLogic) verifyCaptcha(req *types.ResetPasswordRequest) error {
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminResetPasswordLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
|
||||
// Check if admin login captcha is enabled (use admin login captcha for reset password)
|
||||
if !config.EnableAdminLoginCaptcha {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify based on captcha type
|
||||
if config.CaptchaType == "local" {
|
||||
if req.CaptchaId == "" || req.CaptchaCode == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CaptchaId, req.CaptchaCode, req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminResetPasswordLogic] Verify captcha error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
if req.CfToken == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeTurnstile,
|
||||
TurnstileSecret: config.TurnstileSecret,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CfToken, "", req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[AdminResetPasswordLogic] Verify turnstile error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/captcha"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GenerateCaptchaLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Generate captcha
|
||||
func NewGenerateCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GenerateCaptchaLogic {
|
||||
return &GenerateCaptchaLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GenerateCaptchaLogic) GenerateCaptcha() (resp *types.GenerateCaptchaResponse, err error) {
|
||||
resp = &types.GenerateCaptchaResponse{}
|
||||
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[GenerateCaptchaLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
TurnstileSiteKey string `json:"turnstile_site_key"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
|
||||
resp.Type = config.CaptchaType
|
||||
|
||||
// If captcha type is local, generate captcha image
|
||||
if config.CaptchaType == "local" {
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
})
|
||||
|
||||
id, image, err := captchaService.Generate(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[GenerateCaptchaLogic] Generate captcha error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Generate captcha error: %v", err.Error())
|
||||
}
|
||||
|
||||
resp.Id = id
|
||||
resp.Image = image
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
// For Turnstile, just return the site key
|
||||
resp.Id = config.TurnstileSiteKey
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
@@ -16,6 +16,10 @@ func registerIpLimit(svcCtx *svc.ServiceContext, ctx context.Context, registerIp
|
||||
return true
|
||||
}
|
||||
|
||||
// Add timeout protection for Redis operations
|
||||
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Use a sorted set to track IP registrations with timestamp as score
|
||||
// Key format: register:ip:{ip}
|
||||
key := fmt.Sprintf("%s%s", config.RegisterIpKeyPrefix, registerIp)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/pkg/captcha"
|
||||
"github.com/perfect-panel/server/pkg/jwt"
|
||||
"github.com/perfect-panel/server/pkg/uuidx"
|
||||
|
||||
@@ -91,6 +92,11 @@ func (l *ResetPasswordLogic) ResetPassword(req *types.ResetPasswordRequest) (res
|
||||
l.svcCtx.Redis.Del(l.ctx, cacheKey)
|
||||
}
|
||||
|
||||
// Verify captcha
|
||||
if err := l.verifyCaptcha(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check user
|
||||
authMethod, err := l.svcCtx.UserModel.FindUserAuthMethodByOpenID(l.ctx, "email", req.Email)
|
||||
if err != nil {
|
||||
@@ -155,3 +161,68 @@ func (l *ResetPasswordLogic) ResetPassword(req *types.ResetPasswordRequest) (res
|
||||
Token: token,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l *ResetPasswordLogic) verifyCaptcha(req *types.ResetPasswordRequest) error {
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[ResetPasswordLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
EnableUserResetPasswordCaptcha bool `json:"enable_user_reset_password_captcha"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
|
||||
// Check if user reset password captcha is enabled
|
||||
if !config.EnableUserResetPasswordCaptcha {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify based on captcha type
|
||||
if config.CaptchaType == "local" {
|
||||
if req.CaptchaId == "" || req.CaptchaCode == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CaptchaId, req.CaptchaCode, req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[ResetPasswordLogic] Verify captcha error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
if req.CfToken == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeTurnstile,
|
||||
TurnstileSecret: config.TurnstileSecret,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CfToken, "", req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[ResetPasswordLogic] Verify turnstile error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/captcha"
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"github.com/perfect-panel/server/pkg/jwt"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
@@ -94,6 +95,11 @@ func (l *TelephoneLoginLogic) TelephoneLogin(req *types.TelephoneLoginRequest, r
|
||||
return nil, xerr.NewErrCodeMsg(xerr.InvalidParams, "password and telephone code is empty")
|
||||
}
|
||||
|
||||
// Verify captcha
|
||||
if err := l.verifyCaptcha(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if req.TelephoneCode == "" {
|
||||
// Verify password
|
||||
if !tool.MultiPasswordVerify(userInfo.Algo, userInfo.Salt, req.Password, userInfo.Password) {
|
||||
@@ -164,3 +170,67 @@ func (l *TelephoneLoginLogic) TelephoneLogin(req *types.TelephoneLoginRequest, r
|
||||
Token: token,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l *TelephoneLoginLogic) verifyCaptcha(req *types.TelephoneLoginRequest) error {
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[TelephoneLoginLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
EnableUserLoginCaptcha bool `json:"enable_user_login_captcha"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
|
||||
// Check if captcha is enabled for user login
|
||||
if !config.EnableUserLoginCaptcha {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify based on captcha type
|
||||
if config.CaptchaType == "local" {
|
||||
if req.CaptchaId == "" || req.CaptchaCode == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CaptchaId, req.CaptchaCode, req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[TelephoneLoginLogic] Verify captcha error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
if req.CfToken == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeTurnstile,
|
||||
TurnstileSecret: config.TurnstileSecret,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CfToken, "", req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[TelephoneLoginLogic] Verify turnstile error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"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/captcha"
|
||||
"github.com/perfect-panel/server/pkg/jwt"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/phone"
|
||||
@@ -81,6 +82,12 @@ func (l *TelephoneUserRegisterLogic) TelephoneUserRegister(req *types.TelephoneR
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
l.svcCtx.Redis.Del(l.ctx, cacheKey)
|
||||
|
||||
// Verify captcha
|
||||
if err := l.verifyCaptcha(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if the user exists
|
||||
_, err = l.svcCtx.UserModel.FindUserAuthMethodByOpenID(l.ctx, "mobile", phoneNumber)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
@@ -280,3 +287,67 @@ func (l *TelephoneUserRegisterLogic) activeTrial(uid int64) (*user.Subscribe, er
|
||||
return userSub, nil
|
||||
}
|
||||
|
||||
func (l *TelephoneUserRegisterLogic) verifyCaptcha(req *types.TelephoneRegisterRequest) error {
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[TelephoneUserRegisterLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
EnableUserRegisterCaptcha bool `json:"enable_user_register_captcha"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
|
||||
// Check if captcha is enabled for user register
|
||||
if !config.EnableUserRegisterCaptcha {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify based on captcha type
|
||||
if config.CaptchaType == "local" {
|
||||
if req.CaptchaId == "" || req.CaptchaCode == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CaptchaId, req.CaptchaCode, req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[TelephoneUserRegisterLogic] Verify captcha error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
if req.CfToken == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeTurnstile,
|
||||
TurnstileSecret: config.TurnstileSecret,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CfToken, "", req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[TelephoneUserRegisterLogic] Verify turnstile error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/pkg/captcha"
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
|
||||
@@ -66,6 +67,11 @@ func (l *UserLoginLogic) UserLogin(req *types.UserLoginRequest) (resp *types.Log
|
||||
}
|
||||
}(l.svcCtx)
|
||||
|
||||
// Verify captcha
|
||||
if err := l.verifyCaptcha(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userInfo, err = l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
@@ -134,3 +140,67 @@ func (l *UserLoginLogic) UserLogin(req *types.UserLoginRequest) (resp *types.Log
|
||||
Token: token,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l *UserLoginLogic) verifyCaptcha(req *types.UserLoginRequest) error {
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[UserLoginLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
EnableUserLoginCaptcha bool `json:"enable_user_login_captcha"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
|
||||
// Check if captcha is enabled for user login
|
||||
if !config.EnableUserLoginCaptcha {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify based on captcha type
|
||||
if config.CaptchaType == "local" {
|
||||
if req.CaptchaId == "" || req.CaptchaCode == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CaptchaId, req.CaptchaCode, req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[UserLoginLogic] Verify captcha error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
if req.CfToken == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeTurnstile,
|
||||
TurnstileSecret: config.TurnstileSecret,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CfToken, "", req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[UserLoginLogic] Verify turnstile error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -8,11 +8,13 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/group"
|
||||
"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/captcha"
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"github.com/perfect-panel/server/pkg/jwt"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
@@ -85,6 +87,12 @@ func (l *UserRegisterLogic) UserRegister(req *types.UserRegisterRequest) (resp *
|
||||
}
|
||||
l.svcCtx.Redis.Del(l.ctx, cacheKey)
|
||||
}
|
||||
|
||||
// Verify captcha
|
||||
if err := l.verifyCaptcha(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if the user exists
|
||||
u, err := l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
@@ -132,22 +140,76 @@ func (l *UserRegisterLogic) UserRegister(req *types.UserRegisterRequest) (resp *
|
||||
return err
|
||||
}
|
||||
|
||||
if l.svcCtx.Config.Register.EnableTrial {
|
||||
// Active trial
|
||||
var trialErr error
|
||||
trialSubscribe, trialErr = l.activeTrial(userInfo.Id)
|
||||
if trialErr != nil {
|
||||
return trialErr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Activate trial subscription after transaction success (moved outside transaction to reduce lock time)
|
||||
if l.svcCtx.Config.Register.EnableTrial {
|
||||
trialSubscribe, err = l.activeTrial(userInfo.Id)
|
||||
if err != nil {
|
||||
l.Errorw("Failed to activate trial subscription", logger.Field("error", err.Error()))
|
||||
// Don't fail registration if trial activation fails
|
||||
}
|
||||
}
|
||||
|
||||
// Clear cache after transaction success
|
||||
if l.svcCtx.Config.Register.EnableTrial && trialSubscribe != nil {
|
||||
// Trigger user group recalculation (runs in background)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Check if group management is enabled
|
||||
var groupEnabled string
|
||||
err := l.svcCtx.DB.Table("system").
|
||||
Where("`category` = ? AND `key` = ?", "group", "enabled").
|
||||
Select("value").
|
||||
Scan(&groupEnabled).Error
|
||||
if err != nil || groupEnabled != "true" && groupEnabled != "1" {
|
||||
l.Debugf("Group management not enabled, skipping recalculation")
|
||||
return
|
||||
}
|
||||
|
||||
// Get the configured grouping mode
|
||||
var groupMode string
|
||||
err = l.svcCtx.DB.Table("system").
|
||||
Where("`category` = ? AND `key` = ?", "group", "mode").
|
||||
Select("value").
|
||||
Scan(&groupMode).Error
|
||||
if err != nil {
|
||||
l.Errorw("Failed to get group mode", logger.Field("error", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Validate group mode
|
||||
if groupMode != "average" && groupMode != "subscribe" && groupMode != "traffic" {
|
||||
l.Debugf("Invalid group mode (current: %s), skipping", groupMode)
|
||||
return
|
||||
}
|
||||
|
||||
// Trigger group recalculation with the configured mode
|
||||
logic := group.NewRecalculateGroupLogic(ctx, l.svcCtx)
|
||||
req := &types.RecalculateGroupRequest{
|
||||
Mode: groupMode,
|
||||
}
|
||||
|
||||
if err := logic.RecalculateGroup(req); err != nil {
|
||||
l.Errorw("Failed to recalculate user group",
|
||||
logger.Field("user_id", userInfo.Id),
|
||||
logger.Field("error", err.Error()),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
l.Infow("Successfully recalculated user group after registration",
|
||||
logger.Field("user_id", userInfo.Id),
|
||||
logger.Field("mode", groupMode),
|
||||
)
|
||||
}()
|
||||
|
||||
// Clear user subscription cache
|
||||
if err = l.svcCtx.UserModel.ClearSubscribeCache(l.ctx, trialSubscribe); err != nil {
|
||||
l.Errorw("ClearSubscribeCache failed", logger.Field("error", err.Error()), logger.Field("userSubscribeId", trialSubscribe.Id))
|
||||
@@ -202,7 +264,7 @@ func (l *UserRegisterLogic) UserRegister(req *types.UserRegisterRequest) (resp *
|
||||
}
|
||||
loginStatus := true
|
||||
defer func() {
|
||||
if token != "" && userInfo.Id != 0 {
|
||||
if token != "" && userInfo != nil && userInfo.Id != 0 {
|
||||
loginLog := log.Login{
|
||||
Method: "email",
|
||||
LoginIP: req.IP,
|
||||
@@ -275,3 +337,67 @@ func (l *UserRegisterLogic) activeTrial(uid int64) (*user.Subscribe, error) {
|
||||
}
|
||||
return userSub, nil
|
||||
}
|
||||
|
||||
func (l *UserRegisterLogic) verifyCaptcha(req *types.UserRegisterRequest) error {
|
||||
// Get verify config from database
|
||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[UserRegisterLogic] GetVerifyConfig error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyConfig error: %v", err.Error())
|
||||
}
|
||||
|
||||
var config struct {
|
||||
CaptchaType string `json:"captcha_type"`
|
||||
EnableUserRegisterCaptcha bool `json:"enable_user_register_captcha"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
}
|
||||
tool.SystemConfigSliceReflectToStruct(verifyCfg, &config)
|
||||
|
||||
// Check if user register captcha is enabled
|
||||
if !config.EnableUserRegisterCaptcha {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify based on captcha type
|
||||
if config.CaptchaType == "local" {
|
||||
if req.CaptchaId == "" || req.CaptchaCode == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeLocal,
|
||||
RedisClient: l.svcCtx.Redis,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CaptchaId, req.CaptchaCode, req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[UserRegisterLogic] Verify captcha error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
} else if config.CaptchaType == "turnstile" {
|
||||
if req.CfToken == "" {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "captcha required")
|
||||
}
|
||||
|
||||
captchaService := captcha.NewService(captcha.Config{
|
||||
Type: captcha.CaptchaTypeTurnstile,
|
||||
TurnstileSecret: config.TurnstileSecret,
|
||||
})
|
||||
|
||||
valid, err := captchaService.Verify(l.ctx, req.CfToken, "", req.IP)
|
||||
if err != nil {
|
||||
l.Logger.Error("[UserRegisterLogic] Verify turnstile error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verify captcha error")
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "invalid captcha")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user