Skip to content

Commit

Permalink
code refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
mayswind committed Aug 16, 2024
1 parent e532f37 commit 560edf9
Show file tree
Hide file tree
Showing 27 changed files with 437 additions and 245 deletions.
4 changes: 2 additions & 2 deletions cmd/webserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ func startWebServer(c *cli.Context) error {
router.StaticFile("/desktop/"+workboxFileNames[i], filepath.Join(config.StaticRootPath, workboxFileNames[i]))
}

if config.AvatarProvider == settings.InternalAvatarProvider {
if config.AvatarProvider == core.USER_AVATAR_PROVIDER_INTERNAL {
avatarRoute := router.Group("/avatar")
avatarRoute.Use(bindMiddleware(middlewares.JWTAuthorizationByQueryString))
{
Expand Down Expand Up @@ -261,7 +261,7 @@ func startWebServer(c *cli.Context) error {
apiV1Route.GET("/users/profile/get.json", bindApi(api.Users.UserProfileHandler))
apiV1Route.POST("/users/profile/update.json", bindApiWithTokenUpdate(api.Users.UserUpdateProfileHandler, config))

if config.AvatarProvider == settings.InternalAvatarProvider {
if config.AvatarProvider == core.USER_AVATAR_PROVIDER_INTERNAL {
apiV1Route.POST("/users/avatar/update.json", bindApi(api.Users.UserUpdateAvatarHandler))
apiV1Route.POST("/users/avatar/remove.json", bindApi(api.Users.UserRemoveAvatarHandler))
}
Expand Down
14 changes: 11 additions & 3 deletions pkg/api/accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,20 @@ import (

// AccountsApi represents account api
type AccountsApi struct {
ApiUsingConfig
ApiUsingDuplicateChecker
accounts *services.AccountService
}

// Initialize an account api singleton instance
var (
Accounts = &AccountsApi{
ApiUsingConfig: ApiUsingConfig{
container: settings.Container,
},
ApiUsingDuplicateChecker: ApiUsingDuplicateChecker{
container: duplicatechecker.Container,
},
accounts: services.Accounts,
}
)
Expand Down Expand Up @@ -211,8 +219,8 @@ func (a *AccountsApi) AccountCreateHandler(c *core.Context) (any, *errs.Error) {
mainAccount := a.createNewAccountModel(uid, &accountCreateReq, maxOrderId+1)
childrenAccounts := a.createSubAccountModels(uid, &accountCreateReq)

if settings.Container.Current.EnableDuplicateSubmissionsCheck && accountCreateReq.ClientSessionId != "" {
found, remark := duplicatechecker.Container.GetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_ACCOUNT, uid, accountCreateReq.ClientSessionId)
if a.CurrentConfig().EnableDuplicateSubmissionsCheck && accountCreateReq.ClientSessionId != "" {
found, remark := a.GetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_ACCOUNT, uid, accountCreateReq.ClientSessionId)

if found {
log.InfofWithRequestId(c, "[accounts.AccountCreateHandler] another account \"id:%s\" has been created for user \"uid:%d\"", remark, uid)
Expand Down Expand Up @@ -256,7 +264,7 @@ func (a *AccountsApi) AccountCreateHandler(c *core.Context) (any, *errs.Error) {

log.InfofWithRequestId(c, "[accounts.AccountCreateHandler] user \"uid:%d\" has created a new account \"id:%d\" successfully", uid, mainAccount.AccountId)

duplicatechecker.Container.SetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_ACCOUNT, uid, accountCreateReq.ClientSessionId, utils.Int64ToString(mainAccount.AccountId))
a.SetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_ACCOUNT, uid, accountCreateReq.ClientSessionId, utils.Int64ToString(mainAccount.AccountId))
accountInfoResp := mainAccount.ToAccountInfoResponse()

if len(childrenAccounts) > 0 {
Expand Down
9 changes: 7 additions & 2 deletions pkg/api/amap_api_proxies.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,16 @@ const amapRestApiUrl = "https://restapi.amap.com/"

// AmapApiProxy represents amap api proxy
type AmapApiProxy struct {
ApiUsingConfig
}

// Initialize a amap api proxy singleton instance
var (
AmapApis = &AmapApiProxy{}
AmapApis = &AmapApiProxy{
ApiUsingConfig: ApiUsingConfig{
container: settings.Container,
},
}
)

// AmapApiProxyHandler returns amap api response
Expand All @@ -38,7 +43,7 @@ func (p *AmapApiProxy) AmapApiProxyHandler(c *core.Context) (*httputil.ReversePr
}

director := func(req *http.Request) {
targetRawUrl := fmt.Sprintf("%s?%s&jscode=%s", targetUrl, req.URL.RawQuery, settings.Container.Current.AmapApplicationSecret)
targetRawUrl := fmt.Sprintf("%s?%s&jscode=%s", targetUrl, req.URL.RawQuery, p.CurrentConfig().AmapApplicationSecret)
targetUrl, _ := url.Parse(targetRawUrl)

oldCookies := req.Cookies()
Expand Down
14 changes: 9 additions & 5 deletions pkg/api/authorizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

// AuthorizationsApi represents authorization api
type AuthorizationsApi struct {
ApiUsingConfig
users *services.UserService
tokens *services.TokenService
twoFactorAuthorizations *services.TwoFactorAuthorizationService
Expand All @@ -21,6 +22,9 @@ type AuthorizationsApi struct {
// Initialize a authorization api singleton instance
var (
Authorizations = &AuthorizationsApi{
ApiUsingConfig: ApiUsingConfig{
container: settings.Container,
},
users: services.Users,
tokens: services.Tokens,
twoFactorAuthorizations: services.TwoFactorAuthorizations,
Expand Down Expand Up @@ -49,7 +53,7 @@ func (a *AuthorizationsApi) AuthorizeHandler(c *core.Context) (any, *errs.Error)
return nil, errs.ErrUserIsDisabled
}

if settings.Container.Current.EnableUserForceVerifyEmail && !user.EmailVerified {
if a.CurrentConfig().EnableUserForceVerifyEmail && !user.EmailVerified {
hasValidEmailVerifyToken, err := a.tokens.ExistsValidTokenByType(c, user.Uid, core.USER_TOKEN_TYPE_EMAIL_VERIFY)

if err != nil {
Expand Down Expand Up @@ -143,7 +147,7 @@ func (a *AuthorizationsApi) TwoFactorAuthorizeHandler(c *core.Context) (any, *er
return nil, errs.ErrUserIsDisabled
}

if settings.Container.Current.EnableUserForceVerifyEmail && !user.EmailVerified {
if a.CurrentConfig().EnableUserForceVerifyEmail && !user.EmailVerified {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeHandler] user \"uid:%d\" has not verified email", user.Uid)
return nil, errs.ErrEmailIsNotVerified
}
Expand Down Expand Up @@ -205,7 +209,7 @@ func (a *AuthorizationsApi) TwoFactorAuthorizeByRecoveryCodeHandler(c *core.Cont
return nil, errs.ErrUserIsDisabled
}

if settings.Container.Current.EnableUserForceVerifyEmail && !user.EmailVerified {
if a.CurrentConfig().EnableUserForceVerifyEmail && !user.EmailVerified {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] user \"uid:%d\" has not verified email", user.Uid)
return nil, errs.ErrEmailIsNotVerified
}
Expand Down Expand Up @@ -244,7 +248,7 @@ func (a *AuthorizationsApi) getAuthResponse(c *core.Context, token string, need2
return &models.AuthResponse{
Token: token,
Need2FA: need2FA,
User: user.ToUserBasicInfo(),
NotificationContent: settings.Container.GetAfterLoginNotificationContent(user.Language, c.GetClientLocale()),
User: a.GetUserBasicInfo(user),
NotificationContent: a.GetAfterLoginNotificationContent(user.Language, c.GetClientLocale()),
}
}
94 changes: 94 additions & 0 deletions pkg/api/base.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package api

import (
"github.com/mayswind/ezbookkeeping/pkg/duplicatechecker"
"github.com/mayswind/ezbookkeeping/pkg/models"
"github.com/mayswind/ezbookkeeping/pkg/settings"
)

// ApiUsingConfig represents an api that need to use config
type ApiUsingConfig struct {
container *settings.ConfigContainer
}

// CurrentConfig returns the current config
func (a *ApiUsingConfig) CurrentConfig() *settings.Config {
return a.container.Current
}

// GetUserBasicInfo returns the view-object of user basic info according to the user model
func (a *ApiUsingConfig) GetUserBasicInfo(user *models.User) *models.UserBasicInfo {
return user.ToUserBasicInfo(a.CurrentConfig().AvatarProvider, a.CurrentConfig().RootUrl)
}

// GetAfterRegisterNotificationContent returns the notification content displayed each time users register
func (a *ApiUsingConfig) GetAfterRegisterNotificationContent(userLanguage string, clientLanguage string) string {
language := userLanguage

if language == "" {
language = clientLanguage
}

if !a.container.Current.AfterRegisterNotification.Enabled {
return ""
}

if multiLanguageContent, exists := a.container.Current.AfterRegisterNotification.MultiLanguageContent[language]; exists {
return multiLanguageContent
}

return a.container.Current.AfterRegisterNotification.DefaultContent
}

// GetAfterLoginNotificationContent returns the notification content displayed each time users log in
func (a *ApiUsingConfig) GetAfterLoginNotificationContent(userLanguage string, clientLanguage string) string {
language := userLanguage

if language == "" {
language = clientLanguage
}

if !a.container.Current.AfterLoginNotification.Enabled {
return ""
}

if multiLanguageContent, exists := a.container.Current.AfterLoginNotification.MultiLanguageContent[language]; exists {
return multiLanguageContent
}

return a.container.Current.AfterLoginNotification.DefaultContent
}

// GetAfterOpenNotificationContent returns the notification content displayed each time users open the app
func (a *ApiUsingConfig) GetAfterOpenNotificationContent(userLanguage string, clientLanguage string) string {
language := userLanguage

if language == "" {
language = clientLanguage
}

if !a.container.Current.AfterOpenNotification.Enabled {
return ""
}

if multiLanguageContent, exists := a.container.Current.AfterOpenNotification.MultiLanguageContent[language]; exists {
return multiLanguageContent
}

return a.container.Current.AfterOpenNotification.DefaultContent
}

// ApiUsingDuplicateChecker represents an api that need to use duplicate checker
type ApiUsingDuplicateChecker struct {
container *duplicatechecker.DuplicateCheckerContainer
}

// GetSubmissionRemark returns whether the same submission has been processed and related remark by the current duplicate checker
func (a *ApiUsingDuplicateChecker) GetSubmissionRemark(checkerType duplicatechecker.DuplicateCheckerType, uid int64, identification string) (bool, string) {
return a.container.GetSubmissionRemark(checkerType, uid, identification)
}

// SetSubmissionRemark saves the identification and remark to in-memory cache by the current duplicate checker
func (a *ApiUsingDuplicateChecker) SetSubmissionRemark(checkerType duplicatechecker.DuplicateCheckerType, uid int64, identification string, remark string) {
a.container.SetSubmissionRemark(checkerType, uid, identification, remark)
}
6 changes: 5 additions & 1 deletion pkg/api/data_managements.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const pageCountForDataExport = 1000

// DataManagementsApi represents data management api
type DataManagementsApi struct {
ApiUsingConfig
ezBookKeepingCsvExporter *converters.EzBookKeepingCSVFileExporter
ezBookKeepingTsvExporter *converters.EzBookKeepingTSVFileExporter
tokens *services.TokenService
Expand All @@ -33,6 +34,9 @@ type DataManagementsApi struct {
// Initialize a data management api singleton instance
var (
DataManagements = &DataManagementsApi{
ApiUsingConfig: ApiUsingConfig{
container: settings.Container,
},
ezBookKeepingCsvExporter: &converters.EzBookKeepingCSVFileExporter{},
ezBookKeepingTsvExporter: &converters.EzBookKeepingTSVFileExporter{},
tokens: services.Tokens,
Expand Down Expand Up @@ -162,7 +166,7 @@ func (a *DataManagementsApi) ClearDataHandler(c *core.Context) (any, *errs.Error
}

func (a *DataManagementsApi) getExportedFileContent(c *core.Context, fileType string) ([]byte, string, *errs.Error) {
if !settings.Container.Current.EnableDataExport {
if !a.CurrentConfig().EnableDataExport {
return nil, "", errs.ErrDataExportNotAllowed
}

Expand Down
16 changes: 11 additions & 5 deletions pkg/api/exchange_rates.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,17 @@ import (
)

// ExchangeRatesApi represents exchange rate api
type ExchangeRatesApi struct{}
type ExchangeRatesApi struct {
ApiUsingConfig
}

// Initialize a exchange rate api singleton instance
var (
ExchangeRates = &ExchangeRatesApi{}
ExchangeRates = &ExchangeRatesApi{
ApiUsingConfig: ApiUsingConfig{
container: settings.Container,
},
}
)

// LatestExchangeRateHandler returns latest exchange rate data
Expand All @@ -36,17 +42,17 @@ func (a *ExchangeRatesApi) LatestExchangeRateHandler(c *core.Context) (any, *err
uid := c.GetCurrentUid()

transport := http.DefaultTransport.(*http.Transport).Clone()
utils.SetProxyUrl(transport, settings.Container.Current.ExchangeRatesProxy)
utils.SetProxyUrl(transport, a.CurrentConfig().ExchangeRatesProxy)

if settings.Container.Current.ExchangeRatesSkipTLSVerify {
if a.CurrentConfig().ExchangeRatesSkipTLSVerify {
transport.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
}

client := &http.Client{
Transport: transport,
Timeout: time.Duration(settings.Container.Current.ExchangeRatesRequestTimeout) * time.Millisecond,
Timeout: time.Duration(a.CurrentConfig().ExchangeRatesRequestTimeout) * time.Millisecond,
}

urls := dataSource.GetRequestUrls()
Expand Down
10 changes: 7 additions & 3 deletions pkg/api/forget_passwords.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

// ForgetPasswordsApi represents user forget password api
type ForgetPasswordsApi struct {
ApiUsingConfig
users *services.UserService
tokens *services.TokenService
forgetPasswords *services.ForgetPasswordService
Expand All @@ -21,6 +22,9 @@ type ForgetPasswordsApi struct {
// Initialize a user api singleton instance
var (
ForgetPasswords = &ForgetPasswordsApi{
ApiUsingConfig: ApiUsingConfig{
container: settings.Container,
},
users: services.Users,
tokens: services.Tokens,
forgetPasswords: services.ForgetPasswords,
Expand Down Expand Up @@ -52,12 +56,12 @@ func (a *ForgetPasswordsApi) UserForgetPasswordRequestHandler(c *core.Context) (
return nil, errs.ErrUserIsDisabled
}

if settings.Container.Current.ForgetPasswordRequireVerifyEmail && !user.EmailVerified {
if a.CurrentConfig().ForgetPasswordRequireVerifyEmail && !user.EmailVerified {
log.WarnfWithRequestId(c, "[forget_passwords.UserForgetPasswordRequestHandler] user \"uid:%d\" has not verified email", user.Uid)
return nil, errs.ErrEmailIsNotVerified
}

if !settings.Container.Current.EnableSMTP {
if !a.CurrentConfig().EnableSMTP {
return nil, errs.ErrSMTPServerNotEnabled
}

Expand Down Expand Up @@ -105,7 +109,7 @@ func (a *ForgetPasswordsApi) UserResetPasswordHandler(c *core.Context) (any, *er
return nil, errs.ErrUserIsDisabled
}

if settings.Container.Current.ForgetPasswordRequireVerifyEmail && !user.EmailVerified {
if a.CurrentConfig().ForgetPasswordRequireVerifyEmail && !user.EmailVerified {
log.WarnfWithRequestId(c, "[forget_passwords.UserResetPasswordHandler] user \"uid:%d\" has not verified email", user.Uid)
return nil, errs.ErrEmailIsNotVerified
}
Expand Down
Loading

0 comments on commit 560edf9

Please sign in to comment.