init: 1.0.0

This commit is contained in:
Chang lue Tsen
2025-04-25 12:08:29 +09:00
commit 8addcc584b
1031 changed files with 76472 additions and 0 deletions
@@ -0,0 +1,70 @@
package common
import (
"context"
"encoding/json"
"fmt"
"github.com/perfect-panel/ppanel-server/internal/config"
"github.com/perfect-panel/ppanel-server/internal/svc"
"github.com/perfect-panel/ppanel-server/internal/types"
"github.com/perfect-panel/ppanel-server/pkg/authmethod"
"github.com/perfect-panel/ppanel-server/pkg/constant"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"github.com/perfect-panel/ppanel-server/pkg/phone"
"github.com/perfect-panel/ppanel-server/pkg/xerr"
"github.com/pkg/errors"
)
type CheckVerificationCodeLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// Check verification code
func NewCheckVerificationCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckVerificationCodeLogic {
return &CheckVerificationCodeLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *CheckVerificationCodeLogic) CheckVerificationCode(req *types.CheckVerificationCodeRequest) (resp *types.CheckVerificationCodeRespone, err error) {
resp = &types.CheckVerificationCodeRespone{}
if req.Method == authmethod.Email {
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeCacheKey, constant.ParseVerifyType(req.Type), req.Account)
value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
if err != nil {
return resp, nil
}
var payload CacheKeyPayload
if err := json.Unmarshal([]byte(value), &payload); err != nil {
return resp, nil
}
if payload.Code != req.Code {
return resp, nil
}
resp.Status = true
}
if req.Method == authmethod.Mobile {
if !phone.CheckPhone(req.Account) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TelephoneError), "Invalid phone number")
}
cacheKey := fmt.Sprintf("%s:%s:+%s", config.AuthCodeTelephoneCacheKey, constant.ParseVerifyType(req.Type), req.Account)
value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
if err != nil {
return resp, nil
}
var payload CacheKeyPayload
if err := json.Unmarshal([]byte(value), &payload); err != nil {
return resp, nil
}
if payload.Code != req.Code {
return resp, nil
}
resp.Status = true
}
return resp, nil
}
+42
View File
@@ -0,0 +1,42 @@
package common
import (
"context"
"github.com/perfect-panel/ppanel-server/internal/model/ads"
"github.com/perfect-panel/ppanel-server/internal/svc"
"github.com/perfect-panel/ppanel-server/internal/types"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"github.com/perfect-panel/ppanel-server/pkg/tool"
)
type GetAdsLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// Get Ads
func NewGetAdsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAdsLogic {
return &GetAdsLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetAdsLogic) GetAds(req *types.GetAdsRequest) (resp *types.GetAdsResponse, err error) {
// todo: add ads position and device
status := 1
_, data, err := l.svcCtx.AdsModel.GetAdsListByPage(l.ctx, 1, 200, ads.Filter{
Status: &status,
})
if err != nil {
return nil, err
}
resp = &types.GetAdsResponse{
List: make([]types.Ads, len(data)),
}
tool.DeepCopy(&resp.List, data)
return
}
@@ -0,0 +1,136 @@
package common
import (
"context"
"strings"
"github.com/perfect-panel/ppanel-server/internal/model/application"
"github.com/perfect-panel/ppanel-server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
"github.com/perfect-panel/ppanel-server/internal/svc"
"github.com/perfect-panel/ppanel-server/internal/types"
"github.com/perfect-panel/ppanel-server/pkg/logger"
)
type GetApplicationLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// Get Tos Content
func NewGetApplicationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApplicationLogic {
return &GetApplicationLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetApplicationLogic) GetApplication() (resp *types.GetAppcationResponse, err error) {
resp = &types.GetAppcationResponse{}
cfg, err := l.svcCtx.ApplicationModel.FindOneConfig(l.ctx, 1)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
l.Logger.Error("[GetAppInfo] FindOneAppConfig error: ", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetAppInfo FindOneAppConfig error: %v", err.Error())
}
if err != nil {
resp.Config = types.ApplicationConfig{}
} else {
resp.Config = types.ApplicationConfig{
AppId: cfg.AppId,
EncryptionKey: cfg.EncryptionKey,
EncryptionMethod: cfg.EncryptionMethod,
Domains: strings.Split(cfg.Domains, ";"),
StartupPicture: cfg.StartupPicture,
StartupPictureSkipTime: cfg.StartupPictureSkipTime,
}
}
var applications []*application.Application
err = l.svcCtx.ApplicationModel.Transaction(l.ctx, func(tx *gorm.DB) (err error) {
return tx.Model(applications).Preload("ApplicationVersions").Find(&applications).Error
})
if err != nil {
l.Errorw("[QueryApplicationConfig] get application error: ", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get application error: %v", err.Error())
}
if len(applications) == 0 {
return resp, nil
}
for _, app := range applications {
applicationResponse := types.ApplicationResponseInfo{
Id: app.Id,
Name: app.Name,
Icon: app.Icon,
Description: app.Description,
SubscribeType: app.SubscribeType,
}
applicationVersions := app.ApplicationVersions
if len(applicationVersions) != 0 {
for _, applicationVersion := range applicationVersions {
/*if !applicationVersion.IsDefault {
continue
}*/
switch applicationVersion.Platform {
case "ios":
applicationResponse.Platform.IOS = append(applicationResponse.Platform.IOS, &types.ApplicationVersion{
Id: applicationVersion.Id,
Url: applicationVersion.Url,
Version: applicationVersion.Version,
IsDefault: applicationVersion.IsDefault,
Description: applicationVersion.Description,
})
case "macos":
applicationResponse.Platform.MacOS = append(applicationResponse.Platform.MacOS, &types.ApplicationVersion{
Id: applicationVersion.Id,
Url: applicationVersion.Url,
Version: applicationVersion.Version,
IsDefault: applicationVersion.IsDefault,
Description: applicationVersion.Description,
})
case "linux":
applicationResponse.Platform.Linux = append(applicationResponse.Platform.Linux, &types.ApplicationVersion{
Id: applicationVersion.Id,
Url: applicationVersion.Url,
Version: applicationVersion.Version,
IsDefault: applicationVersion.IsDefault,
Description: applicationVersion.Description,
})
case "android":
applicationResponse.Platform.Android = append(applicationResponse.Platform.Android, &types.ApplicationVersion{
Id: applicationVersion.Id,
Url: applicationVersion.Url,
Version: applicationVersion.Version,
IsDefault: applicationVersion.IsDefault,
Description: applicationVersion.Description,
})
case "windows":
applicationResponse.Platform.Windows = append(applicationResponse.Platform.Windows, &types.ApplicationVersion{
Id: applicationVersion.Id,
Url: applicationVersion.Url,
Version: applicationVersion.Version,
IsDefault: applicationVersion.IsDefault,
Description: applicationVersion.Description,
})
case "harmony":
applicationResponse.Platform.Harmony = append(applicationResponse.Platform.Harmony, &types.ApplicationVersion{
Id: applicationVersion.Id,
Url: applicationVersion.Url,
Version: applicationVersion.Version,
IsDefault: applicationVersion.IsDefault,
Description: applicationVersion.Description,
})
}
}
}
resp.Applications = append(resp.Applications, applicationResponse)
}
return
}
@@ -0,0 +1,82 @@
package common
import (
"context"
"github.com/perfect-panel/ppanel-server/internal/svc"
"github.com/perfect-panel/ppanel-server/internal/types"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"github.com/perfect-panel/ppanel-server/pkg/tool"
"github.com/perfect-panel/ppanel-server/pkg/xerr"
"github.com/pkg/errors"
)
type GetGlobalConfigLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// Get global config
func NewGetGlobalConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetGlobalConfigLogic {
return &GetGlobalConfigLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetGlobalConfigLogic) GetGlobalConfig() (resp *types.GetGlobalConfigResponse, err error) {
resp = new(types.GetGlobalConfigResponse)
currencyCfg, err := l.svcCtx.SystemModel.GetCurrencyConfig(l.ctx)
if err != nil {
l.Logger.Error("[GetGlobalConfigLogic] GetCurrencyConfig error: ", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetCurrencyConfig error: %v", err.Error())
}
verifyCodeCfg, err := l.svcCtx.SystemModel.GetVerifyCodeConfig(l.ctx)
if err != nil {
l.Logger.Error("[GetGlobalConfigLogic] GetVerifyCodeConfig error: ", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetVerifyCodeConfig error: %v", err.Error())
}
tool.DeepCopy(&resp.Site, l.svcCtx.Config.Site)
tool.DeepCopy(&resp.Subscribe, l.svcCtx.Config.Subscribe)
tool.DeepCopy(&resp.Auth.Email, l.svcCtx.Config.Email)
tool.DeepCopy(&resp.Auth.Mobile, l.svcCtx.Config.Mobile)
tool.DeepCopy(&resp.Auth.Register, l.svcCtx.Config.Register)
tool.DeepCopy(&resp.Verify, l.svcCtx.Config.Verify)
tool.DeepCopy(&resp.Invite, l.svcCtx.Config.Invite)
tool.SystemConfigSliceReflectToStruct(currencyCfg, &resp.Currency)
tool.SystemConfigSliceReflectToStruct(verifyCodeCfg, &resp.VerifyCode)
resp.Verify = types.VeifyConfig{
TurnstileSiteKey: l.svcCtx.Config.Verify.TurnstileSiteKey,
EnableLoginVerify: l.svcCtx.Config.Verify.LoginVerify,
EnableRegisterVerify: l.svcCtx.Config.Verify.RegisterVerify,
EnableResetPasswordVerify: l.svcCtx.Config.Verify.ResetPasswordVerify,
}
var methods []string
// auth methods
authMethods, err := l.svcCtx.AuthModel.FindAll(l.ctx)
if err != nil {
l.Logger.Error("[GetGlobalConfigLogic] FindAll error: ", logger.Field("error", err.Error()))
}
for _, method := range authMethods {
if *method.Enabled {
methods = append(methods, method.Method)
}
}
resp.OAuthMethods = methods
webAds, err := l.svcCtx.SystemModel.FindOneByKey(l.ctx, "WebAD")
if err != nil {
l.Logger.Error("[GetGlobalConfigLogic] FindOneByKey error: ", logger.Field("error", err.Error()), logger.Field("key", "WebAD"))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindOneByKey error: %v", err.Error())
}
// web ads config
resp.WebAd = webAds.Value == "true"
return
}
@@ -0,0 +1,40 @@
package common
import (
"context"
"github.com/perfect-panel/ppanel-server/internal/svc"
"github.com/perfect-panel/ppanel-server/internal/types"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"github.com/perfect-panel/ppanel-server/pkg/tool"
"github.com/perfect-panel/ppanel-server/pkg/xerr"
"github.com/pkg/errors"
)
type GetPrivacyPolicyLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// Get Privacy Policy
func NewGetPrivacyPolicyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPrivacyPolicyLogic {
return &GetPrivacyPolicyLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetPrivacyPolicyLogic) GetPrivacyPolicy() (resp *types.PrivacyPolicyConfig, err error) {
resp = &types.PrivacyPolicyConfig{}
// get tos config from db
configs, err := l.svcCtx.SystemModel.GetTosConfig(l.ctx)
if err != nil {
l.Errorw("[GetTosConfig] GetTosConfig error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetTosConfig error: %v", err.Error())
}
// reflect to response
tool.SystemConfigSliceReflectToStruct(configs, resp)
return
}
+131
View File
@@ -0,0 +1,131 @@
package common
import (
"context"
"encoding/json"
"io"
"net"
"net/http"
"slices"
"strings"
"time"
"github.com/perfect-panel/ppanel-server/internal/config"
"github.com/perfect-panel/ppanel-server/internal/model/server"
"github.com/perfect-panel/ppanel-server/internal/model/user"
"github.com/perfect-panel/ppanel-server/internal/svc"
"github.com/perfect-panel/ppanel-server/internal/types"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"github.com/perfect-panel/ppanel-server/pkg/xerr"
"github.com/pkg/errors"
)
type GetStatLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// Get Tos
func NewGetStatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetStatLogic {
return &GetStatLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetStatLogic) GetStat() (resp *types.GetStatResponse, err error) {
respJson, err := l.svcCtx.Redis.Get(l.ctx, config.CommonStatCacheKey).Result()
if err == nil {
err = json.Unmarshal([]byte(respJson), resp)
if err == nil {
return
}
}
var u int64
err = l.svcCtx.DB.Model(&user.User{}).Where("enable = 1").Count(&u).Error
if err != nil {
l.Logger.Error("[GetStatLogic] get user count failed: ", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get user count failed: %v", err.Error())
}
if u > 100 {
u -= u % 100
} else if u > 10 {
u -= u % 10
} else {
u = 1
}
var n int64
err = l.svcCtx.DB.Model(&server.Server{}).Where("enable = 1").Count(&n).Error
if err != nil {
l.Logger.Error("[GetStatLogic] get server count failed: ", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get server count failed: %v", err.Error())
}
var nodeaddr []string
err = l.svcCtx.DB.Model(&server.Server{}).Where("enable = 1").Pluck("server_addr", &nodeaddr).Error
if err != nil {
l.Logger.Error("[GetStatLogic] get server_addr failed: ", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get server_addr failed: %v", err.Error())
}
type apireq struct {
query string
fields string
}
type apiret struct {
CountryCode string `json:"countryCode"`
}
//map as dict
type void struct{}
var v void
country := make(map[string]void)
for c := range slices.Chunk(nodeaddr, 100) {
var batchreq []apireq
for _, addr := range c {
isAddr := net.ParseIP(addr)
if isAddr == nil {
ip, err := net.LookupIP(addr)
if err == nil && len(ip) > 0 {
batchreq = append(batchreq, apireq{query: ip[0].String(), fields: "countryCode"})
}
} else {
batchreq = append(batchreq, apireq{query: addr, fields: "countryCode"})
}
}
req, _ := json.Marshal(batchreq)
ret, err := http.Post("http://ip-api.com/batch", "application/json", strings.NewReader(string(req)))
if err == nil {
retBytes, err := io.ReadAll(ret.Body)
if err == nil {
var retStruct []apiret
err := json.Unmarshal(retBytes, &retStruct)
if err == nil {
for _, dat := range retStruct {
if dat.CountryCode != "" {
country[dat.CountryCode] = v
}
}
}
}
}
}
protocolDict := make(map[string]void)
var protocol []string
l.svcCtx.DB.Model(&server.Server{}).Where("enable = true").Pluck("protocol", &protocol)
for _, p := range protocol {
protocolDict[p] = v
}
protocol = nil
for p := range protocolDict {
protocol = append(protocol, p)
}
resp = &types.GetStatResponse{
User: u,
Node: n,
Country: int64(len(country)),
Protocol: protocol,
}
val, _ := json.Marshal(*resp)
_ = l.svcCtx.Redis.Set(l.ctx, config.CommonStatCacheKey, string(val), time.Duration(3600)*time.Second).Err()
return resp, nil
}
@@ -0,0 +1,41 @@
package common
import (
"context"
"github.com/perfect-panel/ppanel-server/internal/svc"
"github.com/perfect-panel/ppanel-server/internal/types"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"github.com/perfect-panel/ppanel-server/pkg/tool"
"github.com/perfect-panel/ppanel-server/pkg/xerr"
"github.com/pkg/errors"
)
type GetSubscriptionLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// Get Subscription
func NewGetSubscriptionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSubscriptionLogic {
return &GetSubscriptionLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetSubscriptionLogic) GetSubscription() (resp *types.GetSubscriptionResponse, err error) {
resp = &types.GetSubscriptionResponse{
List: make([]types.Subscribe, 0),
}
// Get the subscription list
data, err := l.svcCtx.SubscribeModel.QuerySubscribeListByShow(l.ctx)
if err != nil {
l.Errorw("[Site GetSubscription]", logger.Field("err", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get subscription list error: %v", err.Error())
}
tool.DeepCopy(&resp.List, data)
return
}
+40
View File
@@ -0,0 +1,40 @@
package common
import (
"context"
"github.com/perfect-panel/ppanel-server/internal/svc"
"github.com/perfect-panel/ppanel-server/internal/types"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"github.com/perfect-panel/ppanel-server/pkg/tool"
"github.com/perfect-panel/ppanel-server/pkg/xerr"
"github.com/pkg/errors"
)
type GetTosLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// Get Tos
func NewGetTosLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTosLogic {
return &GetTosLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetTosLogic) GetTos() (resp *types.GetTosResponse, err error) {
resp = &types.GetTosResponse{}
// get Tos config from db
configs, err := l.svcCtx.SystemModel.GetTosConfig(l.ctx)
if err != nil {
l.Errorw("[GetTosLogic] GetTos error: ", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetTos error: %v", err.Error())
}
// reflect to response
tool.SystemConfigSliceReflectToStruct(configs, resp)
return
}
+156
View File
@@ -0,0 +1,156 @@
package common
import (
"bytes"
"context"
"encoding/json"
"fmt"
"text/template"
"time"
"github.com/hibiken/asynq"
"github.com/perfect-panel/ppanel-server/internal/config"
"github.com/perfect-panel/ppanel-server/pkg/constant"
"github.com/perfect-panel/ppanel-server/pkg/limit"
"github.com/perfect-panel/ppanel-server/pkg/random"
"github.com/pkg/errors"
"gorm.io/gorm"
"github.com/perfect-panel/ppanel-server/internal/svc"
"github.com/perfect-panel/ppanel-server/internal/types"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"github.com/perfect-panel/ppanel-server/pkg/xerr"
queue "github.com/perfect-panel/ppanel-server/queue/types"
)
type SendEmailCodeLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
const (
IntervalTime = 60
)
type VerifyTemplate struct {
Type uint8
SiteLogo string
SiteName string
Expire uint8
Code string
}
type CacheKeyPayload struct {
Code string `json:"code"`
LastAt int64 `json:"lastAt"`
}
// NewSendEmailCodeLogic Get verification code
func NewSendEmailCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendEmailCodeLogic {
return &SendEmailCodeLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SendEmailCodeLogic) SendEmailCode(req *types.SendCodeRequest) (resp *types.SendCodeResponse, err error) {
// Check if there is Redis in the code
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeCacheKey, constant.ParseVerifyType(req.Type), req.Email)
// Check if the limit is exceeded of current request
limiter := limit.NewPeriodLimit(60, 1, l.svcCtx.Redis, fmt.Sprintf("%s:%s:%s", config.SendIntervalKeyPrefix, "email", constant.ParseVerifyType(req.Type)))
permit, err := limiter.Take(req.Email)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Failed to take limit")
}
if !limiter.ParsePermitState(permit) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TooManyRequests), "send email too many requests")
}
// Check if the limit is exceeded of today
permit, err = l.svcCtx.AuthLimiter.Take(fmt.Sprintf("%s:%s:%s", "email", constant.ParseVerifyType(req.Type), req.Email))
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Failed to take limit")
}
if !l.svcCtx.AuthLimiter.ParsePermitState(permit) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TodaySendCountExceedsLimit), "send email too many requests")
}
m, err := l.svcCtx.UserModel.FindUserAuthMethodByOpenID(l.ctx, "email", req.Email)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindUserAuthMethodByOpenID error")
}
if constant.ParseVerifyType(req.Type) == constant.Register && m.Id > 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserExist), "mobile already bind")
} else if constant.ParseVerifyType(req.Type) == constant.Security && m.Id == 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "mobile not bind")
}
var payload CacheKeyPayload
var taskPayload queue.SendEmailPayload
// Generate verification code
code := random.Key(6, 0)
taskPayload.Email = req.Email
taskPayload.Subject = "Verification code"
content, err := l.initTemplate(req.Type, code)
if err != nil {
l.Logger.Error("[SendEmailCode]: InitTemplate Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Failed to init template")
}
taskPayload.Content = content
// Save to Redis
payload = CacheKeyPayload{
Code: code,
LastAt: time.Now().Unix(),
}
// Marshal the payload
val, _ := json.Marshal(payload)
if err = l.svcCtx.Redis.Set(l.ctx, cacheKey, string(val), time.Second*IntervalTime*5).Err(); err != nil {
l.Errorw("[SendEmailCode]: Redis Error", logger.Field("error", err.Error()), logger.Field("cacheKey", cacheKey))
return nil, errors.Wrap(xerr.NewErrCode(xerr.ERROR), "Failed to set verification code")
}
// Marshal the task payload
payloadBuy, err := json.Marshal(taskPayload)
if err != nil {
l.Errorw("[SendEmailCode]: Marshal Error", logger.Field("error", err.Error()))
return nil, errors.Wrap(xerr.NewErrCode(xerr.ERROR), "Failed to marshal task payload")
}
// Create a queue task
task := asynq.NewTask(queue.ForthwithSendEmail, payloadBuy, asynq.MaxRetry(3))
// Enqueue the task
taskInfo, err := l.svcCtx.Queue.Enqueue(task)
if err != nil {
l.Errorw("[SendEmailCode]: Enqueue Error", logger.Field("error", err.Error()), logger.Field("payload", string(payloadBuy)))
return nil, errors.Wrap(xerr.NewErrCode(xerr.ERROR), "Failed to enqueue task")
}
l.Infow("[SendEmailCode]: Enqueue Success", logger.Field("taskID", taskInfo.ID), logger.Field("payload", string(payloadBuy)))
if l.svcCtx.Config.Model == constant.DevMode {
return &types.SendCodeResponse{
Code: payload.Code,
Status: true,
}, nil
} else {
return &types.SendCodeResponse{
Status: true,
}, nil
}
}
func (l *SendEmailCodeLogic) initTemplate(t uint8, code string) (string, error) {
data := VerifyTemplate{
Type: t,
SiteLogo: l.svcCtx.Config.Site.SiteLogo,
SiteName: l.svcCtx.Config.Site.SiteName,
Expire: 5,
Code: code,
}
tpl, err := template.New("verify").Parse(l.svcCtx.Config.Email.VerifyEmailTemplate)
if err != nil {
return "", err
}
var result bytes.Buffer
err = tpl.Execute(&result, data)
if err != nil {
return "", err
}
return result.String(), nil
}
+123
View File
@@ -0,0 +1,123 @@
package common
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/hibiken/asynq"
"github.com/perfect-panel/ppanel-server/internal/config"
"github.com/perfect-panel/ppanel-server/internal/svc"
"github.com/perfect-panel/ppanel-server/internal/types"
"github.com/perfect-panel/ppanel-server/pkg/constant"
"github.com/perfect-panel/ppanel-server/pkg/limit"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"github.com/perfect-panel/ppanel-server/pkg/phone"
"github.com/perfect-panel/ppanel-server/pkg/random"
"github.com/perfect-panel/ppanel-server/pkg/xerr"
queue "github.com/perfect-panel/ppanel-server/queue/types"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type SmsSendCount struct {
Count int64 `json:"count"`
CreateAt int64 `json:"create_at"`
}
type SendSmsCodeLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// NewSendSmsCodeLogic Get sms verification code
func NewSendSmsCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsCodeLogic {
return &SendSmsCodeLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SendSmsCodeLogic) SendSmsCode(req *types.SendSmsCodeRequest) (resp *types.SendCodeResponse, err error) {
phoneNumber, err := phone.FormatToE164(req.TelephoneAreaCode, req.Telephone)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TelephoneError), "Invalid phone number")
}
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeTelephoneCacheKey, constant.ParseVerifyType(req.Type), phoneNumber)
// Check if the limit is exceeded of current request
limiter := limit.NewPeriodLimit(60, 1, l.svcCtx.Redis, fmt.Sprintf("%s:%s:%s", config.SendIntervalKeyPrefix, "mobile", constant.ParseVerifyType(req.Type)))
permit, err := limiter.Take(phoneNumber)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Failed to take limit")
}
if !limiter.ParsePermitState(permit) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TooManyRequests), "send sms too many requests")
}
// Check if the limit is exceeded of the today
permit, err = l.svcCtx.AuthLimiter.Take(fmt.Sprintf("%s:%s:%s", "mobile", constant.ParseVerifyType(req.Type), phoneNumber))
if err != nil {
return nil, err
}
if !l.svcCtx.AuthLimiter.ParsePermitState(permit) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TodaySendCountExceedsLimit), "This account has reached the limit of sending times today")
}
m, err := l.svcCtx.UserModel.FindUserAuthMethodByOpenID(l.ctx, "mobile", phoneNumber)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindUserAuthMethodByOpenID error")
}
if constant.ParseVerifyType(req.Type) == constant.Register && m.Id > 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserExist), "mobile already bind")
} else if constant.ParseVerifyType(req.Type) == constant.Security && m.Id == 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "mobile not bind")
}
taskPayload := queue.SendSmsPayload{
Type: req.Type,
Telephone: req.Telephone,
TelephoneArea: req.TelephoneAreaCode,
}
// Generate verification code
code := random.Key(6, 0)
taskPayload.Telephone = req.Telephone
taskPayload.Content = code
// Save to Redis
payload := CacheKeyPayload{
Code: code,
LastAt: time.Now().Unix(),
}
// Marshal the payload
val, _ := json.Marshal(payload)
if err = l.svcCtx.Redis.Set(l.ctx, cacheKey, string(val), time.Second*time.Duration(l.svcCtx.Config.VerifyCode.ExpireTime)).Err(); err != nil {
l.Errorw("[SendSmsCode]: Redis Error", logger.Field("error", err.Error()), logger.Field("cacheKey", cacheKey))
return nil, errors.Wrap(xerr.NewErrCode(xerr.ERROR), "Failed to set verification code")
}
// Marshal the task payload
payloadValue, err := json.Marshal(taskPayload)
if err != nil {
l.Errorw("[SendSmsCode]: Marshal Error", logger.Field("error", err.Error()))
return nil, errors.Wrap(xerr.NewErrCode(xerr.ERROR), "Failed to marshal task payload")
}
// Create a queue task
task := asynq.NewTask(queue.ForthwithSendSms, payloadValue)
// Enqueue the task
taskInfo, err := l.svcCtx.Queue.Enqueue(task)
if err != nil {
l.Errorw("[SendSmsCode]: Enqueue Error", logger.Field("error", err.Error()), logger.Field("payload", string(payloadValue)))
return nil, errors.Wrap(xerr.NewErrCode(xerr.ERROR), "Failed to enqueue task")
}
l.Infow("[SendSmsCode]: Enqueue Success", logger.Field("taskID", taskInfo.ID), logger.Field("payload", string(payloadValue)))
if l.svcCtx.Config.Model == constant.DevMode {
return &types.SendCodeResponse{
Code: taskPayload.Content,
Status: true,
}, nil
}
return &types.SendCodeResponse{
Status: true,
}, nil
}