code refactor

This commit is contained in:
MaysWind
2024-08-19 00:31:32 +08:00
parent 6fcb0a2b3c
commit e86d4e05ce
73 changed files with 1404 additions and 1344 deletions
+14
View File
@@ -0,0 +1,14 @@
package cmd
import (
"github.com/urfave/cli/v2"
"github.com/mayswind/ezbookkeeping/pkg/core"
)
func bindAction(fn core.CliHandlerFunc) cli.ActionFunc {
return func(cliCtx *cli.Context) error {
c := core.WrapCilContext(cliCtx)
return fn(c)
}
}
+11 -10
View File
@@ -5,6 +5,7 @@ import (
"github.com/urfave/cli/v2"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/cron"
"github.com/mayswind/ezbookkeeping/pkg/log"
)
@@ -17,12 +18,12 @@ var CronJobs = &cli.Command{
{
Name: "list",
Usage: "List all enabled cron jobs",
Action: listAllCronJobs,
Action: bindAction(listAllCronJobs),
},
{
Name: "run",
Usage: "Run specified cron job",
Action: runCronJob,
Action: bindAction(runCronJob),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
@@ -35,24 +36,24 @@ var CronJobs = &cli.Command{
},
}
func listAllCronJobs(c *cli.Context) error {
func listAllCronJobs(c *core.CliContext) error {
config, err := initializeSystem(c)
if err != nil {
return err
}
err = cron.InitializeCronJobSchedulerContainer(config, false)
err = cron.InitializeCronJobSchedulerContainer(c, config, false)
if err != nil {
log.BootErrorf("[cron_jobs.listAllCronJobs] initializes cron job scheduler failed, because %s", err.Error())
log.BootErrorf(c, "[cron_jobs.listAllCronJobs] initializes cron job scheduler failed, because %s", err.Error())
return err
}
cronJobs := cron.Container.GetAllJobs()
if len(cronJobs) < 1 {
log.BootErrorf("[cron_jobs.listAllCronJobs] there are no enabled cron jobs")
log.BootErrorf(c, "[cron_jobs.listAllCronJobs] there are no enabled cron jobs")
return err
}
@@ -71,17 +72,17 @@ func listAllCronJobs(c *cli.Context) error {
return nil
}
func runCronJob(c *cli.Context) error {
func runCronJob(c *core.CliContext) error {
config, err := initializeSystem(c)
if err != nil {
return err
}
err = cron.InitializeCronJobSchedulerContainer(config, false)
err = cron.InitializeCronJobSchedulerContainer(c, config, false)
if err != nil {
log.BootErrorf("[cron_jobs.runCronJob] initializes cron job scheduler failed, because %s", err.Error())
log.BootErrorf(c, "[cron_jobs.runCronJob] initializes cron job scheduler failed, because %s", err.Error())
return err
}
@@ -89,7 +90,7 @@ func runCronJob(c *cli.Context) error {
err = cron.Container.SyncRunJobNow(jobName)
if err != nil {
log.BootErrorf("[cron_jobs.runCronJob] failed to run cron job \"%s\", because %s", jobName, err.Error())
log.BootErrorf(c, "[cron_jobs.runCronJob] failed to run cron job \"%s\", because %s", jobName, err.Error())
return err
}
+18 -17
View File
@@ -3,6 +3,7 @@ package cmd
import (
"github.com/urfave/cli/v2"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/datastore"
"github.com/mayswind/ezbookkeeping/pkg/log"
"github.com/mayswind/ezbookkeeping/pkg/models"
@@ -16,32 +17,32 @@ var Database = &cli.Command{
{
Name: "update",
Usage: "Update database structure",
Action: updateDatabaseStructure,
Action: bindAction(updateDatabaseStructure),
},
},
}
func updateDatabaseStructure(c *cli.Context) error {
func updateDatabaseStructure(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
return err
}
log.BootInfof("[database.updateDatabaseStructure] starting maintaining")
log.BootInfof(c, "[database.updateDatabaseStructure] starting maintaining")
err = updateAllDatabaseTablesStructure()
err = updateAllDatabaseTablesStructure(c)
if err != nil {
log.BootErrorf("[database.updateDatabaseStructure] update database table structure failed, because %s", err.Error())
log.BootErrorf(c, "[database.updateDatabaseStructure] update database table structure failed, because %s", err.Error())
return err
}
log.BootInfof("[database.updateDatabaseStructure] all tables maintained successfully")
log.BootInfof(c, "[database.updateDatabaseStructure] all tables maintained successfully")
return nil
}
func updateAllDatabaseTablesStructure() error {
func updateAllDatabaseTablesStructure(c *core.CliContext) error {
var err error
err = datastore.Container.UserStore.SyncStructs(new(models.User))
@@ -50,7 +51,7 @@ func updateAllDatabaseTablesStructure() error {
return err
}
log.BootInfof("[database.updateAllDatabaseTablesStructure] user table maintained successfully")
log.BootInfof(c, "[database.updateAllDatabaseTablesStructure] user table maintained successfully")
err = datastore.Container.UserStore.SyncStructs(new(models.TwoFactor))
@@ -58,7 +59,7 @@ func updateAllDatabaseTablesStructure() error {
return err
}
log.BootInfof("[database.updateAllDatabaseTablesStructure] two-factor table maintained successfully")
log.BootInfof(c, "[database.updateAllDatabaseTablesStructure] two-factor table maintained successfully")
err = datastore.Container.UserStore.SyncStructs(new(models.TwoFactorRecoveryCode))
@@ -66,7 +67,7 @@ func updateAllDatabaseTablesStructure() error {
return err
}
log.BootInfof("[database.updateAllDatabaseTablesStructure] two-factor recovery code table maintained successfully")
log.BootInfof(c, "[database.updateAllDatabaseTablesStructure] two-factor recovery code table maintained successfully")
err = datastore.Container.TokenStore.SyncStructs(new(models.TokenRecord))
@@ -74,7 +75,7 @@ func updateAllDatabaseTablesStructure() error {
return err
}
log.BootInfof("[database.updateAllDatabaseTablesStructure] token record table maintained successfully")
log.BootInfof(c, "[database.updateAllDatabaseTablesStructure] token record table maintained successfully")
err = datastore.Container.UserDataStore.SyncStructs(new(models.Account))
@@ -82,7 +83,7 @@ func updateAllDatabaseTablesStructure() error {
return err
}
log.BootInfof("[database.updateAllDatabaseTablesStructure] account table maintained successfully")
log.BootInfof(c, "[database.updateAllDatabaseTablesStructure] account table maintained successfully")
err = datastore.Container.UserDataStore.SyncStructs(new(models.Transaction))
@@ -90,7 +91,7 @@ func updateAllDatabaseTablesStructure() error {
return err
}
log.BootInfof("[database.updateAllDatabaseTablesStructure] transaction table maintained successfully")
log.BootInfof(c, "[database.updateAllDatabaseTablesStructure] transaction table maintained successfully")
err = datastore.Container.UserDataStore.SyncStructs(new(models.TransactionCategory))
@@ -98,7 +99,7 @@ func updateAllDatabaseTablesStructure() error {
return err
}
log.BootInfof("[database.updateAllDatabaseTablesStructure] transaction category table maintained successfully")
log.BootInfof(c, "[database.updateAllDatabaseTablesStructure] transaction category table maintained successfully")
err = datastore.Container.UserDataStore.SyncStructs(new(models.TransactionTag))
@@ -106,7 +107,7 @@ func updateAllDatabaseTablesStructure() error {
return err
}
log.BootInfof("[database.updateAllDatabaseTablesStructure] transaction tag table maintained successfully")
log.BootInfof(c, "[database.updateAllDatabaseTablesStructure] transaction tag table maintained successfully")
err = datastore.Container.UserDataStore.SyncStructs(new(models.TransactionTagIndex))
@@ -114,7 +115,7 @@ func updateAllDatabaseTablesStructure() error {
return err
}
log.BootInfof("[database.updateAllDatabaseTablesStructure] transaction tag index table maintained successfully")
log.BootInfof(c, "[database.updateAllDatabaseTablesStructure] transaction tag index table maintained successfully")
err = datastore.Container.UserDataStore.SyncStructs(new(models.TransactionTemplate))
@@ -122,7 +123,7 @@ func updateAllDatabaseTablesStructure() error {
return err
}
log.BootInfof("[database.updateAllDatabaseTablesStructure] transaction template table maintained successfully")
log.BootInfof(c, "[database.updateAllDatabaseTablesStructure] transaction template table maintained successfully")
return nil
}
+16 -17
View File
@@ -4,8 +4,7 @@ import (
"encoding/json"
"os"
"github.com/urfave/cli/v2"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/datastore"
"github.com/mayswind/ezbookkeeping/pkg/duplicatechecker"
"github.com/mayswind/ezbookkeeping/pkg/exchangerates"
@@ -17,7 +16,7 @@ import (
"github.com/mayswind/ezbookkeeping/pkg/uuid"
)
func initializeSystem(c *cli.Context) (*settings.Config, error) {
func initializeSystem(c *core.CliContext) (*settings.Config, error) {
var err error
configFilePath := c.String("conf-path")
isDisableBootLog := c.Bool("no-boot-log")
@@ -25,26 +24,26 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
if configFilePath != "" {
if _, err = os.Stat(configFilePath); err != nil {
if !isDisableBootLog {
log.BootErrorf("[initializer.initializeSystem] cannot load configuration from custom config path %s, because file not exists", configFilePath)
log.BootErrorf(c, "[initializer.initializeSystem] cannot load configuration from custom config path %s, because file not exists", configFilePath)
}
return nil, err
}
if !isDisableBootLog {
log.BootInfof("[initializer.initializeSystem] will loading configuration from custom config path %s", configFilePath)
log.BootInfof(c, "[initializer.initializeSystem] will loading configuration from custom config path %s", configFilePath)
}
} else {
configFilePath, err = settings.GetDefaultConfigFilePath()
if err != nil {
if !isDisableBootLog {
log.BootErrorf("[initializer.initializeSystem] cannot get default configuration path, because %s", err.Error())
log.BootErrorf(c, "[initializer.initializeSystem] cannot get default configuration path, because %s", err.Error())
}
return nil, err
}
if !isDisableBootLog {
log.BootInfof("[initializer.initializeSystem] will load configuration from default config path %s", configFilePath)
log.BootInfof(c, "[initializer.initializeSystem] will load configuration from default config path %s", configFilePath)
}
}
@@ -52,13 +51,13 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
if err != nil {
if !isDisableBootLog {
log.BootErrorf("[initializer.initializeSystem] cannot load configuration, because %s", err.Error())
log.BootErrorf(c, "[initializer.initializeSystem] cannot load configuration, because %s", err.Error())
}
return nil, err
}
if config.SecretKeyNoSet {
log.BootWarnf("[initializer.initializeSystem] \"secret_key\" in config file is not set, please change it to keep your user data safe")
log.BootWarnf(c, "[initializer.initializeSystem] \"secret_key\" in config file is not set, please change it to keep your user data safe")
}
settings.SetCurrentConfig(config)
@@ -67,7 +66,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
if err != nil {
if !isDisableBootLog {
log.BootErrorf("[initializer.initializeSystem] initializes data store failed, because %s", err.Error())
log.BootErrorf(c, "[initializer.initializeSystem] initializes data store failed, because %s", err.Error())
}
return nil, err
}
@@ -76,7 +75,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
if err != nil {
if !isDisableBootLog {
log.BootErrorf("[initializer.initializeSystem] sets logger configuration failed, because %s", err.Error())
log.BootErrorf(c, "[initializer.initializeSystem] sets logger configuration failed, because %s", err.Error())
}
return nil, err
}
@@ -85,7 +84,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
if err != nil {
if !isDisableBootLog {
log.BootErrorf("[initializer.initializeSystem] initializes object storage failed, because %s", err.Error())
log.BootErrorf(c, "[initializer.initializeSystem] initializes object storage failed, because %s", err.Error())
}
return nil, err
}
@@ -94,7 +93,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
if err != nil {
if !isDisableBootLog {
log.BootErrorf("[initializer.initializeSystem] initializes uuid generator failed, because %s", err.Error())
log.BootErrorf(c, "[initializer.initializeSystem] initializes uuid generator failed, because %s", err.Error())
}
return nil, err
}
@@ -103,7 +102,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
if err != nil {
if !isDisableBootLog {
log.BootErrorf("[initializer.initializeSystem] initializes duplicate checker failed, because %s", err.Error())
log.BootErrorf(c, "[initializer.initializeSystem] initializes duplicate checker failed, because %s", err.Error())
}
return nil, err
}
@@ -112,7 +111,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
if err != nil {
if !isDisableBootLog {
log.BootErrorf("[initializer.initializeSystem] initializes mailer failed, because %s", err.Error())
log.BootErrorf(c, "[initializer.initializeSystem] initializes mailer failed, because %s", err.Error())
}
return nil, err
}
@@ -121,7 +120,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
if err != nil {
if !isDisableBootLog {
log.BootErrorf("[initializer.initializeSystem] initializes exchange rates data source failed, because %s", err.Error())
log.BootErrorf(c, "[initializer.initializeSystem] initializes exchange rates data source failed, because %s", err.Error())
}
return nil, err
}
@@ -129,7 +128,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
cfgJson, _ := json.Marshal(getConfigWithoutSensitiveData(config))
if !isDisableBootLog {
log.BootInfof("[initializer.initializeSystem] has loaded configuration %s", cfgJson)
log.BootInfof(c, "[initializer.initializeSystem] has loaded configuration %s", cfgJson)
}
return config, nil
+3 -2
View File
@@ -5,6 +5,7 @@ import (
"github.com/urfave/cli/v2"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/utils"
)
@@ -16,7 +17,7 @@ var SecurityUtils = &cli.Command{
{
Name: "gen-secret-key",
Usage: "Generate a random secret key",
Action: genSecretKey,
Action: bindAction(genSecretKey),
Flags: []cli.Flag{
&cli.IntFlag{
Name: "length",
@@ -30,7 +31,7 @@ var SecurityUtils = &cli.Command{
},
}
func genSecretKey(c *cli.Context) error {
func genSecretKey(c *core.CliContext) error {
length := c.Int("length")
if length <= 0 {
+69 -68
View File
@@ -7,6 +7,7 @@ import (
"github.com/urfave/cli/v2"
clis "github.com/mayswind/ezbookkeeping/pkg/cli"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/log"
"github.com/mayswind/ezbookkeeping/pkg/models"
@@ -21,7 +22,7 @@ var UserData = &cli.Command{
{
Name: "user-add",
Usage: "Add new user",
Action: addNewUser,
Action: bindAction(addNewUser),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -58,7 +59,7 @@ var UserData = &cli.Command{
{
Name: "user-get",
Usage: "Get specified user info",
Action: getUserInfo,
Action: bindAction(getUserInfo),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -71,7 +72,7 @@ var UserData = &cli.Command{
{
Name: "user-modify-password",
Usage: "Modify user password",
Action: modifyUserPassword,
Action: bindAction(modifyUserPassword),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -90,7 +91,7 @@ var UserData = &cli.Command{
{
Name: "user-enable",
Usage: "Enable specified user",
Action: enableUser,
Action: bindAction(enableUser),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -103,7 +104,7 @@ var UserData = &cli.Command{
{
Name: "user-disable",
Usage: "Disable specified user",
Action: disableUser,
Action: bindAction(disableUser),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -116,7 +117,7 @@ var UserData = &cli.Command{
{
Name: "user-resend-verify-email",
Usage: "Resend user verify email",
Action: resendUserVerifyEmail,
Action: bindAction(resendUserVerifyEmail),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -129,7 +130,7 @@ var UserData = &cli.Command{
{
Name: "user-set-email-verified",
Usage: "Set user email address verified",
Action: setUserEmailVerified,
Action: bindAction(setUserEmailVerified),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -142,7 +143,7 @@ var UserData = &cli.Command{
{
Name: "user-set-email-unverified",
Usage: "Set user email address unverified",
Action: setUserEmailUnverified,
Action: bindAction(setUserEmailUnverified),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -155,7 +156,7 @@ var UserData = &cli.Command{
{
Name: "user-delete",
Usage: "Delete specified user",
Action: deleteUser,
Action: bindAction(deleteUser),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -168,7 +169,7 @@ var UserData = &cli.Command{
{
Name: "user-2fa-disable",
Usage: "Disable user 2fa setting",
Action: disableUser2FA,
Action: bindAction(disableUser2FA),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -181,7 +182,7 @@ var UserData = &cli.Command{
{
Name: "user-session-list",
Usage: "List all user sessions",
Action: listUserTokens,
Action: bindAction(listUserTokens),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -194,7 +195,7 @@ var UserData = &cli.Command{
{
Name: "user-session-clear",
Usage: "Clear user all sessions",
Action: clearUserTokens,
Action: bindAction(clearUserTokens),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -207,7 +208,7 @@ var UserData = &cli.Command{
{
Name: "send-password-reset-mail",
Usage: "Send password reset mail",
Action: sendPasswordResetMail,
Action: bindAction(sendPasswordResetMail),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -220,7 +221,7 @@ var UserData = &cli.Command{
{
Name: "transaction-check",
Usage: "Check whether user all transactions and accounts are correct",
Action: checkUserTransactionAndAccount,
Action: bindAction(checkUserTransactionAndAccount),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -233,7 +234,7 @@ var UserData = &cli.Command{
{
Name: "transaction-tag-index-fix-transaction-time",
Usage: "Fix the transaction tag index data which does not have transaction time",
Action: fixTransactionTagIndexNotHaveTransactionTime,
Action: bindAction(fixTransactionTagIndexNotHaveTransactionTime),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -246,7 +247,7 @@ var UserData = &cli.Command{
{
Name: "transaction-export",
Usage: "Export user all transactions to file",
Action: exportUserTransaction,
Action: bindAction(exportUserTransaction),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
@@ -271,7 +272,7 @@ var UserData = &cli.Command{
},
}
func addNewUser(c *cli.Context) error {
func addNewUser(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -287,7 +288,7 @@ func addNewUser(c *cli.Context) error {
user, err := clis.UserData.AddNewUser(c, username, email, nickname, password, defaultCurrency)
if err != nil {
log.BootErrorf("[user_data.addNewUser] error occurs when adding new user")
log.BootErrorf(c, "[user_data.addNewUser] error occurs when adding new user")
return err
}
@@ -296,7 +297,7 @@ func addNewUser(c *cli.Context) error {
return nil
}
func getUserInfo(c *cli.Context) error {
func getUserInfo(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -307,7 +308,7 @@ func getUserInfo(c *cli.Context) error {
user, err := clis.UserData.GetUserByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.getUserInfo] error occurs when getting user data")
log.BootErrorf(c, "[user_data.getUserInfo] error occurs when getting user data")
return err
}
@@ -316,7 +317,7 @@ func getUserInfo(c *cli.Context) error {
return nil
}
func modifyUserPassword(c *cli.Context) error {
func modifyUserPassword(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -328,16 +329,16 @@ func modifyUserPassword(c *cli.Context) error {
err = clis.UserData.ModifyUserPassword(c, username, password)
if err != nil {
log.BootErrorf("[user_data.modifyUserPassword] error occurs when modifying user password")
log.BootErrorf(c, "[user_data.modifyUserPassword] error occurs when modifying user password")
return err
}
log.BootInfof("[user_data.modifyUserPassword] password of user \"%s\" has been changed", username)
log.BootInfof(c, "[user_data.modifyUserPassword] password of user \"%s\" has been changed", username)
return nil
}
func sendPasswordResetMail(c *cli.Context) error {
func sendPasswordResetMail(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -348,16 +349,16 @@ func sendPasswordResetMail(c *cli.Context) error {
err = clis.UserData.SendPasswordResetMail(c, username)
if err != nil {
log.BootErrorf("[user_data.sendPasswordResetMail] error occurs when sending password reset email")
log.BootErrorf(c, "[user_data.sendPasswordResetMail] error occurs when sending password reset email")
return err
}
log.BootInfof("[user_data.sendPasswordResetMail] a password reset email for user \"%s\" has been sent", username)
log.BootInfof(c, "[user_data.sendPasswordResetMail] a password reset email for user \"%s\" has been sent", username)
return nil
}
func enableUser(c *cli.Context) error {
func enableUser(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -368,16 +369,16 @@ func enableUser(c *cli.Context) error {
err = clis.UserData.EnableUser(c, username)
if err != nil {
log.BootErrorf("[user_data.enableUser] error occurs when setting user enabled")
log.BootErrorf(c, "[user_data.enableUser] error occurs when setting user enabled")
return err
}
log.BootInfof("[user_data.enableUser] user \"%s\" has been set enabled", username)
log.BootInfof(c, "[user_data.enableUser] user \"%s\" has been set enabled", username)
return nil
}
func disableUser(c *cli.Context) error {
func disableUser(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -388,16 +389,16 @@ func disableUser(c *cli.Context) error {
err = clis.UserData.DisableUser(c, username)
if err != nil {
log.BootErrorf("[user_data.disableUser] error occurs when setting user disabled")
log.BootErrorf(c, "[user_data.disableUser] error occurs when setting user disabled")
return err
}
log.BootInfof("[user_data.disableUser] user \"%s\" has been set disabled", username)
log.BootInfof(c, "[user_data.disableUser] user \"%s\" has been set disabled", username)
return nil
}
func resendUserVerifyEmail(c *cli.Context) error {
func resendUserVerifyEmail(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -408,16 +409,16 @@ func resendUserVerifyEmail(c *cli.Context) error {
err = clis.UserData.ResendVerifyEmail(c, username)
if err != nil {
log.BootErrorf("[user_data.resendUserVerifyEmail] error occurs when resending user verify email")
log.BootErrorf(c, "[user_data.resendUserVerifyEmail] error occurs when resending user verify email")
return err
}
log.BootInfof("[user_data.resendUserVerifyEmail] verify email for user \"%s\" has been resent", username)
log.BootInfof(c, "[user_data.resendUserVerifyEmail] verify email for user \"%s\" has been resent", username)
return nil
}
func setUserEmailVerified(c *cli.Context) error {
func setUserEmailVerified(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -428,16 +429,16 @@ func setUserEmailVerified(c *cli.Context) error {
err = clis.UserData.SetUserEmailVerified(c, username)
if err != nil {
log.BootErrorf("[user_data.setUserEmailVerified] error occurs when setting user email address verified")
log.BootErrorf(c, "[user_data.setUserEmailVerified] error occurs when setting user email address verified")
return err
}
log.BootInfof("[user_data.setUserEmailVerified] user \"%s\" email address has been set verified", username)
log.BootInfof(c, "[user_data.setUserEmailVerified] user \"%s\" email address has been set verified", username)
return nil
}
func setUserEmailUnverified(c *cli.Context) error {
func setUserEmailUnverified(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -448,16 +449,16 @@ func setUserEmailUnverified(c *cli.Context) error {
err = clis.UserData.SetUserEmailUnverified(c, username)
if err != nil {
log.BootErrorf("[user_data.setUserEmailUnverified] error occurs when setting user email address unverified")
log.BootErrorf(c, "[user_data.setUserEmailUnverified] error occurs when setting user email address unverified")
return err
}
log.BootInfof("[user_data.setUserEmailUnverified] user \"%s\" email address has been set unverified", username)
log.BootInfof(c, "[user_data.setUserEmailUnverified] user \"%s\" email address has been set unverified", username)
return nil
}
func deleteUser(c *cli.Context) error {
func deleteUser(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -468,16 +469,16 @@ func deleteUser(c *cli.Context) error {
err = clis.UserData.DeleteUser(c, username)
if err != nil {
log.BootErrorf("[user_data.deleteUser] error occurs when deleting user")
log.BootErrorf(c, "[user_data.deleteUser] error occurs when deleting user")
return err
}
log.BootInfof("[user_data.deleteUser] user \"%s\" has been deleted", username)
log.BootInfof(c, "[user_data.deleteUser] user \"%s\" has been deleted", username)
return nil
}
func disableUser2FA(c *cli.Context) error {
func disableUser2FA(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -488,16 +489,16 @@ func disableUser2FA(c *cli.Context) error {
err = clis.UserData.DisableUserTwoFactorAuthorization(c, username)
if err != nil {
log.BootErrorf("[user_data.disableUser2FA] error occurs when disabling user two-factor authorization")
log.BootErrorf(c, "[user_data.disableUser2FA] error occurs when disabling user two-factor authorization")
return err
}
log.BootInfof("[user_data.disableUser2FA] two-factor authorization of user \"%s\" has been disabled", username)
log.BootInfof(c, "[user_data.disableUser2FA] two-factor authorization of user \"%s\" has been disabled", username)
return nil
}
func listUserTokens(c *cli.Context) error {
func listUserTokens(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -508,7 +509,7 @@ func listUserTokens(c *cli.Context) error {
tokens, err := clis.UserData.ListUserTokens(c, username)
if err != nil {
log.BootErrorf("[user_data.listUserTokens] error occurs when getting user tokens")
log.BootErrorf(c, "[user_data.listUserTokens] error occurs when getting user tokens")
return err
}
@@ -523,7 +524,7 @@ func listUserTokens(c *cli.Context) error {
return nil
}
func clearUserTokens(c *cli.Context) error {
func clearUserTokens(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -534,16 +535,16 @@ func clearUserTokens(c *cli.Context) error {
err = clis.UserData.ClearUserTokens(c, username)
if err != nil {
log.BootErrorf("[user_data.clearUserTokens] error occurs when clearing user tokens")
log.BootErrorf(c, "[user_data.clearUserTokens] error occurs when clearing user tokens")
return err
}
log.BootInfof("[user_data.clearUserTokens] all tokens of user \"%s\" has been cleared", username)
log.BootInfof(c, "[user_data.clearUserTokens] all tokens of user \"%s\" has been cleared", username)
return nil
}
func checkUserTransactionAndAccount(c *cli.Context) error {
func checkUserTransactionAndAccount(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -552,21 +553,21 @@ func checkUserTransactionAndAccount(c *cli.Context) error {
username := c.String("username")
log.BootInfof("[user_data.checkUserTransactionAndAccount] starting checking user \"%s\" data", username)
log.BootInfof(c, "[user_data.checkUserTransactionAndAccount] starting checking user \"%s\" data", username)
_, err = clis.UserData.CheckTransactionAndAccount(c, username)
if err != nil {
log.BootErrorf("[user_data.checkUserTransactionAndAccount] error occurs when checking user data")
log.BootErrorf(c, "[user_data.checkUserTransactionAndAccount] error occurs when checking user data")
return err
}
log.BootInfof("[user_data.checkUserTransactionAndAccount] user transactions and accounts data has been checked successfully, there is no problem with user data")
log.BootInfof(c, "[user_data.checkUserTransactionAndAccount] user transactions and accounts data has been checked successfully, there is no problem with user data")
return nil
}
func fixTransactionTagIndexNotHaveTransactionTime(c *cli.Context) error {
func fixTransactionTagIndexNotHaveTransactionTime(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -575,21 +576,21 @@ func fixTransactionTagIndexNotHaveTransactionTime(c *cli.Context) error {
username := c.String("username")
log.BootInfof("[user_data.fixTransactionTagIndexNotHaveTransactionTime] starting fixing user \"%s\" transaction tag index data", username)
log.BootInfof(c, "[user_data.fixTransactionTagIndexNotHaveTransactionTime] starting fixing user \"%s\" transaction tag index data", username)
_, err = clis.UserData.FixTransactionTagIndexWithTransactionTime(c, username)
if err != nil {
log.BootErrorf("[user_data.fixTransactionTagIndexNotHaveTransactionTime] error occurs when fixing user data")
log.BootErrorf(c, "[user_data.fixTransactionTagIndexNotHaveTransactionTime] error occurs when fixing user data")
return err
}
log.BootInfof("[user_data.fixTransactionTagIndexNotHaveTransactionTime] user transaction tag index data has been fixed successfully")
log.BootInfof(c, "[user_data.fixTransactionTagIndexNotHaveTransactionTime] user transaction tag index data has been fixed successfully")
return nil
}
func exportUserTransaction(c *cli.Context) error {
func exportUserTransaction(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
@@ -601,39 +602,39 @@ func exportUserTransaction(c *cli.Context) error {
fileType := c.String("type")
if fileType != "" && fileType != "csv" && fileType != "tsv" {
log.BootErrorf("[user_data.exportUserTransaction] export file type is not supported")
log.BootErrorf(c, "[user_data.exportUserTransaction] export file type is not supported")
return errs.ErrNotSupported
}
if filePath == "" {
log.BootErrorf("[user_data.exportUserTransaction] export file path is unspecified")
log.BootErrorf(c, "[user_data.exportUserTransaction] export file path is unspecified")
return os.ErrNotExist
}
fileExists, err := utils.IsExists(filePath)
if fileExists {
log.BootErrorf("[user_data.exportUserTransaction] specified file path already exists")
log.BootErrorf(c, "[user_data.exportUserTransaction] specified file path already exists")
return os.ErrExist
}
log.BootInfof("[user_data.exportUserTransaction] starting exporting user \"%s\" data", username)
log.BootInfof(c, "[user_data.exportUserTransaction] starting exporting user \"%s\" data", username)
content, err := clis.UserData.ExportTransaction(c, username, fileType)
if err != nil {
log.BootErrorf("[user_data.exportUserTransaction] error occurs when exporting user data")
log.BootErrorf(c, "[user_data.exportUserTransaction] error occurs when exporting user data")
return err
}
err = utils.WriteFile(filePath, content)
if err != nil {
log.BootErrorf("[user_data.exportUserTransaction] failed to write to %s", filePath)
log.BootErrorf(c, "[user_data.exportUserTransaction] failed to write to %s", filePath)
return err
}
log.BootInfof("[user_data.exportUserTransaction] user transactions have been exported to %s", filePath)
log.BootInfof(c, "[user_data.exportUserTransaction] user transactions have been exported to %s", filePath)
return nil
}
+7 -6
View File
@@ -7,6 +7,7 @@ import (
"github.com/urfave/cli/v2"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/mail"
"github.com/mayswind/ezbookkeeping/pkg/requestid"
@@ -21,7 +22,7 @@ var Utilities = &cli.Command{
{
Name: "parse-default-request-id",
Usage: "Parse a request id which is generated by default request generator and show the details",
Action: parseRequestId,
Action: bindAction(parseRequestId),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "id",
@@ -33,7 +34,7 @@ var Utilities = &cli.Command{
{
Name: "send-test-mail",
Usage: "Send an email to specified e-mail address",
Action: sendTestMail,
Action: bindAction(sendTestMail),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "to",
@@ -45,15 +46,15 @@ var Utilities = &cli.Command{
},
}
func parseRequestId(c *cli.Context) error {
func parseRequestId(c *core.CliContext) error {
config, err := initializeSystem(c)
if err != nil {
return err
}
err = requestid.InitializeRequestIdGenerator(config)
defaultGenerator, err := requestid.NewDefaultRequestIdGenerator(config)
err = requestid.InitializeRequestIdGenerator(c, config)
defaultGenerator, err := requestid.NewDefaultRequestIdGenerator(c, config)
if err != nil {
return err
@@ -73,7 +74,7 @@ func parseRequestId(c *cli.Context) error {
return nil
}
func sendTestMail(c *cli.Context) error {
func sendTestMail(c *core.CliContext) error {
config, err := initializeSystem(c)
if err != nil {
+22 -22
View File
@@ -33,40 +33,40 @@ var WebServer = &cli.Command{
{
Name: "run",
Usage: "Run ezBookkeeping web server",
Action: startWebServer,
Action: bindAction(startWebServer),
},
},
}
func startWebServer(c *cli.Context) error {
func startWebServer(c *core.CliContext) error {
config, err := initializeSystem(c)
if err != nil {
return err
}
log.BootInfof("[webserver.startWebServer] static root path is %s", config.StaticRootPath)
log.BootInfof(c, "[webserver.startWebServer] static root path is %s", config.StaticRootPath)
if config.AutoUpdateDatabase {
err = updateAllDatabaseTablesStructure()
err = updateAllDatabaseTablesStructure(c)
if err != nil {
log.BootErrorf("[webserver.startWebServer] update database table structure failed, because %s", err.Error())
log.BootErrorf(c, "[webserver.startWebServer] update database table structure failed, because %s", err.Error())
return err
}
}
err = requestid.InitializeRequestIdGenerator(config)
err = requestid.InitializeRequestIdGenerator(c, config)
if err != nil {
log.BootErrorf("[webserver.startWebServer] initializes requestid generator failed, because %s", err.Error())
log.BootErrorf(c, "[webserver.startWebServer] initializes requestid generator failed, because %s", err.Error())
return err
}
err = cron.InitializeCronJobSchedulerContainer(config, true)
err = cron.InitializeCronJobSchedulerContainer(c, config, true)
if err != nil {
log.BootErrorf("[webserver.startWebServer] initializes cron job scheduler failed, because %s", err.Error())
log.BootErrorf(c, "[webserver.startWebServer] initializes cron job scheduler failed, because %s", err.Error())
return err
}
@@ -76,7 +76,7 @@ func startWebServer(c *cli.Context) error {
uuidServerInfo = fmt.Sprintf(", current uuid server id is %d", config.UuidServerId)
}
log.BootInfof("[webserver.startWebServer] %s%s", serverInfo, uuidServerInfo)
log.BootInfof(c, "[webserver.startWebServer] %s%s", serverInfo, uuidServerInfo)
if config.Mode == settings.MODE_PRODUCTION {
gin.SetMode(gin.ReleaseMode)
@@ -345,20 +345,20 @@ func startWebServer(c *cli.Context) error {
listenAddr := fmt.Sprintf("%s:%d", config.HttpAddr, config.HttpPort)
if config.Protocol == settings.SCHEME_SOCKET {
log.BootInfof("[webserver.startWebServer] will run at socks:%s", config.UnixSocketPath)
log.BootInfof(c, "[webserver.startWebServer] will run at socks:%s", config.UnixSocketPath)
err = router.RunUnix(config.UnixSocketPath)
} else if config.Protocol == settings.SCHEME_HTTP {
log.BootInfof("[webserver.startWebServer] will run at http://%s", listenAddr)
log.BootInfof(c, "[webserver.startWebServer] will run at http://%s", listenAddr)
err = router.Run(listenAddr)
} else if config.Protocol == settings.SCHEME_HTTPS {
log.BootInfof("[webserver.startWebServer] will run at https://%s", listenAddr)
log.BootInfof(c, "[webserver.startWebServer] will run at https://%s", listenAddr)
err = router.RunTLS(listenAddr, config.CertFile, config.CertKeyFile)
} else {
err = errs.ErrInvalidProtocol
}
if err != nil {
log.BootErrorf("[webserver.startWebServer] cannot start, because %s", err)
log.BootErrorf(c, "[webserver.startWebServer] cannot start, because %s", err)
return err
}
@@ -367,13 +367,13 @@ func startWebServer(c *cli.Context) error {
func bindMiddleware(fn core.MiddlewareHandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
fn(core.WrapContext(c))
fn(core.WrapWebContext(c))
}
}
func bindApi(fn core.ApiHandlerFunc) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
c := core.WrapContext(ginCtx)
c := core.WrapWebContext(ginCtx)
result, err := fn(c)
if err != nil {
@@ -386,7 +386,7 @@ func bindApi(fn core.ApiHandlerFunc) gin.HandlerFunc {
func bindApiWithTokenUpdate(fn core.ApiHandlerFunc, config *settings.Config) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
c := core.WrapContext(ginCtx)
c := core.WrapWebContext(ginCtx)
result, err := fn(c)
if err == nil && config.MapProvider == settings.AmapProvider && config.AmapSecurityVerificationMethod == settings.AmapSecurityVerificationInternalProxyMethod {
@@ -403,7 +403,7 @@ func bindApiWithTokenUpdate(fn core.ApiHandlerFunc, config *settings.Config) gin
func bindCsv(fn core.DataHandlerFunc) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
c := core.WrapContext(ginCtx)
c := core.WrapWebContext(ginCtx)
result, fileName, err := fn(c)
if err != nil {
@@ -416,7 +416,7 @@ func bindCsv(fn core.DataHandlerFunc) gin.HandlerFunc {
func bindTsv(fn core.DataHandlerFunc) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
c := core.WrapContext(ginCtx)
c := core.WrapWebContext(ginCtx)
result, fileName, err := fn(c)
if err != nil {
@@ -429,7 +429,7 @@ func bindTsv(fn core.DataHandlerFunc) gin.HandlerFunc {
func bindImage(fn core.ImageHandlerFunc) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
c := core.WrapContext(ginCtx)
c := core.WrapWebContext(ginCtx)
result, contentType, err := fn(c)
if err != nil {
@@ -442,7 +442,7 @@ func bindImage(fn core.ImageHandlerFunc) gin.HandlerFunc {
func bindCachedImage(fn core.ImageHandlerFunc, store persistence.CacheStore) gin.HandlerFunc {
return cache.CachePage(store, time.Minute, func(ginCtx *gin.Context) {
c := core.WrapContext(ginCtx)
c := core.WrapWebContext(ginCtx)
result, contentType, err := fn(c)
if err != nil {
@@ -455,7 +455,7 @@ func bindCachedImage(fn core.ImageHandlerFunc, store persistence.CacheStore) gin
func bindProxy(fn core.ProxyHandlerFunc) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
c := core.WrapContext(ginCtx)
c := core.WrapWebContext(ginCtx)
proxy, err := fn(c)
if err != nil {
+42 -42
View File
@@ -35,12 +35,12 @@ var (
)
// AccountListHandler returns accounts list of current user
func (a *AccountsApi) AccountListHandler(c *core.Context) (any, *errs.Error) {
func (a *AccountsApi) AccountListHandler(c *core.WebContext) (any, *errs.Error) {
var accountListReq models.AccountListRequest
err := c.ShouldBindQuery(&accountListReq)
if err != nil {
log.WarnfWithRequestId(c, "[accounts.AccountListHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[accounts.AccountListHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -48,7 +48,7 @@ func (a *AccountsApi) AccountListHandler(c *core.Context) (any, *errs.Error) {
accounts, err := a.accounts.GetAllAccountsByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[accounts.AccountListHandler] failed to get all accounts for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[accounts.AccountListHandler] failed to get all accounts for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -95,12 +95,12 @@ func (a *AccountsApi) AccountListHandler(c *core.Context) (any, *errs.Error) {
}
// AccountGetHandler returns one specific account of current user
func (a *AccountsApi) AccountGetHandler(c *core.Context) (any, *errs.Error) {
func (a *AccountsApi) AccountGetHandler(c *core.WebContext) (any, *errs.Error) {
var accountGetReq models.AccountGetRequest
err := c.ShouldBindQuery(&accountGetReq)
if err != nil {
log.WarnfWithRequestId(c, "[accounts.AccountGetHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[accounts.AccountGetHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -108,7 +108,7 @@ func (a *AccountsApi) AccountGetHandler(c *core.Context) (any, *errs.Error) {
accountAndSubAccounts, err := a.accounts.GetAccountAndSubAccountsByAccountId(c, uid, accountGetReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[accounts.AccountGetHandler] failed to get account \"id:%d\" for user \"uid:%d\", because %s", accountGetReq.Id, uid, err.Error())
log.Errorf(c, "[accounts.AccountGetHandler] failed to get account \"id:%d\" for user \"uid:%d\", because %s", accountGetReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -138,50 +138,50 @@ func (a *AccountsApi) AccountGetHandler(c *core.Context) (any, *errs.Error) {
}
// AccountCreateHandler saves a new account by request parameters for current user
func (a *AccountsApi) AccountCreateHandler(c *core.Context) (any, *errs.Error) {
func (a *AccountsApi) AccountCreateHandler(c *core.WebContext) (any, *errs.Error) {
var accountCreateReq models.AccountCreateRequest
err := c.ShouldBindJSON(&accountCreateReq)
if err != nil {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[accounts.AccountCreateHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
utcOffset, err := c.GetClientTimezoneOffset()
if err != nil {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] cannot get client timezone offset, because %s", err.Error())
log.Warnf(c, "[accounts.AccountCreateHandler] cannot get client timezone offset, because %s", err.Error())
return nil, errs.ErrClientTimezoneOffsetInvalid
}
if accountCreateReq.Category < models.ACCOUNT_CATEGORY_CASH || accountCreateReq.Category > models.ACCOUNT_CATEGORY_INVESTMENT {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] account category invalid, category is %d", accountCreateReq.Category)
log.Warnf(c, "[accounts.AccountCreateHandler] account category invalid, category is %d", accountCreateReq.Category)
return nil, errs.ErrAccountCategoryInvalid
}
if accountCreateReq.Type == models.ACCOUNT_TYPE_SINGLE_ACCOUNT {
if len(accountCreateReq.SubAccounts) > 0 {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] account cannot have any sub-accounts")
log.Warnf(c, "[accounts.AccountCreateHandler] account cannot have any sub-accounts")
return nil, errs.ErrAccountCannotHaveSubAccounts
}
if accountCreateReq.Currency == validators.ParentAccountCurrencyPlaceholder {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] account cannot set currency placeholder")
log.Warnf(c, "[accounts.AccountCreateHandler] account cannot set currency placeholder")
return nil, errs.ErrAccountCurrencyInvalid
}
} else if accountCreateReq.Type == models.ACCOUNT_TYPE_MULTI_SUB_ACCOUNTS {
if len(accountCreateReq.SubAccounts) < 1 {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] account does not have any sub-accounts")
log.Warnf(c, "[accounts.AccountCreateHandler] account does not have any sub-accounts")
return nil, errs.ErrAccountHaveNoSubAccount
}
if accountCreateReq.Currency != validators.ParentAccountCurrencyPlaceholder {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] parent account cannot set currency")
log.Warnf(c, "[accounts.AccountCreateHandler] parent account cannot set currency")
return nil, errs.ErrParentAccountCannotSetCurrency
}
if accountCreateReq.Balance != 0 {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] parent account cannot set balance")
log.Warnf(c, "[accounts.AccountCreateHandler] parent account cannot set balance")
return nil, errs.ErrParentAccountCannotSetBalance
}
@@ -189,22 +189,22 @@ func (a *AccountsApi) AccountCreateHandler(c *core.Context) (any, *errs.Error) {
subAccount := accountCreateReq.SubAccounts[i]
if subAccount.Category != accountCreateReq.Category {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] category of sub-account not equals to parent")
log.Warnf(c, "[accounts.AccountCreateHandler] category of sub-account not equals to parent")
return nil, errs.ErrSubAccountCategoryNotEqualsToParent
}
if subAccount.Type != models.ACCOUNT_TYPE_SINGLE_ACCOUNT {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] sub-account type invalid")
log.Warnf(c, "[accounts.AccountCreateHandler] sub-account type invalid")
return nil, errs.ErrSubAccountTypeInvalid
}
if subAccount.Currency == validators.ParentAccountCurrencyPlaceholder {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] sub-account cannot set currency placeholder")
log.Warnf(c, "[accounts.AccountCreateHandler] sub-account cannot set currency placeholder")
return nil, errs.ErrAccountCurrencyInvalid
}
}
} else {
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] account type invalid, type is %d", accountCreateReq.Type)
log.Warnf(c, "[accounts.AccountCreateHandler] account type invalid, type is %d", accountCreateReq.Type)
return nil, errs.ErrAccountTypeInvalid
}
@@ -212,7 +212,7 @@ func (a *AccountsApi) AccountCreateHandler(c *core.Context) (any, *errs.Error) {
maxOrderId, err := a.accounts.GetMaxDisplayOrder(c, uid, accountCreateReq.Category)
if err != nil {
log.ErrorfWithRequestId(c, "[accounts.AccountCreateHandler] failed to get max display order for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[accounts.AccountCreateHandler] failed to get max display order for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -223,14 +223,14 @@ func (a *AccountsApi) AccountCreateHandler(c *core.Context) (any, *errs.Error) {
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)
log.Infof(c, "[accounts.AccountCreateHandler] another account \"id:%s\" has been created for user \"uid:%d\"", remark, uid)
accountId, err := utils.StringToInt64(remark)
if err == nil {
accountAndSubAccounts, err := a.accounts.GetAccountAndSubAccountsByAccountId(c, uid, accountId)
if err != nil {
log.ErrorfWithRequestId(c, "[accounts.AccountCreateHandler] failed to get existed account \"id:%d\" for user \"uid:%d\", because %s", accountId, uid, err.Error())
log.Errorf(c, "[accounts.AccountCreateHandler] failed to get existed account \"id:%d\" for user \"uid:%d\", because %s", accountId, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -258,11 +258,11 @@ func (a *AccountsApi) AccountCreateHandler(c *core.Context) (any, *errs.Error) {
err = a.accounts.CreateAccounts(c, mainAccount, childrenAccounts, utcOffset)
if err != nil {
log.ErrorfWithRequestId(c, "[accounts.AccountCreateHandler] failed to create account \"id:%d\" for user \"uid:%d\", because %s", mainAccount.AccountId, uid, err.Error())
log.Errorf(c, "[accounts.AccountCreateHandler] failed to create account \"id:%d\" for user \"uid:%d\", because %s", mainAccount.AccountId, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[accounts.AccountCreateHandler] user \"uid:%d\" has created a new account \"id:%d\" successfully", uid, mainAccount.AccountId)
log.Infof(c, "[accounts.AccountCreateHandler] user \"uid:%d\" has created a new account \"id:%d\" successfully", uid, mainAccount.AccountId)
a.SetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_ACCOUNT, uid, accountCreateReq.ClientSessionId, utils.Int64ToString(mainAccount.AccountId))
accountInfoResp := mainAccount.ToAccountInfoResponse()
@@ -279,17 +279,17 @@ func (a *AccountsApi) AccountCreateHandler(c *core.Context) (any, *errs.Error) {
}
// AccountModifyHandler saves an existed account by request parameters for current user
func (a *AccountsApi) AccountModifyHandler(c *core.Context) (any, *errs.Error) {
func (a *AccountsApi) AccountModifyHandler(c *core.WebContext) (any, *errs.Error) {
var accountModifyReq models.AccountModifyRequest
err := c.ShouldBindJSON(&accountModifyReq)
if err != nil {
log.WarnfWithRequestId(c, "[accounts.AccountModifyHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[accounts.AccountModifyHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
if accountModifyReq.Category < models.ACCOUNT_CATEGORY_CASH || accountModifyReq.Category > models.ACCOUNT_CATEGORY_INVESTMENT {
log.WarnfWithRequestId(c, "[accounts.AccountModifyHandler] account category invalid, category is %d", accountModifyReq.Category)
log.Warnf(c, "[accounts.AccountModifyHandler] account category invalid, category is %d", accountModifyReq.Category)
return nil, errs.ErrAccountCategoryInvalid
}
@@ -297,7 +297,7 @@ func (a *AccountsApi) AccountModifyHandler(c *core.Context) (any, *errs.Error) {
accountAndSubAccounts, err := a.accounts.GetAccountAndSubAccountsByAccountId(c, uid, accountModifyReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[accounts.AccountModifyHandler] failed to get account \"id:%d\" for user \"uid:%d\", because %s", accountModifyReq.Id, uid, err.Error())
log.Errorf(c, "[accounts.AccountModifyHandler] failed to get account \"id:%d\" for user \"uid:%d\", because %s", accountModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -343,11 +343,11 @@ func (a *AccountsApi) AccountModifyHandler(c *core.Context) (any, *errs.Error) {
err = a.accounts.ModifyAccounts(c, uid, toUpdateAccounts)
if err != nil {
log.ErrorfWithRequestId(c, "[accounts.AccountModifyHandler] failed to update account \"id:%d\" for user \"uid:%d\", because %s", accountModifyReq.Id, uid, err.Error())
log.Errorf(c, "[accounts.AccountModifyHandler] failed to update account \"id:%d\" for user \"uid:%d\", because %s", accountModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[accounts.AccountModifyHandler] user \"uid:%d\" has updated account \"id:%d\" successfully", uid, accountModifyReq.Id)
log.Infof(c, "[accounts.AccountModifyHandler] user \"uid:%d\" has updated account \"id:%d\" successfully", uid, accountModifyReq.Id)
accountRespMap := make(map[int64]*models.AccountInfoResponse)
@@ -390,12 +390,12 @@ func (a *AccountsApi) AccountModifyHandler(c *core.Context) (any, *errs.Error) {
}
// AccountHideHandler hides an existed account by request parameters for current user
func (a *AccountsApi) AccountHideHandler(c *core.Context) (any, *errs.Error) {
func (a *AccountsApi) AccountHideHandler(c *core.WebContext) (any, *errs.Error) {
var accountHideReq models.AccountHideRequest
err := c.ShouldBindJSON(&accountHideReq)
if err != nil {
log.WarnfWithRequestId(c, "[accounts.AccountHideHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[accounts.AccountHideHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -403,21 +403,21 @@ func (a *AccountsApi) AccountHideHandler(c *core.Context) (any, *errs.Error) {
err = a.accounts.HideAccount(c, uid, []int64{accountHideReq.Id}, accountHideReq.Hidden)
if err != nil {
log.ErrorfWithRequestId(c, "[accounts.AccountHideHandler] failed to hide account \"id:%d\" for user \"uid:%d\", because %s", accountHideReq.Id, uid, err.Error())
log.Errorf(c, "[accounts.AccountHideHandler] failed to hide account \"id:%d\" for user \"uid:%d\", because %s", accountHideReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[accounts.AccountHideHandler] user \"uid:%d\" has hidden account \"id:%d\"", uid, accountHideReq.Id)
log.Infof(c, "[accounts.AccountHideHandler] user \"uid:%d\" has hidden account \"id:%d\"", uid, accountHideReq.Id)
return true, nil
}
// AccountMoveHandler moves display order of existed accounts by request parameters for current user
func (a *AccountsApi) AccountMoveHandler(c *core.Context) (any, *errs.Error) {
func (a *AccountsApi) AccountMoveHandler(c *core.WebContext) (any, *errs.Error) {
var accountMoveReq models.AccountMoveRequest
err := c.ShouldBindJSON(&accountMoveReq)
if err != nil {
log.WarnfWithRequestId(c, "[accounts.AccountMoveHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[accounts.AccountMoveHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -438,21 +438,21 @@ func (a *AccountsApi) AccountMoveHandler(c *core.Context) (any, *errs.Error) {
err = a.accounts.ModifyAccountDisplayOrders(c, uid, accounts)
if err != nil {
log.ErrorfWithRequestId(c, "[accounts.AccountMoveHandler] failed to move accounts for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[accounts.AccountMoveHandler] failed to move accounts for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[accounts.AccountMoveHandler] user \"uid:%d\" has moved accounts", uid)
log.Infof(c, "[accounts.AccountMoveHandler] user \"uid:%d\" has moved accounts", uid)
return true, nil
}
// AccountDeleteHandler deletes an existed account by request parameters for current user
func (a *AccountsApi) AccountDeleteHandler(c *core.Context) (any, *errs.Error) {
func (a *AccountsApi) AccountDeleteHandler(c *core.WebContext) (any, *errs.Error) {
var accountDeleteReq models.AccountDeleteRequest
err := c.ShouldBindJSON(&accountDeleteReq)
if err != nil {
log.WarnfWithRequestId(c, "[accounts.AccountDeleteHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[accounts.AccountDeleteHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -460,11 +460,11 @@ func (a *AccountsApi) AccountDeleteHandler(c *core.Context) (any, *errs.Error) {
err = a.accounts.DeleteAccount(c, uid, accountDeleteReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[accounts.AccountDeleteHandler] failed to delete account \"id:%d\" for user \"uid:%d\", because %s", accountDeleteReq.Id, uid, err.Error())
log.Errorf(c, "[accounts.AccountDeleteHandler] failed to delete account \"id:%d\" for user \"uid:%d\", because %s", accountDeleteReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[accounts.AccountDeleteHandler] user \"uid:%d\" has deleted account \"id:%d\"", uid, accountDeleteReq.Id)
log.Infof(c, "[accounts.AccountDeleteHandler] user \"uid:%d\" has deleted account \"id:%d\"", uid, accountDeleteReq.Id)
return true, nil
}
+1 -1
View File
@@ -31,7 +31,7 @@ var (
)
// AmapApiProxyHandler returns amap api response
func (p *AmapApiProxy) AmapApiProxyHandler(c *core.Context) (*httputil.ReverseProxy, *errs.Error) {
func (p *AmapApiProxy) AmapApiProxyHandler(c *core.WebContext) (*httputil.ReverseProxy, *errs.Error) {
var targetUrl string
if strings.HasPrefix(c.Request.RequestURI, "/_AMapService/v4/map/styles") {
+31 -31
View File
@@ -32,24 +32,24 @@ var (
)
// AuthorizeHandler verifies and authorizes current login request
func (a *AuthorizationsApi) AuthorizeHandler(c *core.Context) (any, *errs.Error) {
func (a *AuthorizationsApi) AuthorizeHandler(c *core.WebContext) (any, *errs.Error) {
var credential models.UserLoginRequest
err := c.ShouldBindJSON(&credential)
if err != nil {
log.WarnfWithRequestId(c, "[authorizations.AuthorizeHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[authorizations.AuthorizeHandler] parse request failed, because %s", err.Error())
return nil, errs.ErrLoginNameOrPasswordInvalid
}
user, err := a.users.GetUserByUsernameOrEmailAndPassword(c, credential.LoginName, credential.Password)
if err != nil {
log.WarnfWithRequestId(c, "[authorizations.AuthorizeHandler] login failed for user \"%s\", because %s", credential.LoginName, err.Error())
log.Warnf(c, "[authorizations.AuthorizeHandler] login failed for user \"%s\", because %s", credential.LoginName, err.Error())
return nil, errs.ErrLoginNameOrPasswordWrong
}
if user.Disabled {
log.WarnfWithRequestId(c, "[authorizations.AuthorizeHandler] login failed for user \"%s\", because user is disabled", credential.LoginName)
log.Warnf(c, "[authorizations.AuthorizeHandler] login failed for user \"%s\", because user is disabled", credential.LoginName)
return nil, errs.ErrUserIsDisabled
}
@@ -57,11 +57,11 @@ func (a *AuthorizationsApi) AuthorizeHandler(c *core.Context) (any, *errs.Error)
hasValidEmailVerifyToken, err := a.tokens.ExistsValidTokenByType(c, user.Uid, core.USER_TOKEN_TYPE_EMAIL_VERIFY)
if err != nil {
log.WarnfWithRequestId(c, "[authorizations.AuthorizeHandler] failed check whether user \"uid:%d\" has valid verify email token, because %s", user.Uid, err.Error())
log.Warnf(c, "[authorizations.AuthorizeHandler] failed check whether user \"uid:%d\" has valid verify email token, because %s", user.Uid, err.Error())
hasValidEmailVerifyToken = false
}
log.WarnfWithRequestId(c, "[authorizations.AuthorizeHandler] login failed for user \"%s\", because user has not verified email", credential.LoginName)
log.Warnf(c, "[authorizations.AuthorizeHandler] login failed for user \"%s\", because user has not verified email", credential.LoginName)
return nil, errs.NewErrorWithContext(errs.ErrEmailIsNotVerified, map[string]any{
"email": user.Email,
@@ -72,7 +72,7 @@ func (a *AuthorizationsApi) AuthorizeHandler(c *core.Context) (any, *errs.Error)
err = a.users.UpdateUserLastLoginTime(c, user.Uid)
if err != nil {
log.WarnfWithRequestId(c, "[authorizations.AuthorizeHandler] failed to update last login time for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Warnf(c, "[authorizations.AuthorizeHandler] failed to update last login time for user \"uid:%d\", because %s", user.Uid, err.Error())
}
twoFactorEnable := a.tokens.CurrentConfig().EnableTwoFactor
@@ -81,7 +81,7 @@ func (a *AuthorizationsApi) AuthorizeHandler(c *core.Context) (any, *errs.Error)
twoFactorEnable, err = a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, user.Uid)
if err != nil {
log.ErrorfWithRequestId(c, "[authorizations.AuthorizeHandler] failed to check two-factor setting for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[authorizations.AuthorizeHandler] failed to check two-factor setting for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.Or(err, errs.ErrSystemError)
}
}
@@ -96,7 +96,7 @@ func (a *AuthorizationsApi) AuthorizeHandler(c *core.Context) (any, *errs.Error)
}
if err != nil {
log.ErrorfWithRequestId(c, "[authorizations.AuthorizeHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[authorizations.AuthorizeHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.ErrTokenGenerating
}
@@ -106,19 +106,19 @@ func (a *AuthorizationsApi) AuthorizeHandler(c *core.Context) (any, *errs.Error)
c.SetTokenClaims(claims)
log.InfofWithRequestId(c, "[authorizations.AuthorizeHandler] user \"uid:%d\" has logined, token type is %d, token will be expired at %d", user.Uid, claims.Type, claims.ExpiresAt)
log.Infof(c, "[authorizations.AuthorizeHandler] user \"uid:%d\" has logined, token type is %d, token will be expired at %d", user.Uid, claims.Type, claims.ExpiresAt)
authResp := a.getAuthResponse(c, token, twoFactorEnable, user)
return authResp, nil
}
// TwoFactorAuthorizeHandler verifies and authorizes current 2fa login by passcode
func (a *AuthorizationsApi) TwoFactorAuthorizeHandler(c *core.Context) (any, *errs.Error) {
func (a *AuthorizationsApi) TwoFactorAuthorizeHandler(c *core.WebContext) (any, *errs.Error) {
var credential models.TwoFactorLoginRequest
err := c.ShouldBindJSON(&credential)
if err != nil {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[authorizations.TwoFactorAuthorizeHandler] parse request failed, because %s", err.Error())
return nil, errs.ErrPasscodeInvalid
}
@@ -126,29 +126,29 @@ func (a *AuthorizationsApi) TwoFactorAuthorizeHandler(c *core.Context) (any, *er
twoFactorSetting, err := a.twoFactorAuthorizations.GetUserTwoFactorSettingByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[authorizations.TwoFactorAuthorizeHandler] failed to get two-factor setting for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[authorizations.TwoFactorAuthorizeHandler] failed to get two-factor setting for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrSystemError)
}
if !totp.Validate(credential.Passcode, twoFactorSetting.Secret) {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeHandler] passcode is invalid for user \"uid:%d\"", uid)
log.Warnf(c, "[authorizations.TwoFactorAuthorizeHandler] passcode is invalid for user \"uid:%d\"", uid)
return nil, errs.ErrPasscodeInvalid
}
user, err := a.users.GetUserById(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[authorizations.TwoFactorAuthorizeHandler] failed to get user \"uid:%d\" info, because %s", user.Uid, err.Error())
log.Errorf(c, "[authorizations.TwoFactorAuthorizeHandler] failed to get user \"uid:%d\" info, because %s", user.Uid, err.Error())
return nil, errs.ErrUserNotFound
}
if user.Disabled {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeHandler] user \"uid:%d\" is disabled", user.Uid)
log.Warnf(c, "[authorizations.TwoFactorAuthorizeHandler] user \"uid:%d\" is disabled", user.Uid)
return nil, errs.ErrUserIsDisabled
}
if a.CurrentConfig().EnableUserForceVerifyEmail && !user.EmailVerified {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeHandler] user \"uid:%d\" has not verified email", user.Uid)
log.Warnf(c, "[authorizations.TwoFactorAuthorizeHandler] user \"uid:%d\" has not verified email", user.Uid)
return nil, errs.ErrEmailIsNotVerified
}
@@ -156,32 +156,32 @@ func (a *AuthorizationsApi) TwoFactorAuthorizeHandler(c *core.Context) (any, *er
err = a.tokens.DeleteTokenByClaims(c, oldTokenClaims)
if err != nil {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeHandler] failed to revoke temporary token \"utid:%s\" for user \"uid:%d\", because %s", oldTokenClaims.UserTokenId, user.Uid, err.Error())
log.Warnf(c, "[authorizations.TwoFactorAuthorizeHandler] failed to revoke temporary token \"utid:%s\" for user \"uid:%d\", because %s", oldTokenClaims.UserTokenId, user.Uid, err.Error())
}
token, claims, err := a.tokens.CreateToken(c, user)
if err != nil {
log.ErrorfWithRequestId(c, "[authorizations.TwoFactorAuthorizeHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[authorizations.TwoFactorAuthorizeHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.ErrTokenGenerating
}
c.SetTextualToken(token)
c.SetTokenClaims(claims)
log.InfofWithRequestId(c, "[authorizations.TwoFactorAuthorizeHandler] user \"uid:%d\" has authorized two-factor via passcode, token will be expired at %d", user.Uid, claims.ExpiresAt)
log.Infof(c, "[authorizations.TwoFactorAuthorizeHandler] user \"uid:%d\" has authorized two-factor via passcode, token will be expired at %d", user.Uid, claims.ExpiresAt)
authResp := a.getAuthResponse(c, token, false, user)
return authResp, nil
}
// TwoFactorAuthorizeByRecoveryCodeHandler verifies and authorizes current 2fa login by recovery code
func (a *AuthorizationsApi) TwoFactorAuthorizeByRecoveryCodeHandler(c *core.Context) (any, *errs.Error) {
func (a *AuthorizationsApi) TwoFactorAuthorizeByRecoveryCodeHandler(c *core.WebContext) (any, *errs.Error) {
var credential models.TwoFactorRecoveryCodeLoginRequest
err := c.ShouldBindJSON(&credential)
if err != nil {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] parse request failed, because %s", err.Error())
return nil, errs.ErrTwoFactorRecoveryCodeInvalid
}
@@ -189,7 +189,7 @@ func (a *AuthorizationsApi) TwoFactorAuthorizeByRecoveryCodeHandler(c *core.Cont
enableTwoFactor, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
if err != nil {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] failed to get two-factor setting for user \"uid:%d\", because %s", uid, err.Error())
log.Warnf(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] failed to get two-factor setting for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrSystemError)
}
@@ -200,24 +200,24 @@ func (a *AuthorizationsApi) TwoFactorAuthorizeByRecoveryCodeHandler(c *core.Cont
user, err := a.users.GetUserById(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] failed to get user \"uid:%d\" info, because %s", user.Uid, err.Error())
log.Errorf(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] failed to get user \"uid:%d\" info, because %s", user.Uid, err.Error())
return nil, errs.ErrUserNotFound
}
if user.Disabled {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] user \"uid:%d\" is disabled", user.Uid)
log.Warnf(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] user \"uid:%d\" is disabled", user.Uid)
return nil, errs.ErrUserIsDisabled
}
if a.CurrentConfig().EnableUserForceVerifyEmail && !user.EmailVerified {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] user \"uid:%d\" has not verified email", user.Uid)
log.Warnf(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] user \"uid:%d\" has not verified email", user.Uid)
return nil, errs.ErrEmailIsNotVerified
}
err = a.twoFactorAuthorizations.GetAndUseUserTwoFactorRecoveryCode(c, uid, credential.RecoveryCode, user.Salt)
if err != nil {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] failed to get two-factor recovery code for user \"uid:%d\", because %s", uid, err.Error())
log.Warnf(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] failed to get two-factor recovery code for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrTwoFactorRecoveryCodeNotExist)
}
@@ -225,26 +225,26 @@ func (a *AuthorizationsApi) TwoFactorAuthorizeByRecoveryCodeHandler(c *core.Cont
err = a.tokens.DeleteTokenByClaims(c, oldTokenClaims)
if err != nil {
log.WarnfWithRequestId(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] failed to revoke temporary token \"utid:%s\" for user \"uid:%d\", because %s", oldTokenClaims.UserTokenId, user.Uid, err.Error())
log.Warnf(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] failed to revoke temporary token \"utid:%s\" for user \"uid:%d\", because %s", oldTokenClaims.UserTokenId, user.Uid, err.Error())
}
token, claims, err := a.tokens.CreateToken(c, user)
if err != nil {
log.ErrorfWithRequestId(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.ErrTokenGenerating
}
c.SetTextualToken(token)
c.SetTokenClaims(claims)
log.InfofWithRequestId(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] user \"uid:%d\" has authorized two-factor via recovery code \"%s\", token will be expired at %d", user.Uid, credential.RecoveryCode, claims.ExpiresAt)
log.Infof(c, "[authorizations.TwoFactorAuthorizeByRecoveryCodeHandler] user \"uid:%d\" has authorized two-factor via recovery code \"%s\", token will be expired at %d", user.Uid, credential.RecoveryCode, claims.ExpiresAt)
authResp := a.getAuthResponse(c, token, false, user)
return authResp, nil
}
func (a *AuthorizationsApi) getAuthResponse(c *core.Context, token string, need2FA bool, user *models.User) *models.AuthResponse {
func (a *AuthorizationsApi) getAuthResponse(c *core.WebContext, token string, need2FA bool, user *models.User) *models.AuthResponse {
return &models.AuthResponse{
Token: token,
Need2FA: need2FA,
+25 -25
View File
@@ -50,50 +50,50 @@ var (
)
// ExportDataToEzbookkeepingCSVHandler returns exported data in csv format
func (a *DataManagementsApi) ExportDataToEzbookkeepingCSVHandler(c *core.Context) ([]byte, string, *errs.Error) {
func (a *DataManagementsApi) ExportDataToEzbookkeepingCSVHandler(c *core.WebContext) ([]byte, string, *errs.Error) {
return a.getExportedFileContent(c, "csv")
}
// ExportDataToEzbookkeepingTSVHandler returns exported data in csv format
func (a *DataManagementsApi) ExportDataToEzbookkeepingTSVHandler(c *core.Context) ([]byte, string, *errs.Error) {
func (a *DataManagementsApi) ExportDataToEzbookkeepingTSVHandler(c *core.WebContext) ([]byte, string, *errs.Error) {
return a.getExportedFileContent(c, "tsv")
}
// DataStatisticsHandler returns user data statistics
func (a *DataManagementsApi) DataStatisticsHandler(c *core.Context) (any, *errs.Error) {
func (a *DataManagementsApi) DataStatisticsHandler(c *core.WebContext) (any, *errs.Error) {
uid := c.GetCurrentUid()
totalAccountCount, err := a.accounts.GetTotalAccountCountByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.DataStatisticsHandler] failed to get total account count for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[data_managements.DataStatisticsHandler] failed to get total account count for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.ErrOperationFailed
}
totalTransactionCategoryCount, err := a.categories.GetTotalCategoryCountByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.DataStatisticsHandler] failed to get total transaction category count for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[data_managements.DataStatisticsHandler] failed to get total transaction category count for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.ErrOperationFailed
}
totalTransactionTagCount, err := a.tags.GetTotalTagCountByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.DataStatisticsHandler] failed to get total transaction tag count for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[data_managements.DataStatisticsHandler] failed to get total transaction tag count for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.ErrOperationFailed
}
totalTransactionCount, err := a.transactions.GetTotalTransactionCountByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.DataStatisticsHandler] failed to get total transaction count for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[data_managements.DataStatisticsHandler] failed to get total transaction count for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.ErrOperationFailed
}
totalTransactionTemplateCount, err := a.templates.GetTotalNormalTemplateCountByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.DataStatisticsHandler] failed to get total transaction template count for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[data_managements.DataStatisticsHandler] failed to get total transaction template count for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.ErrOperationFailed
}
@@ -109,12 +109,12 @@ func (a *DataManagementsApi) DataStatisticsHandler(c *core.Context) (any, *errs.
}
// ClearDataHandler deletes all user data
func (a *DataManagementsApi) ClearDataHandler(c *core.Context) (any, *errs.Error) {
func (a *DataManagementsApi) ClearDataHandler(c *core.WebContext) (any, *errs.Error) {
var clearDataReq models.ClearDataRequest
err := c.ShouldBindJSON(&clearDataReq)
if err != nil {
log.WarnfWithRequestId(c, "[data_managements.ClearDataHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[data_managements.ClearDataHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -123,7 +123,7 @@ func (a *DataManagementsApi) ClearDataHandler(c *core.Context) (any, *errs.Error
if err != nil {
if !errs.IsCustomError(err) {
log.WarnfWithRequestId(c, "[data_managements.ClearDataHandler] failed to get user for user \"uid:%d\", because %s", uid, err.Error())
log.Warnf(c, "[data_managements.ClearDataHandler] failed to get user for user \"uid:%d\", because %s", uid, err.Error())
}
return nil, errs.ErrUserNotFound
@@ -136,36 +136,36 @@ func (a *DataManagementsApi) ClearDataHandler(c *core.Context) (any, *errs.Error
err = a.transactions.DeleteAllTransactions(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.ClearDataHandler] failed to delete all transactions, because %s", err.Error())
log.Errorf(c, "[data_managements.ClearDataHandler] failed to delete all transactions, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
err = a.categories.DeleteAllCategories(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.ClearDataHandler] failed to delete all transaction categories, because %s", err.Error())
log.Errorf(c, "[data_managements.ClearDataHandler] failed to delete all transaction categories, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
err = a.tags.DeleteAllTags(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.ClearDataHandler] failed to delete all transaction tags, because %s", err.Error())
log.Errorf(c, "[data_managements.ClearDataHandler] failed to delete all transaction tags, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
err = a.templates.DeleteAllTemplates(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.ClearDataHandler] failed to delete all transaction templates, because %s", err.Error())
log.Errorf(c, "[data_managements.ClearDataHandler] failed to delete all transaction templates, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[data_managements.ClearDataHandler] user \"uid:%d\" has cleared all data", uid)
log.Infof(c, "[data_managements.ClearDataHandler] user \"uid:%d\" has cleared all data", uid)
return true, nil
}
func (a *DataManagementsApi) getExportedFileContent(c *core.Context, fileType string) ([]byte, string, *errs.Error) {
func (a *DataManagementsApi) getExportedFileContent(c *core.WebContext, fileType string) ([]byte, string, *errs.Error) {
if !a.CurrentConfig().EnableDataExport {
return nil, "", errs.ErrDataExportNotAllowed
}
@@ -174,7 +174,7 @@ func (a *DataManagementsApi) getExportedFileContent(c *core.Context, fileType st
utcOffset, err := c.GetClientTimezoneOffset()
if err != nil {
log.WarnfWithRequestId(c, "[data_managements.ExportDataHandler] cannot get client timezone offset, because %s", err.Error())
log.Warnf(c, "[data_managements.ExportDataHandler] cannot get client timezone offset, because %s", err.Error())
} else {
timezone = time.FixedZone("Client Timezone", int(utcOffset)*60)
}
@@ -184,7 +184,7 @@ func (a *DataManagementsApi) getExportedFileContent(c *core.Context, fileType st
if err != nil {
if !errs.IsCustomError(err) {
log.WarnfWithRequestId(c, "[data_managements.ExportDataHandler] failed to get user for user \"uid:%d\", because %s", uid, err.Error())
log.Warnf(c, "[data_managements.ExportDataHandler] failed to get user for user \"uid:%d\", because %s", uid, err.Error())
}
return nil, "", errs.ErrUserNotFound
@@ -193,28 +193,28 @@ func (a *DataManagementsApi) getExportedFileContent(c *core.Context, fileType st
accounts, err := a.accounts.GetAllAccountsByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.ExportDataHandler] failed to get all accounts for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[data_managements.ExportDataHandler] failed to get all accounts for user \"uid:%d\", because %s", uid, err.Error())
return nil, "", errs.ErrOperationFailed
}
categories, err := a.categories.GetAllCategoriesByUid(c, uid, 0, -1)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.ExportDataHandler] failed to get categories for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[data_managements.ExportDataHandler] failed to get categories for user \"uid:%d\", because %s", uid, err.Error())
return nil, "", errs.ErrOperationFailed
}
tags, err := a.tags.GetAllTagsByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.ExportDataHandler] failed to get tags for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[data_managements.ExportDataHandler] failed to get tags for user \"uid:%d\", because %s", uid, err.Error())
return nil, "", errs.ErrOperationFailed
}
tagIndexes, err := a.tags.GetAllTagIdsMapOfAllTransactions(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.ExportDataHandler] failed to get tag index for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[data_managements.ExportDataHandler] failed to get tag index for user \"uid:%d\", because %s", uid, err.Error())
return nil, "", errs.ErrOperationFailed
}
@@ -225,7 +225,7 @@ func (a *DataManagementsApi) getExportedFileContent(c *core.Context, fileType st
allTransactions, err := a.transactions.GetAllTransactions(c, uid, pageCountForDataExport, true)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.ExportDataHandler] failed to all transactions user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[data_managements.ExportDataHandler] failed to all transactions user \"uid:%d\", because %s", uid, err.Error())
return nil, "", errs.ErrOperationFailed
}
@@ -240,7 +240,7 @@ func (a *DataManagementsApi) getExportedFileContent(c *core.Context, fileType st
result, err := dataExporter.ToExportedContent(uid, allTransactions, accountMap, categoryMap, tagMap, tagIndexes)
if err != nil {
log.ErrorfWithRequestId(c, "[data_managements.ExportDataHandler] failed to get csv format exported data for \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[data_managements.ExportDataHandler] failed to get csv format exported data for \"uid:%d\", because %s", uid, err.Error())
return nil, "", errs.Or(err, errs.ErrOperationFailed)
}
+2 -2
View File
@@ -14,11 +14,11 @@ var (
)
// ApiNotFound returns api not found error
func (a *DefaultApi) ApiNotFound(c *core.Context) (any, *errs.Error) {
func (a *DefaultApi) ApiNotFound(c *core.WebContext) (any, *errs.Error) {
return nil, errs.ErrApiNotFound
}
// MethodNotAllowed returns method not allowed error
func (a *DefaultApi) MethodNotAllowed(c *core.Context) (any, *errs.Error) {
func (a *DefaultApi) MethodNotAllowed(c *core.WebContext) (any, *errs.Error) {
return nil, errs.ErrMethodNotAllowed
}
+4 -4
View File
@@ -32,7 +32,7 @@ var (
)
// LatestExchangeRateHandler returns latest exchange rate data
func (a *ExchangeRatesApi) LatestExchangeRateHandler(c *core.Context) (any, *errs.Error) {
func (a *ExchangeRatesApi) LatestExchangeRateHandler(c *core.WebContext) (any, *errs.Error) {
dataSource := exchangerates.Container.Current
if dataSource == nil {
@@ -65,12 +65,12 @@ func (a *ExchangeRatesApi) LatestExchangeRateHandler(c *core.Context) (any, *err
resp, err := client.Do(req)
if err != nil {
log.ErrorfWithRequestId(c, "[exchange_rates.LatestExchangeRateHandler] failed to request latest exchange rate data for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[exchange_rates.LatestExchangeRateHandler] failed to request latest exchange rate data for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.ErrFailedToRequestRemoteApi
}
if resp.StatusCode != 200 {
log.ErrorfWithRequestId(c, "[exchange_rates.LatestExchangeRateHandler] failed to get latest exchange rate data response for user \"uid:%d\", because response code is not 200", uid)
log.Errorf(c, "[exchange_rates.LatestExchangeRateHandler] failed to get latest exchange rate data response for user \"uid:%d\", because response code is not 200", uid)
return nil, errs.ErrFailedToRequestRemoteApi
}
@@ -79,7 +79,7 @@ func (a *ExchangeRatesApi) LatestExchangeRateHandler(c *core.Context) (any, *err
exchangeRateResp, err := dataSource.Parse(c, body)
if err != nil {
log.ErrorfWithRequestId(c, "[exchange_rates.LatestExchangeRateHandler] failed to parse response for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[exchange_rates.LatestExchangeRateHandler] failed to parse response for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrFailedToRequestRemoteApi)
}
+17 -17
View File
@@ -32,12 +32,12 @@ var (
)
// UserForgetPasswordRequestHandler generates password reset link and send user an email with this link
func (a *ForgetPasswordsApi) UserForgetPasswordRequestHandler(c *core.Context) (any, *errs.Error) {
func (a *ForgetPasswordsApi) UserForgetPasswordRequestHandler(c *core.WebContext) (any, *errs.Error) {
var request models.ForgetPasswordRequest
err := c.ShouldBindJSON(&request)
if err != nil {
log.WarnfWithRequestId(c, "[forget_passwords.UserForgetPasswordRequestHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[forget_passwords.UserForgetPasswordRequestHandler] parse request failed, because %s", err.Error())
return nil, errs.ErrEmailIsEmptyOrInvalid
}
@@ -45,19 +45,19 @@ func (a *ForgetPasswordsApi) UserForgetPasswordRequestHandler(c *core.Context) (
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[forget_passwords.UserForgetPasswordRequestHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[forget_passwords.UserForgetPasswordRequestHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
}
if user.Disabled {
log.WarnfWithRequestId(c, "[forget_passwords.UserForgetPasswordRequestHandler] user \"uid:%d\" is disabled", user.Uid)
log.Warnf(c, "[forget_passwords.UserForgetPasswordRequestHandler] user \"uid:%d\" is disabled", user.Uid)
return nil, errs.ErrUserIsDisabled
}
if a.CurrentConfig().ForgetPasswordRequireVerifyEmail && !user.EmailVerified {
log.WarnfWithRequestId(c, "[forget_passwords.UserForgetPasswordRequestHandler] user \"uid:%d\" has not verified email", user.Uid)
log.Warnf(c, "[forget_passwords.UserForgetPasswordRequestHandler] user \"uid:%d\" has not verified email", user.Uid)
return nil, errs.ErrEmailIsNotVerified
}
@@ -68,7 +68,7 @@ func (a *ForgetPasswordsApi) UserForgetPasswordRequestHandler(c *core.Context) (
token, _, err := a.tokens.CreatePasswordResetToken(c, user)
if err != nil {
log.ErrorfWithRequestId(c, "[forget_passwords.UserForgetPasswordRequestHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[forget_passwords.UserForgetPasswordRequestHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.ErrTokenGenerating
}
@@ -76,7 +76,7 @@ func (a *ForgetPasswordsApi) UserForgetPasswordRequestHandler(c *core.Context) (
err = a.forgetPasswords.SendPasswordResetEmail(c, user, token, c.GetClientLocale())
if err != nil {
log.WarnfWithRequestId(c, "[forget_passwords.UserForgetPasswordRequestHandler] cannot send email to \"%s\", because %s", user.Email, err.Error())
log.Warnf(c, "[forget_passwords.UserForgetPasswordRequestHandler] cannot send email to \"%s\", because %s", user.Email, err.Error())
}
}()
@@ -84,12 +84,12 @@ func (a *ForgetPasswordsApi) UserForgetPasswordRequestHandler(c *core.Context) (
}
// UserResetPasswordHandler resets user password by request parameters
func (a *ForgetPasswordsApi) UserResetPasswordHandler(c *core.Context) (any, *errs.Error) {
func (a *ForgetPasswordsApi) UserResetPasswordHandler(c *core.WebContext) (any, *errs.Error) {
var request models.PasswordResetRequest
err := c.ShouldBindJSON(&request)
if err != nil {
log.WarnfWithRequestId(c, "[forget_passwords.UserResetPasswordHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[forget_passwords.UserResetPasswordHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -98,24 +98,24 @@ func (a *ForgetPasswordsApi) UserResetPasswordHandler(c *core.Context) (any, *er
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[forget_passwords.UserResetPasswordHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[forget_passwords.UserResetPasswordHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
}
if user.Disabled {
log.WarnfWithRequestId(c, "[forget_passwords.UserResetPasswordHandler] user \"uid:%d\" is disabled", user.Uid)
log.Warnf(c, "[forget_passwords.UserResetPasswordHandler] user \"uid:%d\" is disabled", user.Uid)
return nil, errs.ErrUserIsDisabled
}
if a.CurrentConfig().ForgetPasswordRequireVerifyEmail && !user.EmailVerified {
log.WarnfWithRequestId(c, "[forget_passwords.UserResetPasswordHandler] user \"uid:%d\" has not verified email", user.Uid)
log.Warnf(c, "[forget_passwords.UserResetPasswordHandler] user \"uid:%d\" has not verified email", user.Uid)
return nil, errs.ErrEmailIsNotVerified
}
if user.Email != request.Email {
log.WarnfWithRequestId(c, "[forget_passwords.UserResetPasswordHandler] request email not equals the user email")
log.Warnf(c, "[forget_passwords.UserResetPasswordHandler] request email not equals the user email")
return nil, errs.ErrEmptyIsInvalid
}
@@ -124,7 +124,7 @@ func (a *ForgetPasswordsApi) UserResetPasswordHandler(c *core.Context) (any, *er
err = a.tokens.DeleteTokenByClaims(c, oldTokenClaims)
if err != nil {
log.WarnfWithRequestId(c, "[forget_passwords.UserResetPasswordHandler] failed to revoke password reset token \"utid:%s\" for user \"uid:%d\", because %s", oldTokenClaims.UserTokenId, user.Uid, err.Error())
log.Warnf(c, "[forget_passwords.UserResetPasswordHandler] failed to revoke password reset token \"utid:%s\" for user \"uid:%d\", because %s", oldTokenClaims.UserTokenId, user.Uid, err.Error())
}
return nil, errs.ErrNewPasswordEqualsOldInvalid
@@ -139,7 +139,7 @@ func (a *ForgetPasswordsApi) UserResetPasswordHandler(c *core.Context) (any, *er
_, _, err = a.users.UpdateUser(c, userNew, false)
if err != nil {
log.ErrorfWithRequestId(c, "[forget_passwords.UserResetPasswordHandler] failed to update user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[forget_passwords.UserResetPasswordHandler] failed to update user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -147,9 +147,9 @@ func (a *ForgetPasswordsApi) UserResetPasswordHandler(c *core.Context) (any, *er
err = a.tokens.DeleteTokensBeforeTime(c, uid, now)
if err == nil {
log.InfofWithRequestId(c, "[forget_passwords.UserResetPasswordHandler] revoke old tokens before unix time \"%d\" for user \"uid:%d\"", now, user.Uid)
log.Infof(c, "[forget_passwords.UserResetPasswordHandler] revoke old tokens before unix time \"%d\" for user \"uid:%d\"", now, user.Uid)
} else {
log.WarnfWithRequestId(c, "[forget_passwords.UserResetPasswordHandler] failed to revoke old tokens for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Warnf(c, "[forget_passwords.UserResetPasswordHandler] failed to revoke old tokens for user \"uid:%d\", because %s", user.Uid, err.Error())
}
return true, nil
+1 -1
View File
@@ -15,7 +15,7 @@ var (
)
// HealthStatusHandler returns the health status of current service
func (a *HealthsApi) HealthStatusHandler(c *core.Context) (any, *errs.Error) {
func (a *HealthsApi) HealthStatusHandler(c *core.WebContext) (any, *errs.Error) {
result := make(map[string]string)
result["version"] = settings.Version
+5 -5
View File
@@ -37,8 +37,8 @@ var (
)
// MapTileImageProxyHandler returns map tile image
func (p *MapImageProxy) MapTileImageProxyHandler(c *core.Context) (*httputil.ReverseProxy, *errs.Error) {
return p.mapImageProxyHandler(c, func(c *core.Context, mapProvider string) (string, *errs.Error) {
func (p *MapImageProxy) MapTileImageProxyHandler(c *core.WebContext) (*httputil.ReverseProxy, *errs.Error) {
return p.mapImageProxyHandler(c, func(c *core.WebContext, mapProvider string) (string, *errs.Error) {
if mapProvider == settings.OpenStreetMapProvider {
return openStreetMapTileImageUrlFormat, nil
} else if mapProvider == settings.OpenStreetMapHumanitarianStyleProvider {
@@ -71,8 +71,8 @@ func (p *MapImageProxy) MapTileImageProxyHandler(c *core.Context) (*httputil.Rev
}
// MapAnnotationImageProxyHandler returns map annotation image
func (p *MapImageProxy) MapAnnotationImageProxyHandler(c *core.Context) (*httputil.ReverseProxy, *errs.Error) {
return p.mapImageProxyHandler(c, func(c *core.Context, mapProvider string) (string, *errs.Error) {
func (p *MapImageProxy) MapAnnotationImageProxyHandler(c *core.WebContext) (*httputil.ReverseProxy, *errs.Error) {
return p.mapImageProxyHandler(c, func(c *core.WebContext, mapProvider string) (string, *errs.Error) {
if mapProvider == settings.TianDiTuProvider {
return tianDiTuMapAnnotationUrlFormat + "&tk=" + p.CurrentConfig().TianDiTuAPIKey, nil
} else if mapProvider == settings.CustomProvider {
@@ -83,7 +83,7 @@ func (p *MapImageProxy) MapAnnotationImageProxyHandler(c *core.Context) (*httput
})
}
func (p *MapImageProxy) mapImageProxyHandler(c *core.Context, fn func(c *core.Context, mapProvider string) (string, *errs.Error)) (*httputil.ReverseProxy, *errs.Error) {
func (p *MapImageProxy) mapImageProxyHandler(c *core.WebContext, fn func(c *core.WebContext, mapProvider string) (string, *errs.Error)) (*httputil.ReverseProxy, *errs.Error) {
mapProvider := strings.Replace(c.Query("provider"), "-", "_", -1)
targetUrl := ""
+2 -2
View File
@@ -32,7 +32,7 @@ var (
)
// MobileUrlQrCodeHandler returns a mobile url qr code image
func (a *QrCodesApi) MobileUrlQrCodeHandler(c *core.Context) ([]byte, string, *errs.Error) {
func (a *QrCodesApi) MobileUrlQrCodeHandler(c *core.WebContext) ([]byte, string, *errs.Error) {
fullUrl := a.CurrentConfig().RootUrl + "mobile"
data, err := a.generateUrlQrCode(c, fullUrl)
@@ -43,7 +43,7 @@ func (a *QrCodesApi) MobileUrlQrCodeHandler(c *core.Context) ([]byte, string, *e
return data, "image/png", nil
}
func (a *QrCodesApi) generateUrlQrCode(c *core.Context, url string) ([]byte, *errs.Error) {
func (a *QrCodesApi) generateUrlQrCode(c *core.WebContext, url string) ([]byte, *errs.Error) {
qrCodeImg, _ := qr.Encode(url, qr.M, qr.Auto)
qrCodeImg, _ = barcode.Scale(qrCodeImg, qrCodeDefaultWidth, qrCodeDefaultHeight)
imgData := &bytes.Buffer{}
+23 -23
View File
@@ -32,12 +32,12 @@ var (
)
// TokenListHandler returns available token list of current user
func (a *TokensApi) TokenListHandler(c *core.Context) (any, *errs.Error) {
func (a *TokensApi) TokenListHandler(c *core.WebContext) (any, *errs.Error) {
uid := c.GetCurrentUid()
tokens, err := a.tokens.GetAllUnexpiredNormalTokensByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[tokens.TokenListHandler] failed to get all tokens for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[tokens.TokenListHandler] failed to get all tokens for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -66,7 +66,7 @@ func (a *TokensApi) TokenListHandler(c *core.Context) (any, *errs.Error) {
}
// TokenRevokeCurrentHandler revokes current token of current user
func (a *TokensApi) TokenRevokeCurrentHandler(c *core.Context) (any, *errs.Error) {
func (a *TokensApi) TokenRevokeCurrentHandler(c *core.WebContext) (any, *errs.Error) {
_, claims, err := a.tokens.ParseTokenByHeader(c)
if err != nil {
@@ -76,7 +76,7 @@ func (a *TokensApi) TokenRevokeCurrentHandler(c *core.Context) (any, *errs.Error
userTokenId, err := utils.StringToInt64(claims.UserTokenId)
if err != nil {
log.WarnfWithRequestId(c, "[tokens.TokenRevokeCurrentHandler] parse user token id failed, because %s", err.Error())
log.Warnf(c, "[tokens.TokenRevokeCurrentHandler] parse user token id failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -90,21 +90,21 @@ func (a *TokensApi) TokenRevokeCurrentHandler(c *core.Context) (any, *errs.Error
err = a.tokens.DeleteToken(c, tokenRecord)
if err != nil {
log.ErrorfWithRequestId(c, "[token.TokenRevokeCurrentHandler] failed to revoke token \"id:%s\" for user \"uid:%d\", because %s", tokenId, claims.Uid, err.Error())
log.Errorf(c, "[token.TokenRevokeCurrentHandler] failed to revoke token \"id:%s\" for user \"uid:%d\", because %s", tokenId, claims.Uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[token.TokenRevokeCurrentHandler] user \"uid:%d\" has revoked token \"id:%s\"", claims.Uid, tokenId)
log.Infof(c, "[token.TokenRevokeCurrentHandler] user \"uid:%d\" has revoked token \"id:%s\"", claims.Uid, tokenId)
return true, nil
}
// TokenRevokeHandler revokes specific token of current user
func (a *TokensApi) TokenRevokeHandler(c *core.Context) (any, *errs.Error) {
func (a *TokensApi) TokenRevokeHandler(c *core.WebContext) (any, *errs.Error) {
var tokenRevokeReq models.TokenRevokeRequest
err := c.ShouldBindJSON(&tokenRevokeReq)
if err != nil {
log.WarnfWithRequestId(c, "[tokens.TokenRevokeHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[tokens.TokenRevokeHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -112,7 +112,7 @@ func (a *TokensApi) TokenRevokeHandler(c *core.Context) (any, *errs.Error) {
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[token.TokenRevokeHandler] failed to parse token \"id:%s\", because %s", tokenRevokeReq.TokenId, err.Error())
log.Errorf(c, "[token.TokenRevokeHandler] failed to parse token \"id:%s\", because %s", tokenRevokeReq.TokenId, err.Error())
}
return nil, errs.Or(err, errs.ErrInvalidTokenId)
@@ -121,28 +121,28 @@ func (a *TokensApi) TokenRevokeHandler(c *core.Context) (any, *errs.Error) {
uid := c.GetCurrentUid()
if tokenRecord.Uid != uid {
log.WarnfWithRequestId(c, "[token.TokenRevokeHandler] token \"id:%s\" is not owned by user \"uid:%d\"", tokenRevokeReq.TokenId, uid)
log.Warnf(c, "[token.TokenRevokeHandler] token \"id:%s\" is not owned by user \"uid:%d\"", tokenRevokeReq.TokenId, uid)
return nil, errs.ErrInvalidTokenId
}
err = a.tokens.DeleteToken(c, tokenRecord)
if err != nil {
log.ErrorfWithRequestId(c, "[token.TokenRevokeHandler] failed to revoke token \"id:%s\" for user \"uid:%d\", because %s", tokenRevokeReq.TokenId, uid, err.Error())
log.Errorf(c, "[token.TokenRevokeHandler] failed to revoke token \"id:%s\" for user \"uid:%d\", because %s", tokenRevokeReq.TokenId, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[token.TokenRevokeHandler] user \"uid:%d\" has revoked token \"id:%s\"", uid, tokenRevokeReq.TokenId)
log.Infof(c, "[token.TokenRevokeHandler] user \"uid:%d\" has revoked token \"id:%s\"", uid, tokenRevokeReq.TokenId)
return true, nil
}
// TokenRevokeAllHandler revokes all tokens of current user except current token
func (a *TokensApi) TokenRevokeAllHandler(c *core.Context) (any, *errs.Error) {
func (a *TokensApi) TokenRevokeAllHandler(c *core.WebContext) (any, *errs.Error) {
uid := c.GetCurrentUid()
tokens, err := a.tokens.GetAllTokensByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[tokens.TokenRevokeAllHandler] failed to get all tokens for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[tokens.TokenRevokeAllHandler] failed to get all tokens for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -163,21 +163,21 @@ func (a *TokensApi) TokenRevokeAllHandler(c *core.Context) (any, *errs.Error) {
err = a.tokens.DeleteTokens(c, uid, tokens)
if err != nil {
log.ErrorfWithRequestId(c, "[token.TokenRevokeAllHandler] failed to revoke all tokens for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[token.TokenRevokeAllHandler] failed to revoke all tokens for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[token.TokenRevokeAllHandler] user \"uid:%d\" has revoked all tokens", uid)
log.Infof(c, "[token.TokenRevokeAllHandler] user \"uid:%d\" has revoked all tokens", uid)
return true, nil
}
// TokenRefreshHandler refresh current token of current user
func (a *TokensApi) TokenRefreshHandler(c *core.Context) (any, *errs.Error) {
func (a *TokensApi) TokenRefreshHandler(c *core.WebContext) (any, *errs.Error) {
uid := c.GetCurrentUid()
user, err := a.users.GetUserById(c, uid)
if err != nil {
log.WarnfWithRequestId(c, "[token.TokenRefreshHandler] failed to get user \"uid:%d\" info, because %s", uid, err.Error())
log.Warnf(c, "[token.TokenRefreshHandler] failed to get user \"uid:%d\" info, because %s", uid, err.Error())
return nil, errs.ErrUserNotFound
}
@@ -185,12 +185,12 @@ func (a *TokensApi) TokenRefreshHandler(c *core.Context) (any, *errs.Error) {
oldTokenClaims := c.GetTokenClaims()
if now-oldTokenClaims.IssuedAt < int64(a.CurrentConfig().TokenMinRefreshInterval) {
log.InfofWithRequestId(c, "[token.TokenRefreshHandler] token of user \"uid:%d\" does not need to be refreshed", uid)
log.Infof(c, "[token.TokenRefreshHandler] token of user \"uid:%d\" does not need to be refreshed", uid)
userTokenId, err := utils.StringToInt64(oldTokenClaims.UserTokenId)
if err != nil {
log.WarnfWithRequestId(c, "[tokens.TokenRefreshHandler] parse user token id failed, because %s", err.Error())
log.Warnf(c, "[tokens.TokenRefreshHandler] parse user token id failed, because %s", err.Error())
} else {
tokenRecord := &models.TokenRecord{
Uid: oldTokenClaims.Uid,
@@ -203,7 +203,7 @@ func (a *TokensApi) TokenRefreshHandler(c *core.Context) (any, *errs.Error) {
err = a.tokens.UpdateTokenLastSeen(c, tokenRecord)
if err != nil {
log.WarnfWithRequestId(c, "[token.TokenRefreshHandler] failed to update last seen of token \"id:%s\" for user \"uid:%d\", because %s", tokenId, uid, err.Error())
log.Warnf(c, "[token.TokenRefreshHandler] failed to update last seen of token \"id:%s\" for user \"uid:%d\", because %s", tokenId, uid, err.Error())
}
}
@@ -218,7 +218,7 @@ func (a *TokensApi) TokenRefreshHandler(c *core.Context) (any, *errs.Error) {
token, claims, err := a.tokens.CreateToken(c, user)
if err != nil {
log.ErrorfWithRequestId(c, "[token.TokenRefreshHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[token.TokenRefreshHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.Or(err, errs.ErrTokenGenerating)
}
@@ -232,7 +232,7 @@ func (a *TokensApi) TokenRefreshHandler(c *core.Context) (any, *errs.Error) {
c.SetTextualToken(token)
c.SetTokenClaims(claims)
log.InfofWithRequestId(c, "[token.TokenRefreshHandler] user \"uid:%d\" token refreshed, new token will be expired at %d", user.Uid, claims.ExpiresAt)
log.Infof(c, "[token.TokenRefreshHandler] user \"uid:%d\" token refreshed, new token will be expired at %d", user.Uid, claims.ExpiresAt)
refreshResp := &models.TokenRefreshResponse{
NewToken: token,
+42 -42
View File
@@ -36,12 +36,12 @@ var (
)
// CategoryListHandler returns transaction category list of current user
func (a *TransactionCategoriesApi) CategoryListHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionCategoriesApi) CategoryListHandler(c *core.WebContext) (any, *errs.Error) {
var categoryListReq models.TransactionCategoryListRequest
err := c.ShouldBindQuery(&categoryListReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_categories.CategoryListHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_categories.CategoryListHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -49,7 +49,7 @@ func (a *TransactionCategoriesApi) CategoryListHandler(c *core.Context) (any, *e
categories, err := a.categories.GetAllCategoriesByUid(c, uid, categoryListReq.Type, categoryListReq.ParentId)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryListHandler] failed to get categories for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryListHandler] failed to get categories for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -57,12 +57,12 @@ func (a *TransactionCategoriesApi) CategoryListHandler(c *core.Context) (any, *e
}
// CategoryGetHandler returns one specific transaction category of current user
func (a *TransactionCategoriesApi) CategoryGetHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionCategoriesApi) CategoryGetHandler(c *core.WebContext) (any, *errs.Error) {
var categoryGetReq models.TransactionCategoryGetRequest
err := c.ShouldBindQuery(&categoryGetReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_categories.CategoryGetHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_categories.CategoryGetHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -70,7 +70,7 @@ func (a *TransactionCategoriesApi) CategoryGetHandler(c *core.Context) (any, *er
category, err := a.categories.GetCategoryByCategoryId(c, uid, categoryGetReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryGetHandler] failed to get category \"id:%d\" for user \"uid:%d\", because %s", categoryGetReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryGetHandler] failed to get category \"id:%d\" for user \"uid:%d\", because %s", categoryGetReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -80,17 +80,17 @@ func (a *TransactionCategoriesApi) CategoryGetHandler(c *core.Context) (any, *er
}
// CategoryCreateHandler saves a new transaction category by request parameters for current user
func (a *TransactionCategoriesApi) CategoryCreateHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionCategoriesApi) CategoryCreateHandler(c *core.WebContext) (any, *errs.Error) {
var categoryCreateReq models.TransactionCategoryCreateRequest
err := c.ShouldBindJSON(&categoryCreateReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_categories.CategoryCreateHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_categories.CategoryCreateHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
if categoryCreateReq.Type < models.CATEGORY_TYPE_INCOME || categoryCreateReq.Type > models.CATEGORY_TYPE_TRANSFER {
log.WarnfWithRequestId(c, "[transaction_categories.CategoryCreateHandler] category type invalid, type is %d", categoryCreateReq.Type)
log.Warnf(c, "[transaction_categories.CategoryCreateHandler] category type invalid, type is %d", categoryCreateReq.Type)
return nil, errs.ErrTransactionCategoryTypeInvalid
}
@@ -100,17 +100,17 @@ func (a *TransactionCategoriesApi) CategoryCreateHandler(c *core.Context) (any,
parentCategory, err := a.categories.GetCategoryByCategoryId(c, uid, categoryCreateReq.ParentId)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryCreateHandler] failed to get parent category \"id:%d\" for user \"uid:%d\", because %s", categoryCreateReq.ParentId, uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryCreateHandler] failed to get parent category \"id:%d\" for user \"uid:%d\", because %s", categoryCreateReq.ParentId, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
if parentCategory == nil {
log.WarnfWithRequestId(c, "[transaction_categories.CategoryCreateHandler] parent category \"id:%d\" does not exist for user \"uid:%d\"", categoryCreateReq.ParentId, uid)
log.Warnf(c, "[transaction_categories.CategoryCreateHandler] parent category \"id:%d\" does not exist for user \"uid:%d\"", categoryCreateReq.ParentId, uid)
return nil, errs.ErrParentTransactionCategoryNotFound
}
if parentCategory.ParentCategoryId > 0 {
log.WarnfWithRequestId(c, "[transaction_categories.CategoryCreateHandler] parent category \"id:%d\" has another parent category \"id:%d\" for user \"uid:%d\"", parentCategory.CategoryId, parentCategory.ParentCategoryId, uid)
log.Warnf(c, "[transaction_categories.CategoryCreateHandler] parent category \"id:%d\" has another parent category \"id:%d\" for user \"uid:%d\"", parentCategory.CategoryId, parentCategory.ParentCategoryId, uid)
return nil, errs.ErrCannotAddToSecondaryTransactionCategory
}
}
@@ -124,7 +124,7 @@ func (a *TransactionCategoriesApi) CategoryCreateHandler(c *core.Context) (any,
}
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryCreateHandler] failed to get max display order for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryCreateHandler] failed to get max display order for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -134,14 +134,14 @@ func (a *TransactionCategoriesApi) CategoryCreateHandler(c *core.Context) (any,
found, remark := a.GetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_CATEGORY, uid, categoryCreateReq.ClientSessionId)
if found {
log.InfofWithRequestId(c, "[transaction_categories.CategoryCreateHandler] another category \"id:%s\" has been created for user \"uid:%d\"", remark, uid)
log.Infof(c, "[transaction_categories.CategoryCreateHandler] another category \"id:%s\" has been created for user \"uid:%d\"", remark, uid)
categoryId, err := utils.StringToInt64(remark)
if err == nil {
category, err = a.categories.GetCategoryByCategoryId(c, uid, categoryId)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryCreateHandler] failed to get existed category \"id:%d\" for user \"uid:%d\", because %s", categoryId, uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryCreateHandler] failed to get existed category \"id:%d\" for user \"uid:%d\", because %s", categoryId, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -155,11 +155,11 @@ func (a *TransactionCategoriesApi) CategoryCreateHandler(c *core.Context) (any,
err = a.categories.CreateCategory(c, category)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryCreateHandler] failed to create category \"id:%d\" for user \"uid:%d\", because %s", category.CategoryId, uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryCreateHandler] failed to create category \"id:%d\" for user \"uid:%d\", because %s", category.CategoryId, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_categories.CategoryCreateHandler] user \"uid:%d\" has created a new category \"id:%d\" successfully", uid, category.CategoryId)
log.Infof(c, "[transaction_categories.CategoryCreateHandler] user \"uid:%d\" has created a new category \"id:%d\" successfully", uid, category.CategoryId)
a.SetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_CATEGORY, uid, categoryCreateReq.ClientSessionId, utils.Int64ToString(category.CategoryId))
categoryResp := category.ToTransactionCategoryInfoResponse()
@@ -168,12 +168,12 @@ func (a *TransactionCategoriesApi) CategoryCreateHandler(c *core.Context) (any,
}
// CategoryCreateBatchHandler saves some new transaction category by request parameters for current user
func (a *TransactionCategoriesApi) CategoryCreateBatchHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionCategoriesApi) CategoryCreateBatchHandler(c *core.WebContext) (any, *errs.Error) {
var categoryCreateBatchReq models.TransactionCategoryCreateBatchRequest
err := c.ShouldBindBodyWith(&categoryCreateBatchReq, binding.JSON)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_categories.CategoryCreateBatchHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_categories.CategoryCreateBatchHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -189,12 +189,12 @@ func (a *TransactionCategoriesApi) CategoryCreateBatchHandler(c *core.Context) (
}
// CategoryModifyHandler saves an existed transaction category by request parameters for current user
func (a *TransactionCategoriesApi) CategoryModifyHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionCategoriesApi) CategoryModifyHandler(c *core.WebContext) (any, *errs.Error) {
var categoryModifyReq models.TransactionCategoryModifyRequest
err := c.ShouldBindJSON(&categoryModifyReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_categories.CategoryModifyHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_categories.CategoryModifyHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -202,7 +202,7 @@ func (a *TransactionCategoriesApi) CategoryModifyHandler(c *core.Context) (any,
category, err := a.categories.GetCategoryByCategoryId(c, uid, categoryModifyReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryModifyHandler] failed to get category \"id:%d\" for user \"uid:%d\", because %s", categoryModifyReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryModifyHandler] failed to get category \"id:%d\" for user \"uid:%d\", because %s", categoryModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -238,14 +238,14 @@ func (a *TransactionCategoriesApi) CategoryModifyHandler(c *core.Context) (any,
fromPrimaryCategory, err := a.categories.GetCategoryByCategoryId(c, uid, category.ParentCategoryId)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryModifyHandler] failed to get old primary category \"id:%d\" of category \"id:%d\" for user \"uid:%d\", because %s", category.ParentCategoryId, categoryModifyReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryModifyHandler] failed to get old primary category \"id:%d\" of category \"id:%d\" for user \"uid:%d\", because %s", category.ParentCategoryId, categoryModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
toPrimaryCategory, err := a.categories.GetCategoryByCategoryId(c, uid, newCategory.ParentCategoryId)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryModifyHandler] failed to get new primary category \"id:%d\" of category \"id:%d\" for user \"uid:%d\", because %s", newCategory.ParentCategoryId, categoryModifyReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryModifyHandler] failed to get new primary category \"id:%d\" of category \"id:%d\" for user \"uid:%d\", because %s", newCategory.ParentCategoryId, categoryModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -261,11 +261,11 @@ func (a *TransactionCategoriesApi) CategoryModifyHandler(c *core.Context) (any,
err = a.categories.ModifyCategory(c, newCategory)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryModifyHandler] failed to update category \"id:%d\" for user \"uid:%d\", because %s", categoryModifyReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryModifyHandler] failed to update category \"id:%d\" for user \"uid:%d\", because %s", categoryModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_categories.CategoryModifyHandler] user \"uid:%d\" has updated category \"id:%d\" successfully", uid, categoryModifyReq.Id)
log.Infof(c, "[transaction_categories.CategoryModifyHandler] user \"uid:%d\" has updated category \"id:%d\" successfully", uid, categoryModifyReq.Id)
newCategory.Type = category.Type
newCategory.DisplayOrder = category.DisplayOrder
@@ -275,12 +275,12 @@ func (a *TransactionCategoriesApi) CategoryModifyHandler(c *core.Context) (any,
}
// CategoryHideHandler hides an existed transaction category by request parameters for current user
func (a *TransactionCategoriesApi) CategoryHideHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionCategoriesApi) CategoryHideHandler(c *core.WebContext) (any, *errs.Error) {
var categoryHideReq models.TransactionCategoryHideRequest
err := c.ShouldBindJSON(&categoryHideReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_categories.CategoryHideHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_categories.CategoryHideHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -288,21 +288,21 @@ func (a *TransactionCategoriesApi) CategoryHideHandler(c *core.Context) (any, *e
err = a.categories.HideCategory(c, uid, []int64{categoryHideReq.Id}, categoryHideReq.Hidden)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryHideHandler] failed to hide category \"id:%d\" for user \"uid:%d\", because %s", categoryHideReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryHideHandler] failed to hide category \"id:%d\" for user \"uid:%d\", because %s", categoryHideReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_categories.CategoryHideHandler] user \"uid:%d\" has hidden category \"id:%d\"", uid, categoryHideReq.Id)
log.Infof(c, "[transaction_categories.CategoryHideHandler] user \"uid:%d\" has hidden category \"id:%d\"", uid, categoryHideReq.Id)
return true, nil
}
// CategoryMoveHandler moves display order of existed transaction categories by request parameters for current user
func (a *TransactionCategoriesApi) CategoryMoveHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionCategoriesApi) CategoryMoveHandler(c *core.WebContext) (any, *errs.Error) {
var categoryMoveReq models.TransactionCategoryMoveRequest
err := c.ShouldBindJSON(&categoryMoveReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_categories.CategoryMoveHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_categories.CategoryMoveHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -323,21 +323,21 @@ func (a *TransactionCategoriesApi) CategoryMoveHandler(c *core.Context) (any, *e
err = a.categories.ModifyCategoryDisplayOrders(c, uid, categories)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryMoveHandler] failed to move categories for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryMoveHandler] failed to move categories for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_categories.CategoryMoveHandler] user \"uid:%d\" has moved categories", uid)
log.Infof(c, "[transaction_categories.CategoryMoveHandler] user \"uid:%d\" has moved categories", uid)
return true, nil
}
// CategoryDeleteHandler deletes an existed transaction category by request parameters for current user
func (a *TransactionCategoriesApi) CategoryDeleteHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionCategoriesApi) CategoryDeleteHandler(c *core.WebContext) (any, *errs.Error) {
var categoryDeleteReq models.TransactionCategoryDeleteRequest
err := c.ShouldBindJSON(&categoryDeleteReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_categories.CategoryDeleteHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_categories.CategoryDeleteHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -345,15 +345,15 @@ func (a *TransactionCategoriesApi) CategoryDeleteHandler(c *core.Context) (any,
err = a.categories.DeleteCategory(c, uid, categoryDeleteReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryDeleteHandler] failed to delete category \"id:%d\" for user \"uid:%d\", because %s", categoryDeleteReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryDeleteHandler] failed to delete category \"id:%d\" for user \"uid:%d\", because %s", categoryDeleteReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_categories.CategoryDeleteHandler] user \"uid:%d\" has deleted category \"id:%d\"", uid, categoryDeleteReq.Id)
log.Infof(c, "[transaction_categories.CategoryDeleteHandler] user \"uid:%d\" has deleted category \"id:%d\"", uid, categoryDeleteReq.Id)
return true, nil
}
func (a *TransactionCategoriesApi) createBatchCategories(c *core.Context, uid int64, categoryCreateBatchReq *models.TransactionCategoryCreateBatchRequest) ([]*models.TransactionCategory, error) {
func (a *TransactionCategoriesApi) createBatchCategories(c *core.WebContext, uid int64, categoryCreateBatchReq *models.TransactionCategoryCreateBatchRequest) ([]*models.TransactionCategory, error) {
var err error
categoryTypeMaxOrderMap := make(map[models.TransactionCategoryType]int32)
categoriesMap := make(map[*models.TransactionCategory][]*models.TransactionCategory)
@@ -368,7 +368,7 @@ func (a *TransactionCategoriesApi) createBatchCategories(c *core.Context, uid in
maxOrderId, err = a.categories.GetMaxDisplayOrder(c, uid, categoryCreateReq.Type)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.CategoryCreateBatchHandler] failed to get max display order for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transaction_categories.CategoryCreateBatchHandler] failed to get max display order for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
}
@@ -396,11 +396,11 @@ func (a *TransactionCategoriesApi) createBatchCategories(c *core.Context, uid in
categories, err := a.categories.CreateCategories(c, uid, categoriesMap)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_categories.createBatchCategories] failed to create categories for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transaction_categories.createBatchCategories] failed to create categories for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_categories.createBatchCategories] user \"uid:%d\" has created categories successfully", uid)
log.Infof(c, "[transaction_categories.createBatchCategories] user \"uid:%d\" has created categories successfully", uid)
return categories, nil
}
+27 -27
View File
@@ -23,12 +23,12 @@ var (
)
// TagListHandler returns transaction tag list of current user
func (a *TransactionTagsApi) TagListHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTagsApi) TagListHandler(c *core.WebContext) (any, *errs.Error) {
uid := c.GetCurrentUid()
tags, err := a.tags.GetAllTagsByUid(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_tags.TagListHandler] failed to get tags for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transaction_tags.TagListHandler] failed to get tags for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -44,12 +44,12 @@ func (a *TransactionTagsApi) TagListHandler(c *core.Context) (any, *errs.Error)
}
// TagGetHandler returns one specific transaction tag of current user
func (a *TransactionTagsApi) TagGetHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTagsApi) TagGetHandler(c *core.WebContext) (any, *errs.Error) {
var tagGetReq models.TransactionTagGetRequest
err := c.ShouldBindQuery(&tagGetReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_tags.TagGetHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_tags.TagGetHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -57,7 +57,7 @@ func (a *TransactionTagsApi) TagGetHandler(c *core.Context) (any, *errs.Error) {
tag, err := a.tags.GetTagByTagId(c, uid, tagGetReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_tags.TagGetHandler] failed to get tag \"id:%d\" for user \"uid:%d\", because %s", tagGetReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_tags.TagGetHandler] failed to get tag \"id:%d\" for user \"uid:%d\", because %s", tagGetReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -67,12 +67,12 @@ func (a *TransactionTagsApi) TagGetHandler(c *core.Context) (any, *errs.Error) {
}
// TagCreateHandler saves a new transaction tag by request parameters for current user
func (a *TransactionTagsApi) TagCreateHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTagsApi) TagCreateHandler(c *core.WebContext) (any, *errs.Error) {
var tagCreateReq models.TransactionTagCreateRequest
err := c.ShouldBindJSON(&tagCreateReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_tags.TagCreateHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_tags.TagCreateHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -81,7 +81,7 @@ func (a *TransactionTagsApi) TagCreateHandler(c *core.Context) (any, *errs.Error
maxOrderId, err := a.tags.GetMaxDisplayOrder(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_tags.TagCreateHandler] failed to get max display order for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transaction_tags.TagCreateHandler] failed to get max display order for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -90,11 +90,11 @@ func (a *TransactionTagsApi) TagCreateHandler(c *core.Context) (any, *errs.Error
err = a.tags.CreateTag(c, tag)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_tags.TagCreateHandler] failed to create tag \"id:%d\" for user \"uid:%d\", because %s", tag.TagId, uid, err.Error())
log.Errorf(c, "[transaction_tags.TagCreateHandler] failed to create tag \"id:%d\" for user \"uid:%d\", because %s", tag.TagId, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_tags.TagCreateHandler] user \"uid:%d\" has created a new tag \"id:%d\" successfully", uid, tag.TagId)
log.Infof(c, "[transaction_tags.TagCreateHandler] user \"uid:%d\" has created a new tag \"id:%d\" successfully", uid, tag.TagId)
tagResp := tag.ToTransactionTagInfoResponse()
@@ -102,12 +102,12 @@ func (a *TransactionTagsApi) TagCreateHandler(c *core.Context) (any, *errs.Error
}
// TagModifyHandler saves an existed transaction tag by request parameters for current user
func (a *TransactionTagsApi) TagModifyHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTagsApi) TagModifyHandler(c *core.WebContext) (any, *errs.Error) {
var tagModifyReq models.TransactionTagModifyRequest
err := c.ShouldBindJSON(&tagModifyReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_tags.TagModifyHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_tags.TagModifyHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -115,7 +115,7 @@ func (a *TransactionTagsApi) TagModifyHandler(c *core.Context) (any, *errs.Error
tag, err := a.tags.GetTagByTagId(c, uid, tagModifyReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_tags.TagModifyHandler] failed to get tag \"id:%d\" for user \"uid:%d\", because %s", tagModifyReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_tags.TagModifyHandler] failed to get tag \"id:%d\" for user \"uid:%d\", because %s", tagModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -132,11 +132,11 @@ func (a *TransactionTagsApi) TagModifyHandler(c *core.Context) (any, *errs.Error
err = a.tags.ModifyTag(c, newTag)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_tags.TagModifyHandler] failed to update tag \"id:%d\" for user \"uid:%d\", because %s", tagModifyReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_tags.TagModifyHandler] failed to update tag \"id:%d\" for user \"uid:%d\", because %s", tagModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_tags.TagModifyHandler] user \"uid:%d\" has updated tag \"id:%d\" successfully", uid, tagModifyReq.Id)
log.Infof(c, "[transaction_tags.TagModifyHandler] user \"uid:%d\" has updated tag \"id:%d\" successfully", uid, tagModifyReq.Id)
tag.Name = newTag.Name
tagResp := tag.ToTransactionTagInfoResponse()
@@ -145,12 +145,12 @@ func (a *TransactionTagsApi) TagModifyHandler(c *core.Context) (any, *errs.Error
}
// TagHideHandler hides an transaction tag by request parameters for current user
func (a *TransactionTagsApi) TagHideHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTagsApi) TagHideHandler(c *core.WebContext) (any, *errs.Error) {
var tagHideReq models.TransactionTagHideRequest
err := c.ShouldBindJSON(&tagHideReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_tags.TagHideHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_tags.TagHideHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -158,21 +158,21 @@ func (a *TransactionTagsApi) TagHideHandler(c *core.Context) (any, *errs.Error)
err = a.tags.HideTag(c, uid, []int64{tagHideReq.Id}, tagHideReq.Hidden)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_tags.TagHideHandler] failed to hide tag \"id:%d\" for user \"uid:%d\", because %s", tagHideReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_tags.TagHideHandler] failed to hide tag \"id:%d\" for user \"uid:%d\", because %s", tagHideReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_tags.TagHideHandler] user \"uid:%d\" has hidden tag \"id:%d\"", uid, tagHideReq.Id)
log.Infof(c, "[transaction_tags.TagHideHandler] user \"uid:%d\" has hidden tag \"id:%d\"", uid, tagHideReq.Id)
return true, nil
}
// TagMoveHandler moves display order of existed transaction tags by request parameters for current user
func (a *TransactionTagsApi) TagMoveHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTagsApi) TagMoveHandler(c *core.WebContext) (any, *errs.Error) {
var tagMoveReq models.TransactionTagMoveRequest
err := c.ShouldBindJSON(&tagMoveReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_tags.TagMoveHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_tags.TagMoveHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -193,21 +193,21 @@ func (a *TransactionTagsApi) TagMoveHandler(c *core.Context) (any, *errs.Error)
err = a.tags.ModifyTagDisplayOrders(c, uid, tags)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_tags.TagMoveHandler] failed to move tags for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transaction_tags.TagMoveHandler] failed to move tags for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_tags.TagMoveHandler] user \"uid:%d\" has moved tags", uid)
log.Infof(c, "[transaction_tags.TagMoveHandler] user \"uid:%d\" has moved tags", uid)
return true, nil
}
// TagDeleteHandler deletes an existed transaction tag by request parameters for current user
func (a *TransactionTagsApi) TagDeleteHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTagsApi) TagDeleteHandler(c *core.WebContext) (any, *errs.Error) {
var tagDeleteReq models.TransactionTagDeleteRequest
err := c.ShouldBindJSON(&tagDeleteReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_tags.TagDeleteHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_tags.TagDeleteHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -215,11 +215,11 @@ func (a *TransactionTagsApi) TagDeleteHandler(c *core.Context) (any, *errs.Error
err = a.tags.DeleteTag(c, uid, tagDeleteReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_tags.TagDeleteHandler] failed to delete tag \"id:%d\" for user \"uid:%d\", because %s", tagDeleteReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_tags.TagDeleteHandler] failed to delete tag \"id:%d\" for user \"uid:%d\", because %s", tagDeleteReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_tags.TagDeleteHandler] user \"uid:%d\" has deleted tag \"id:%d\"", uid, tagDeleteReq.Id)
log.Infof(c, "[transaction_tags.TagDeleteHandler] user \"uid:%d\" has deleted tag \"id:%d\"", uid, tagDeleteReq.Id)
return true, nil
}
+34 -34
View File
@@ -35,17 +35,17 @@ var (
)
// TemplateListHandler returns transaction template list of current user
func (a *TransactionTemplatesApi) TemplateListHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTemplatesApi) TemplateListHandler(c *core.WebContext) (any, *errs.Error) {
var templateListReq models.TransactionTemplateListRequest
err := c.ShouldBindQuery(&templateListReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_templates.TemplateListHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_templates.TemplateListHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
if templateListReq.TemplateType < models.TRANSACTION_TEMPLATE_TYPE_NORMAL || templateListReq.TemplateType > models.TRANSACTION_TEMPLATE_TYPE_NORMAL {
log.WarnfWithRequestId(c, "[transaction_templates.TemplateListHandler] template type invalid, type is %d", templateListReq.TemplateType)
log.Warnf(c, "[transaction_templates.TemplateListHandler] template type invalid, type is %d", templateListReq.TemplateType)
return nil, errs.ErrTransactionTemplateTypeInvalid
}
@@ -53,7 +53,7 @@ func (a *TransactionTemplatesApi) TemplateListHandler(c *core.Context) (any, *er
templates, err := a.templates.GetAllTemplatesByUid(c, uid, templateListReq.TemplateType)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_templates.TemplateListHandler] failed to get templates for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transaction_templates.TemplateListHandler] failed to get templates for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -70,12 +70,12 @@ func (a *TransactionTemplatesApi) TemplateListHandler(c *core.Context) (any, *er
}
// TemplateGetHandler returns one specific transaction template of current user
func (a *TransactionTemplatesApi) TemplateGetHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTemplatesApi) TemplateGetHandler(c *core.WebContext) (any, *errs.Error) {
var templateGetReq models.TransactionTemplateGetRequest
err := c.ShouldBindQuery(&templateGetReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_templates.TemplateGetHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_templates.TemplateGetHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -83,7 +83,7 @@ func (a *TransactionTemplatesApi) TemplateGetHandler(c *core.Context) (any, *err
template, err := a.templates.GetTemplateByTemplateId(c, uid, templateGetReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_templates.TemplateGetHandler] failed to get template \"id:%d\" for user \"uid:%d\", because %s", templateGetReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_templates.TemplateGetHandler] failed to get template \"id:%d\" for user \"uid:%d\", because %s", templateGetReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -94,22 +94,22 @@ func (a *TransactionTemplatesApi) TemplateGetHandler(c *core.Context) (any, *err
}
// TemplateCreateHandler saves a new transaction template by request parameters for current user
func (a *TransactionTemplatesApi) TemplateCreateHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTemplatesApi) TemplateCreateHandler(c *core.WebContext) (any, *errs.Error) {
var templateCreateReq models.TransactionTemplateCreateRequest
err := c.ShouldBindJSON(&templateCreateReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_templates.TemplateCreateHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_templates.TemplateCreateHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
if templateCreateReq.TemplateType < models.TRANSACTION_TEMPLATE_TYPE_NORMAL || templateCreateReq.TemplateType > models.TRANSACTION_TEMPLATE_TYPE_NORMAL {
log.WarnfWithRequestId(c, "[transaction_templates.TemplateCreateHandler] template type invalid, type is %d", templateCreateReq.TemplateType)
log.Warnf(c, "[transaction_templates.TemplateCreateHandler] template type invalid, type is %d", templateCreateReq.TemplateType)
return nil, errs.ErrTransactionTemplateTypeInvalid
}
if templateCreateReq.Type <= models.TRANSACTION_TYPE_MODIFY_BALANCE || templateCreateReq.Type > models.TRANSACTION_TYPE_TRANSFER {
log.WarnfWithRequestId(c, "[transaction_templates.TemplateCreateHandler] transaction type invalid, type is %d", templateCreateReq.Type)
log.Warnf(c, "[transaction_templates.TemplateCreateHandler] transaction type invalid, type is %d", templateCreateReq.Type)
return nil, errs.ErrTransactionTypeInvalid
}
@@ -118,7 +118,7 @@ func (a *TransactionTemplatesApi) TemplateCreateHandler(c *core.Context) (any, *
maxOrderId, err := a.templates.GetMaxDisplayOrder(c, uid, templateCreateReq.TemplateType)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_templates.TemplateCreateHandler] failed to get max display order for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transaction_templates.TemplateCreateHandler] failed to get max display order for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -129,14 +129,14 @@ func (a *TransactionTemplatesApi) TemplateCreateHandler(c *core.Context) (any, *
found, remark := a.GetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_TEMPLATE, uid, templateCreateReq.ClientSessionId)
if found {
log.InfofWithRequestId(c, "[transaction_templates.TemplateCreateHandler] another template \"id:%s\" has been created for user \"uid:%d\"", remark, uid)
log.Infof(c, "[transaction_templates.TemplateCreateHandler] another template \"id:%s\" has been created for user \"uid:%d\"", remark, uid)
templateId, err := utils.StringToInt64(remark)
if err == nil {
template, err = a.templates.GetTemplateByTemplateId(c, uid, templateId)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_templates.TemplateCreateHandler] failed to get existed template \"id:%d\" for user \"uid:%d\", because %s", templateId, uid, err.Error())
log.Errorf(c, "[transaction_templates.TemplateCreateHandler] failed to get existed template \"id:%d\" for user \"uid:%d\", because %s", templateId, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -150,11 +150,11 @@ func (a *TransactionTemplatesApi) TemplateCreateHandler(c *core.Context) (any, *
err = a.templates.CreateTemplate(c, template)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_templates.TemplateCreateHandler] failed to create template \"id:%d\" for user \"uid:%d\", because %s", template.TemplateId, uid, err.Error())
log.Errorf(c, "[transaction_templates.TemplateCreateHandler] failed to create template \"id:%d\" for user \"uid:%d\", because %s", template.TemplateId, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_templates.TemplateCreateHandler] user \"uid:%d\" has created a new template \"id:%d\" successfully", uid, template.TemplateId)
log.Infof(c, "[transaction_templates.TemplateCreateHandler] user \"uid:%d\" has created a new template \"id:%d\" successfully", uid, template.TemplateId)
a.SetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_TEMPLATE, uid, templateCreateReq.ClientSessionId, utils.Int64ToString(template.TemplateId))
templateResp := template.ToTransactionTemplateInfoResponse(serverUtcOffset)
@@ -163,17 +163,17 @@ func (a *TransactionTemplatesApi) TemplateCreateHandler(c *core.Context) (any, *
}
// TemplateModifyHandler saves an existed transaction template by request parameters for current user
func (a *TransactionTemplatesApi) TemplateModifyHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTemplatesApi) TemplateModifyHandler(c *core.WebContext) (any, *errs.Error) {
var templateModifyReq models.TransactionTemplateModifyRequest
err := c.ShouldBindJSON(&templateModifyReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_templates.TemplateModifyHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_templates.TemplateModifyHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
if templateModifyReq.Type <= models.TRANSACTION_TYPE_MODIFY_BALANCE || templateModifyReq.Type > models.TRANSACTION_TYPE_TRANSFER {
log.WarnfWithRequestId(c, "[transaction_templates.TemplateModifyHandler] transaction type invalid, type is %d", templateModifyReq.Type)
log.Warnf(c, "[transaction_templates.TemplateModifyHandler] transaction type invalid, type is %d", templateModifyReq.Type)
return nil, errs.ErrTransactionTypeInvalid
}
@@ -181,7 +181,7 @@ func (a *TransactionTemplatesApi) TemplateModifyHandler(c *core.Context) (any, *
template, err := a.templates.GetTemplateByTemplateId(c, uid, templateModifyReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_templates.TemplateModifyHandler] failed to get template \"id:%d\" for user \"uid:%d\", because %s", templateModifyReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_templates.TemplateModifyHandler] failed to get template \"id:%d\" for user \"uid:%d\", because %s", templateModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -216,11 +216,11 @@ func (a *TransactionTemplatesApi) TemplateModifyHandler(c *core.Context) (any, *
err = a.templates.ModifyTemplate(c, newTemplate)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_templates.TemplateModifyHandler] failed to update template \"id:%d\" for user \"uid:%d\", because %s", templateModifyReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_templates.TemplateModifyHandler] failed to update template \"id:%d\" for user \"uid:%d\", because %s", templateModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_templates.TemplateModifyHandler] user \"uid:%d\" has updated template \"id:%d\" successfully", uid, templateModifyReq.Id)
log.Infof(c, "[transaction_templates.TemplateModifyHandler] user \"uid:%d\" has updated template \"id:%d\" successfully", uid, templateModifyReq.Id)
serverUtcOffset := utils.GetServerTimezoneOffsetMinutes()
newTemplate.TemplateType = template.TemplateType
@@ -232,12 +232,12 @@ func (a *TransactionTemplatesApi) TemplateModifyHandler(c *core.Context) (any, *
}
// TemplateHideHandler hides an transaction template by request parameters for current user
func (a *TransactionTemplatesApi) TemplateHideHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTemplatesApi) TemplateHideHandler(c *core.WebContext) (any, *errs.Error) {
var templateHideReq models.TransactionTemplateHideRequest
err := c.ShouldBindJSON(&templateHideReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_templates.TemplateHideHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_templates.TemplateHideHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -245,21 +245,21 @@ func (a *TransactionTemplatesApi) TemplateHideHandler(c *core.Context) (any, *er
err = a.templates.HideTemplate(c, uid, []int64{templateHideReq.Id}, templateHideReq.Hidden)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_templates.TemplateHideHandler] failed to hide template \"id:%d\" for user \"uid:%d\", because %s", templateHideReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_templates.TemplateHideHandler] failed to hide template \"id:%d\" for user \"uid:%d\", because %s", templateHideReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_templates.TemplateHideHandler] user \"uid:%d\" has hidden template \"id:%d\"", uid, templateHideReq.Id)
log.Infof(c, "[transaction_templates.TemplateHideHandler] user \"uid:%d\" has hidden template \"id:%d\"", uid, templateHideReq.Id)
return true, nil
}
// TemplateMoveHandler moves display order of existed transaction templates by request parameters for current user
func (a *TransactionTemplatesApi) TemplateMoveHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTemplatesApi) TemplateMoveHandler(c *core.WebContext) (any, *errs.Error) {
var templateMoveReq models.TransactionTemplateMoveRequest
err := c.ShouldBindJSON(&templateMoveReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_templates.CategoryMoveHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_templates.TemplateMoveHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -280,21 +280,21 @@ func (a *TransactionTemplatesApi) TemplateMoveHandler(c *core.Context) (any, *er
err = a.templates.ModifyTemplateDisplayOrders(c, uid, templates)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_templates.TemplateMoveHandler] failed to move templates for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transaction_templates.TemplateMoveHandler] failed to move templates for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_templates.TemplateMoveHandler] user \"uid:%d\" has moved templates", uid)
log.Infof(c, "[transaction_templates.TemplateMoveHandler] user \"uid:%d\" has moved templates", uid)
return true, nil
}
// TemplateDeleteHandler deletes an existed transaction template by request parameters for current user
func (a *TransactionTemplatesApi) TemplateDeleteHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionTemplatesApi) TemplateDeleteHandler(c *core.WebContext) (any, *errs.Error) {
var templateDeleteReq models.TransactionTemplateDeleteRequest
err := c.ShouldBindJSON(&templateDeleteReq)
if err != nil {
log.WarnfWithRequestId(c, "[transaction_templates.TemplateDeleteHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transaction_templates.TemplateDeleteHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -302,11 +302,11 @@ func (a *TransactionTemplatesApi) TemplateDeleteHandler(c *core.Context) (any, *
err = a.templates.DeleteTemplate(c, uid, templateDeleteReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transaction_templates.TemplateDeleteHandler] failed to delete template \"id:%d\" for user \"uid:%d\", because %s", templateDeleteReq.Id, uid, err.Error())
log.Errorf(c, "[transaction_templates.TemplateDeleteHandler] failed to delete template \"id:%d\" for user \"uid:%d\", because %s", templateDeleteReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transaction_templates.TemplateDeleteHandler] user \"uid:%d\" has deleted template \"id:%d\"", uid, templateDeleteReq.Id)
log.Infof(c, "[transaction_templates.TemplateDeleteHandler] user \"uid:%d\" has deleted template \"id:%d\"", uid, templateDeleteReq.Id)
return true, nil
}
+94 -94
View File
@@ -45,12 +45,12 @@ var (
)
// TransactionCountHandler returns transaction total count of current user
func (a *TransactionsApi) TransactionCountHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionsApi) TransactionCountHandler(c *core.WebContext) (any, *errs.Error) {
var transactionCountReq models.TransactionCountRequest
err := c.ShouldBindQuery(&transactionCountReq)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionCountHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionCountHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -59,14 +59,14 @@ func (a *TransactionsApi) TransactionCountHandler(c *core.Context) (any, *errs.E
allAccountIds, err := a.getAccountOrSubAccountIds(c, transactionCountReq.AccountIds, uid)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionCountHandler] get account error, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionCountHandler] get account error, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
allCategoryIds, err := a.getCategoryOrSubCategoryIds(c, transactionCountReq.CategoryIds, uid)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionCountHandler] get transaction category error, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionCountHandler] get transaction category error, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -77,7 +77,7 @@ func (a *TransactionsApi) TransactionCountHandler(c *core.Context) (any, *errs.E
allTagIds, err = a.getTagIds(transactionCountReq.TagIds)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionCountHandler] get transaction tag ids error, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionCountHandler] get transaction tag ids error, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
}
@@ -85,7 +85,7 @@ func (a *TransactionsApi) TransactionCountHandler(c *core.Context) (any, *errs.E
totalCount, err := a.transactions.GetTransactionCount(c, uid, transactionCountReq.MaxTime, transactionCountReq.MinTime, transactionCountReq.Type, allCategoryIds, allAccountIds, allTagIds, noTags, transactionCountReq.AmountFilter, transactionCountReq.Keyword)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionCountHandler] failed to get transaction count for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionCountHandler] failed to get transaction count for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -97,19 +97,19 @@ func (a *TransactionsApi) TransactionCountHandler(c *core.Context) (any, *errs.E
}
// TransactionListHandler returns transaction list of current user
func (a *TransactionsApi) TransactionListHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionsApi) TransactionListHandler(c *core.WebContext) (any, *errs.Error) {
var transactionListReq models.TransactionListByMaxTimeRequest
err := c.ShouldBindQuery(&transactionListReq)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionListHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionListHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
utcOffset, err := c.GetClientTimezoneOffset()
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionListHandler] cannot get client timezone offset, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionListHandler] cannot get client timezone offset, because %s", err.Error())
return nil, errs.ErrClientTimezoneOffsetInvalid
}
@@ -118,7 +118,7 @@ func (a *TransactionsApi) TransactionListHandler(c *core.Context) (any, *errs.Er
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[transactions.TransactionListHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[transactions.TransactionListHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -127,14 +127,14 @@ func (a *TransactionsApi) TransactionListHandler(c *core.Context) (any, *errs.Er
allAccountIds, err := a.getAccountOrSubAccountIds(c, transactionListReq.AccountIds, uid)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionListHandler] get account error, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionListHandler] get account error, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
allCategoryIds, err := a.getCategoryOrSubCategoryIds(c, transactionListReq.CategoryIds, uid)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionListHandler] get transaction category error, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionListHandler] get transaction category error, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -145,7 +145,7 @@ func (a *TransactionsApi) TransactionListHandler(c *core.Context) (any, *errs.Er
allTagIds, err = a.getTagIds(transactionListReq.TagIds)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionListHandler] get transaction tag ids error, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionListHandler] get transaction tag ids error, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
}
@@ -156,7 +156,7 @@ func (a *TransactionsApi) TransactionListHandler(c *core.Context) (any, *errs.Er
totalCount, err = a.transactions.GetTransactionCount(c, uid, transactionListReq.MaxTime, transactionListReq.MinTime, transactionListReq.Type, allCategoryIds, allAccountIds, allTagIds, noTags, transactionListReq.AmountFilter, transactionListReq.Keyword)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionListHandler] failed to get transaction count for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionListHandler] failed to get transaction count for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
}
@@ -164,7 +164,7 @@ func (a *TransactionsApi) TransactionListHandler(c *core.Context) (any, *errs.Er
transactions, err := a.transactions.GetTransactionsByMaxTime(c, uid, transactionListReq.MaxTime, transactionListReq.MinTime, transactionListReq.Type, allCategoryIds, allAccountIds, allTagIds, noTags, transactionListReq.AmountFilter, transactionListReq.Keyword, transactionListReq.Page, transactionListReq.Count, true, true)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionListHandler] failed to get transactions earlier than \"%d\" for user \"uid:%d\", because %s", transactionListReq.MaxTime, uid, err.Error())
log.Errorf(c, "[transactions.TransactionListHandler] failed to get transactions earlier than \"%d\" for user \"uid:%d\", because %s", transactionListReq.MaxTime, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -180,7 +180,7 @@ func (a *TransactionsApi) TransactionListHandler(c *core.Context) (any, *errs.Er
transactionResult, err := a.getTransactionListResult(c, user, transactions, utcOffset, transactionListReq.TrimAccount, transactionListReq.TrimCategory, transactionListReq.TrimTag)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionListHandler] failed to assemble transaction result for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionListHandler] failed to assemble transaction result for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -200,19 +200,19 @@ func (a *TransactionsApi) TransactionListHandler(c *core.Context) (any, *errs.Er
}
// TransactionMonthListHandler returns all transaction list of current user by month
func (a *TransactionsApi) TransactionMonthListHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionsApi) TransactionMonthListHandler(c *core.WebContext) (any, *errs.Error) {
var transactionListReq models.TransactionListInMonthByPageRequest
err := c.ShouldBindQuery(&transactionListReq)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionMonthListHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionMonthListHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
utcOffset, err := c.GetClientTimezoneOffset()
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionMonthListHandler] cannot get client timezone offset, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionMonthListHandler] cannot get client timezone offset, because %s", err.Error())
return nil, errs.ErrClientTimezoneOffsetInvalid
}
@@ -221,7 +221,7 @@ func (a *TransactionsApi) TransactionMonthListHandler(c *core.Context) (any, *er
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[transactions.TransactionMonthListHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[transactions.TransactionMonthListHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -230,14 +230,14 @@ func (a *TransactionsApi) TransactionMonthListHandler(c *core.Context) (any, *er
allAccountIds, err := a.getAccountOrSubAccountIds(c, transactionListReq.AccountIds, uid)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionMonthListHandler] get account error, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionMonthListHandler] get account error, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
allCategoryIds, err := a.getCategoryOrSubCategoryIds(c, transactionListReq.CategoryIds, uid)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionMonthListHandler] get transaction category error, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionMonthListHandler] get transaction category error, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -248,7 +248,7 @@ func (a *TransactionsApi) TransactionMonthListHandler(c *core.Context) (any, *er
allTagIds, err = a.getTagIds(transactionListReq.TagIds)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionMonthListHandler] get transaction tag ids error, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionMonthListHandler] get transaction tag ids error, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
}
@@ -256,14 +256,14 @@ func (a *TransactionsApi) TransactionMonthListHandler(c *core.Context) (any, *er
transactions, err := a.transactions.GetTransactionsInMonthByPage(c, uid, transactionListReq.Year, transactionListReq.Month, transactionListReq.Type, allCategoryIds, allAccountIds, allTagIds, noTags, transactionListReq.AmountFilter, transactionListReq.Keyword)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionMonthListHandler] failed to get transactions in month \"%d-%d\" for user \"uid:%d\", because %s", transactionListReq.Year, transactionListReq.Month, uid, err.Error())
log.Errorf(c, "[transactions.TransactionMonthListHandler] failed to get transactions in month \"%d-%d\" for user \"uid:%d\", because %s", transactionListReq.Year, transactionListReq.Month, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
transactionResult, err := a.getTransactionListResult(c, user, transactions, utcOffset, transactionListReq.TrimAccount, transactionListReq.TrimCategory, transactionListReq.TrimTag)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionMonthListHandler] failed to assemble transaction result for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionMonthListHandler] failed to assemble transaction result for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -276,19 +276,19 @@ func (a *TransactionsApi) TransactionMonthListHandler(c *core.Context) (any, *er
}
// TransactionStatisticsHandler returns transaction statistics of current user
func (a *TransactionsApi) TransactionStatisticsHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionsApi) TransactionStatisticsHandler(c *core.WebContext) (any, *errs.Error) {
var statisticReq models.TransactionStatisticRequest
err := c.ShouldBindQuery(&statisticReq)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionStatisticsHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionStatisticsHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
utcOffset, err := c.GetClientTimezoneOffset()
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionStatisticsHandler] cannot get client timezone offset, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionStatisticsHandler] cannot get client timezone offset, because %s", err.Error())
return nil, errs.ErrClientTimezoneOffsetInvalid
}
@@ -296,7 +296,7 @@ func (a *TransactionsApi) TransactionStatisticsHandler(c *core.Context) (any, *e
totalAmounts, err := a.transactions.GetAccountsAndCategoriesTotalIncomeAndExpense(c, uid, statisticReq.StartTime, statisticReq.EndTime, utcOffset, statisticReq.UseTransactionTimezone)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionStatisticsHandler] failed to get accounts and categories total income and expense for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionStatisticsHandler] failed to get accounts and categories total income and expense for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -320,26 +320,26 @@ func (a *TransactionsApi) TransactionStatisticsHandler(c *core.Context) (any, *e
}
// TransactionStatisticsTrendsHandler returns transaction statistics trends of current user
func (a *TransactionsApi) TransactionStatisticsTrendsHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionsApi) TransactionStatisticsTrendsHandler(c *core.WebContext) (any, *errs.Error) {
var statisticTrendsReq models.TransactionStatisticTrendsRequest
err := c.ShouldBindQuery(&statisticTrendsReq)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionStatisticsTrendsHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionStatisticsTrendsHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
utcOffset, err := c.GetClientTimezoneOffset()
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionStatisticsTrendsHandler] cannot get client timezone offset, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionStatisticsTrendsHandler] cannot get client timezone offset, because %s", err.Error())
return nil, errs.ErrClientTimezoneOffsetInvalid
}
startYear, startMonth, endYear, endMonth, err := statisticTrendsReq.GetNumericYearMonthRange()
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionStatisticsTrendsHandler] cannot parse year month, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionStatisticsTrendsHandler] cannot parse year month, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -347,7 +347,7 @@ func (a *TransactionsApi) TransactionStatisticsTrendsHandler(c *core.Context) (a
allMonthlyTotalAmounts, err := a.transactions.GetAccountsAndCategoriesMonthlyIncomeAndExpense(c, uid, startYear, startMonth, endYear, endMonth, utcOffset, statisticTrendsReq.UseTransactionTimezone)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionStatisticsTrendsHandler] failed to get accounts and categories total income and expense for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionStatisticsTrendsHandler] failed to get accounts and categories total income and expense for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -378,36 +378,36 @@ func (a *TransactionsApi) TransactionStatisticsTrendsHandler(c *core.Context) (a
}
// TransactionAmountsHandler returns transaction amounts of current user
func (a *TransactionsApi) TransactionAmountsHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionsApi) TransactionAmountsHandler(c *core.WebContext) (any, *errs.Error) {
var transactionAmountsReq models.TransactionAmountsRequest
err := c.ShouldBindQuery(&transactionAmountsReq)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionAmountsHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionAmountsHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
requestItems, err := transactionAmountsReq.GetTransactionAmountsRequestItems()
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionAmountsHandler] get request item failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionAmountsHandler] get request item failed, because %s", err.Error())
return nil, errs.ErrQueryItemsInvalid
}
if len(requestItems) < 1 {
log.WarnfWithRequestId(c, "[transactions.TransactionAmountsHandler] parse request failed, because there are no valid items")
log.Warnf(c, "[transactions.TransactionAmountsHandler] parse request failed, because there are no valid items")
return nil, errs.ErrQueryItemsEmpty
}
if len(requestItems) > 20 {
log.WarnfWithRequestId(c, "[transactions.TransactionAmountsHandler] parse request failed, because there are too many items")
log.Warnf(c, "[transactions.TransactionAmountsHandler] parse request failed, because there are too many items")
return nil, errs.ErrQueryItemsTooMuch
}
utcOffset, err := c.GetClientTimezoneOffset()
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionAmountsHandler] cannot get client timezone offset, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionAmountsHandler] cannot get client timezone offset, because %s", err.Error())
return nil, errs.ErrClientTimezoneOffsetInvalid
}
@@ -417,7 +417,7 @@ func (a *TransactionsApi) TransactionAmountsHandler(c *core.Context) (any, *errs
accountMap := a.accounts.GetAccountMapByList(accounts)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionAmountsHandler] failed to get all accounts for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionAmountsHandler] failed to get all accounts for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -429,7 +429,7 @@ func (a *TransactionsApi) TransactionAmountsHandler(c *core.Context) (any, *errs
incomeAmounts, expenseAmounts, err := a.transactions.GetAccountsTotalIncomeAndExpense(c, uid, requestItem.StartTime, requestItem.EndTime, utcOffset, transactionAmountsReq.UseTransactionTimezone)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionAmountsHandler] failed to get transaction amounts item for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionAmountsHandler] failed to get transaction amounts item for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -439,7 +439,7 @@ func (a *TransactionsApi) TransactionAmountsHandler(c *core.Context) (any, *errs
account, exists := accountMap[accountId]
if !exists {
log.WarnfWithRequestId(c, "[transactions.TransactionAmountsHandler] cannot find account for account \"id:%d\" of user \"uid:%d\"", accountId, uid)
log.Warnf(c, "[transactions.TransactionAmountsHandler] cannot find account for account \"id:%d\" of user \"uid:%d\"", accountId, uid)
continue
}
@@ -461,7 +461,7 @@ func (a *TransactionsApi) TransactionAmountsHandler(c *core.Context) (any, *errs
account, exists := accountMap[accountId]
if !exists {
log.WarnfWithRequestId(c, "[transactions.TransactionAmountsHandler] cannot find account for account \"id:%d\" of user \"uid:%d\"", accountId, uid)
log.Warnf(c, "[transactions.TransactionAmountsHandler] cannot find account for account \"id:%d\" of user \"uid:%d\"", accountId, uid)
continue
}
@@ -498,19 +498,19 @@ func (a *TransactionsApi) TransactionAmountsHandler(c *core.Context) (any, *errs
}
// TransactionGetHandler returns one specific transaction of current user
func (a *TransactionsApi) TransactionGetHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionsApi) TransactionGetHandler(c *core.WebContext) (any, *errs.Error) {
var transactionGetReq models.TransactionGetRequest
err := c.ShouldBindQuery(&transactionGetReq)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionGetHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionGetHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
utcOffset, err := c.GetClientTimezoneOffset()
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionGetHandler] cannot get client timezone offset, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionGetHandler] cannot get client timezone offset, because %s", err.Error())
return nil, errs.ErrClientTimezoneOffsetInvalid
}
@@ -519,7 +519,7 @@ func (a *TransactionsApi) TransactionGetHandler(c *core.Context) (any, *errs.Err
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[transactions.TransactionGetHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[transactions.TransactionGetHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -528,7 +528,7 @@ func (a *TransactionsApi) TransactionGetHandler(c *core.Context) (any, *errs.Err
transaction, err := a.transactions.GetTransactionByTransactionId(c, uid, transactionGetReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionGetHandler] failed to get transaction \"id:%d\" for user \"uid:%d\", because %s", transactionGetReq.Id, uid, err.Error())
log.Errorf(c, "[transactions.TransactionGetHandler] failed to get transaction \"id:%d\" for user \"uid:%d\", because %s", transactionGetReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -547,13 +547,13 @@ func (a *TransactionsApi) TransactionGetHandler(c *core.Context) (any, *errs.Err
accountMap, err := a.accounts.GetAccountsByAccountIds(c, uid, accountIds)
if _, exists := accountMap[transaction.AccountId]; !exists {
log.WarnfWithRequestId(c, "[transactions.TransactionGetHandler] account of transaction \"id:%d\" does not exist for user \"uid:%d\"", transaction.TransactionId, uid)
log.Warnf(c, "[transactions.TransactionGetHandler] account of transaction \"id:%d\" does not exist for user \"uid:%d\"", transaction.TransactionId, uid)
return nil, errs.ErrTransactionNotFound
}
if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_OUT {
if _, exists := accountMap[transaction.RelatedAccountId]; !exists {
log.WarnfWithRequestId(c, "[transactions.TransactionGetHandler] related account of transaction \"id:%d\" does not exist for user \"uid:%d\"", transaction.TransactionId, uid)
log.Warnf(c, "[transactions.TransactionGetHandler] related account of transaction \"id:%d\" does not exist for user \"uid:%d\"", transaction.TransactionId, uid)
return nil, errs.ErrTransactionNotFound
}
}
@@ -561,7 +561,7 @@ func (a *TransactionsApi) TransactionGetHandler(c *core.Context) (any, *errs.Err
allTransactionTagIds, err := a.transactionTags.GetAllTagIdsOfTransactions(c, uid, []int64{transaction.TransactionId})
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionGetHandler] failed to get transactions tag ids for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionGetHandler] failed to get transactions tag ids for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -572,7 +572,7 @@ func (a *TransactionsApi) TransactionGetHandler(c *core.Context) (any, *errs.Err
category, err = a.transactionCategories.GetCategoryByCategoryId(c, uid, transaction.CategoryId)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionGetHandler] failed to get transactions category for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionGetHandler] failed to get transactions category for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
}
@@ -581,7 +581,7 @@ func (a *TransactionsApi) TransactionGetHandler(c *core.Context) (any, *errs.Err
tagMap, err = a.transactionTags.GetTagsByTagIds(c, uid, utils.ToUniqueInt64Slice(a.getTransactionTagIds(allTransactionTagIds)))
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionGetHandler] failed to get transactions tags for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionGetHandler] failed to get transactions tags for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
}
@@ -614,42 +614,42 @@ func (a *TransactionsApi) TransactionGetHandler(c *core.Context) (any, *errs.Err
}
// TransactionCreateHandler saves a new transaction by request parameters for current user
func (a *TransactionsApi) TransactionCreateHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionsApi) TransactionCreateHandler(c *core.WebContext) (any, *errs.Error) {
var transactionCreateReq models.TransactionCreateRequest
err := c.ShouldBindJSON(&transactionCreateReq)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionCreateHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionCreateHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
tagIds, err := utils.StringArrayToInt64Array(transactionCreateReq.TagIds)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionCreateHandler] parse tag ids failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionCreateHandler] parse tag ids failed, because %s", err.Error())
return nil, errs.ErrTransactionTagIdInvalid
}
if transactionCreateReq.Type < models.TRANSACTION_TYPE_MODIFY_BALANCE || transactionCreateReq.Type > models.TRANSACTION_TYPE_TRANSFER {
log.WarnfWithRequestId(c, "[transactions.TransactionCreateHandler] transaction type is invalid")
log.Warnf(c, "[transactions.TransactionCreateHandler] transaction type is invalid")
return nil, errs.ErrTransactionTypeInvalid
}
if transactionCreateReq.Type == models.TRANSACTION_TYPE_MODIFY_BALANCE && transactionCreateReq.CategoryId > 0 {
log.WarnfWithRequestId(c, "[transactions.TransactionCreateHandler] balance modification transaction cannot set category id")
log.Warnf(c, "[transactions.TransactionCreateHandler] balance modification transaction cannot set category id")
return nil, errs.ErrBalanceModificationTransactionCannotSetCategory
}
if transactionCreateReq.Type != models.TRANSACTION_TYPE_TRANSFER && transactionCreateReq.DestinationAccountId != 0 {
log.WarnfWithRequestId(c, "[transactions.TransactionCreateHandler] non-transfer transaction destination account cannot be set")
log.Warnf(c, "[transactions.TransactionCreateHandler] non-transfer transaction destination account cannot be set")
return nil, errs.ErrTransactionDestinationAccountCannotBeSet
} else if transactionCreateReq.Type == models.TRANSACTION_TYPE_TRANSFER && transactionCreateReq.SourceAccountId == transactionCreateReq.DestinationAccountId {
log.WarnfWithRequestId(c, "[transactions.TransactionCreateHandler] transfer transaction source account must not be destination account")
log.Warnf(c, "[transactions.TransactionCreateHandler] transfer transaction source account must not be destination account")
return nil, errs.ErrTransactionSourceAndDestinationIdCannotBeEqual
}
if transactionCreateReq.Type != models.TRANSACTION_TYPE_TRANSFER && transactionCreateReq.DestinationAmount != 0 {
log.WarnfWithRequestId(c, "[transactions.TransactionCreateHandler] non-transfer transaction destination amount cannot be set")
log.Warnf(c, "[transactions.TransactionCreateHandler] non-transfer transaction destination amount cannot be set")
return nil, errs.ErrTransactionDestinationAmountCannotBeSet
}
@@ -658,7 +658,7 @@ func (a *TransactionsApi) TransactionCreateHandler(c *core.Context) (any, *errs.
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[transactions.TransactionCreateHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[transactions.TransactionCreateHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -675,14 +675,14 @@ func (a *TransactionsApi) TransactionCreateHandler(c *core.Context) (any, *errs.
found, remark := a.GetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_TRANSACTION, uid, transactionCreateReq.ClientSessionId)
if found {
log.InfofWithRequestId(c, "[transactions.TransactionCreateHandler] another transaction \"id:%s\" has been created for user \"uid:%d\"", remark, uid)
log.Infof(c, "[transactions.TransactionCreateHandler] another transaction \"id:%s\" has been created for user \"uid:%d\"", remark, uid)
transactionId, err := utils.StringToInt64(remark)
if err == nil {
transaction, err = a.transactions.GetTransactionByTransactionId(c, uid, transactionId)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionCreateHandler] failed to get existed transaction \"id:%d\" for user \"uid:%d\", because %s", transactionId, uid, err.Error())
log.Errorf(c, "[transactions.TransactionCreateHandler] failed to get existed transaction \"id:%d\" for user \"uid:%d\", because %s", transactionId, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -696,11 +696,11 @@ func (a *TransactionsApi) TransactionCreateHandler(c *core.Context) (any, *errs.
err = a.transactions.CreateTransaction(c, transaction, tagIds)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionCreateHandler] failed to create transaction \"id:%d\" for user \"uid:%d\", because %s", transaction.TransactionId, uid, err.Error())
log.Errorf(c, "[transactions.TransactionCreateHandler] failed to create transaction \"id:%d\" for user \"uid:%d\", because %s", transaction.TransactionId, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transactions.TransactionCreateHandler] user \"uid:%d\" has created a new transaction \"id:%d\" successfully", uid, transaction.TransactionId)
log.Infof(c, "[transactions.TransactionCreateHandler] user \"uid:%d\" has created a new transaction \"id:%d\" successfully", uid, transaction.TransactionId)
a.SetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_TRANSACTION, uid, transactionCreateReq.ClientSessionId, utils.Int64ToString(transaction.TransactionId))
transactionResp := transaction.ToTransactionInfoResponse(tagIds, transactionEditable)
@@ -709,19 +709,19 @@ func (a *TransactionsApi) TransactionCreateHandler(c *core.Context) (any, *errs.
}
// TransactionModifyHandler saves an existed transaction by request parameters for current user
func (a *TransactionsApi) TransactionModifyHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionsApi) TransactionModifyHandler(c *core.WebContext) (any, *errs.Error) {
var transactionModifyReq models.TransactionModifyRequest
err := c.ShouldBindJSON(&transactionModifyReq)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionModifyHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionModifyHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
tagIds, err := utils.StringArrayToInt64Array(transactionModifyReq.TagIds)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionModifyHandler] parse tag ids failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionModifyHandler] parse tag ids failed, because %s", err.Error())
return nil, errs.ErrTransactionTagIdInvalid
}
@@ -730,7 +730,7 @@ func (a *TransactionsApi) TransactionModifyHandler(c *core.Context) (any, *errs.
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[transactions.TransactionModifyHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[transactions.TransactionModifyHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -739,19 +739,19 @@ func (a *TransactionsApi) TransactionModifyHandler(c *core.Context) (any, *errs.
transaction, err := a.transactions.GetTransactionByTransactionId(c, uid, transactionModifyReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionModifyHandler] failed to get transaction \"id:%d\" for user \"uid:%d\", because %s", transactionModifyReq.Id, uid, err.Error())
log.Errorf(c, "[transactions.TransactionModifyHandler] failed to get transaction \"id:%d\" for user \"uid:%d\", because %s", transactionModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_IN {
log.WarnfWithRequestId(c, "[transactions.TransactionModifyHandler] cannot modify transaction \"id:%d\" for user \"uid:%d\", because transaction type is transfer in", transactionModifyReq.Id, uid)
log.Warnf(c, "[transactions.TransactionModifyHandler] cannot modify transaction \"id:%d\" for user \"uid:%d\", because transaction type is transfer in", transactionModifyReq.Id, uid)
return nil, errs.ErrTransactionTypeInvalid
}
allTransactionTagIds, err := a.transactionTags.GetAllTagIdsOfTransactions(c, uid, []int64{transaction.TransactionId})
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionModifyHandler] failed to get transactions tag ids for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.TransactionModifyHandler] failed to get transactions tag ids for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -816,11 +816,11 @@ func (a *TransactionsApi) TransactionModifyHandler(c *core.Context) (any, *errs.
err = a.transactions.ModifyTransaction(c, newTransaction, len(transactionTagIds), addTransactionTagIds, removeTransactionTagIds)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionModifyHandler] failed to update transaction \"id:%d\" for user \"uid:%d\", because %s", transactionModifyReq.Id, uid, err.Error())
log.Errorf(c, "[transactions.TransactionModifyHandler] failed to update transaction \"id:%d\" for user \"uid:%d\", because %s", transactionModifyReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transactions.TransactionModifyHandler] user \"uid:%d\" has updated transaction \"id:%d\" successfully", uid, transactionModifyReq.Id)
log.Infof(c, "[transactions.TransactionModifyHandler] user \"uid:%d\" has updated transaction \"id:%d\" successfully", uid, transactionModifyReq.Id)
newTransaction.Type = transaction.Type
newTransactionResp := newTransaction.ToTransactionInfoResponse(tagIds, transactionEditable)
@@ -829,19 +829,19 @@ func (a *TransactionsApi) TransactionModifyHandler(c *core.Context) (any, *errs.
}
// TransactionDeleteHandler deletes an existed transaction by request parameters for current user
func (a *TransactionsApi) TransactionDeleteHandler(c *core.Context) (any, *errs.Error) {
func (a *TransactionsApi) TransactionDeleteHandler(c *core.WebContext) (any, *errs.Error) {
var transactionDeleteReq models.TransactionDeleteRequest
err := c.ShouldBindJSON(&transactionDeleteReq)
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionDeleteHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionDeleteHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
utcOffset, err := c.GetClientTimezoneOffset()
if err != nil {
log.WarnfWithRequestId(c, "[transactions.TransactionDeleteHandler] cannot get client timezone offset, because %s", err.Error())
log.Warnf(c, "[transactions.TransactionDeleteHandler] cannot get client timezone offset, because %s", err.Error())
return nil, errs.ErrClientTimezoneOffsetInvalid
}
@@ -850,7 +850,7 @@ func (a *TransactionsApi) TransactionDeleteHandler(c *core.Context) (any, *errs.
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[transactions.TransactionDeleteHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[transactions.TransactionDeleteHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -859,12 +859,12 @@ func (a *TransactionsApi) TransactionDeleteHandler(c *core.Context) (any, *errs.
transaction, err := a.transactions.GetTransactionByTransactionId(c, uid, transactionDeleteReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionDeleteHandler] failed to get transaction \"id:%d\" for user \"uid:%d\", because %s", transactionDeleteReq.Id, uid, err.Error())
log.Errorf(c, "[transactions.TransactionDeleteHandler] failed to get transaction \"id:%d\" for user \"uid:%d\", because %s", transactionDeleteReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_IN {
log.WarnfWithRequestId(c, "[transactions.TransactionDeleteHandler] cannot delete transaction \"id:%d\" for user \"uid:%d\", because transaction type is transfer in", transactionDeleteReq.Id, uid)
log.Warnf(c, "[transactions.TransactionDeleteHandler] cannot delete transaction \"id:%d\" for user \"uid:%d\", because transaction type is transfer in", transactionDeleteReq.Id, uid)
return nil, errs.ErrTransactionTypeInvalid
}
@@ -877,28 +877,28 @@ func (a *TransactionsApi) TransactionDeleteHandler(c *core.Context) (any, *errs.
err = a.transactions.DeleteTransaction(c, uid, transactionDeleteReq.Id)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionDeleteHandler] failed to delete transaction \"id:%d\" for user \"uid:%d\", because %s", transactionDeleteReq.Id, uid, err.Error())
log.Errorf(c, "[transactions.TransactionDeleteHandler] failed to delete transaction \"id:%d\" for user \"uid:%d\", because %s", transactionDeleteReq.Id, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[transactions.TransactionDeleteHandler] user \"uid:%d\" has deleted transaction \"id:%d\"", uid, transactionDeleteReq.Id)
log.Infof(c, "[transactions.TransactionDeleteHandler] user \"uid:%d\" has deleted transaction \"id:%d\"", uid, transactionDeleteReq.Id)
return true, nil
}
func (a *TransactionsApi) filterTransactions(c *core.Context, uid int64, transactions []*models.Transaction, accountMap map[int64]*models.Account) []*models.Transaction {
func (a *TransactionsApi) filterTransactions(c *core.WebContext, uid int64, transactions []*models.Transaction, accountMap map[int64]*models.Account) []*models.Transaction {
finalTransactions := make([]*models.Transaction, 0, len(transactions))
for i := 0; i < len(transactions); i++ {
transaction := transactions[i]
if _, exists := accountMap[transaction.AccountId]; !exists {
log.WarnfWithRequestId(c, "[transactions.filterTransactions] account of transaction \"id:%d\" does not exist for user \"uid:%d\"", transaction.TransactionId, uid)
log.Warnf(c, "[transactions.filterTransactions] account of transaction \"id:%d\" does not exist for user \"uid:%d\"", transaction.TransactionId, uid)
continue
}
if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_IN || transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_OUT {
if _, exists := accountMap[transaction.RelatedAccountId]; !exists {
log.WarnfWithRequestId(c, "[transactions.filterTransactions] related account of transaction \"id:%d\" does not exist for user \"uid:%d\"", transaction.TransactionId, uid)
log.Warnf(c, "[transactions.filterTransactions] related account of transaction \"id:%d\" does not exist for user \"uid:%d\"", transaction.TransactionId, uid)
continue
}
}
@@ -909,7 +909,7 @@ func (a *TransactionsApi) filterTransactions(c *core.Context, uid int64, transac
return finalTransactions
}
func (a *TransactionsApi) getAccountOrSubAccountIds(c *core.Context, accountIds string, uid int64) ([]int64, error) {
func (a *TransactionsApi) getAccountOrSubAccountIds(c *core.WebContext, accountIds string, uid int64) ([]int64, error) {
if accountIds == "" || accountIds == "0" {
return nil, nil
}
@@ -961,7 +961,7 @@ func (a *TransactionsApi) getAccountOrSubAccountIds(c *core.Context, accountIds
return allAccountIds, nil
}
func (a *TransactionsApi) getCategoryOrSubCategoryIds(c *core.Context, categoryIds string, uid int64) ([]int64, error) {
func (a *TransactionsApi) getCategoryOrSubCategoryIds(c *core.WebContext, categoryIds string, uid int64) ([]int64, error) {
if categoryIds == "" || categoryIds == "0" {
return nil, nil
}
@@ -1053,7 +1053,7 @@ func (a *TransactionsApi) getTransactionTagInfoResponses(tagIds []int64, allTran
return allTags
}
func (a *TransactionsApi) getTransactionListResult(c *core.Context, user *models.User, transactions []*models.Transaction, utcOffset int16, trimAccount bool, trimCategory bool, trimTag bool) (models.TransactionInfoResponseSlice, error) {
func (a *TransactionsApi) getTransactionListResult(c *core.WebContext, user *models.User, transactions []*models.Transaction, utcOffset int16, trimAccount bool, trimCategory bool, trimTag bool) (models.TransactionInfoResponseSlice, error) {
uid := user.Uid
transactionIds := make([]int64, len(transactions))
accountIds := make([]int64, 0, len(transactions)*2)
@@ -1079,7 +1079,7 @@ func (a *TransactionsApi) getTransactionListResult(c *core.Context, user *models
allAccounts, err := a.accounts.GetAccountsByAccountIds(c, uid, utils.ToUniqueInt64Slice(accountIds))
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.getTransactionListResult] failed to get accounts for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.getTransactionListResult] failed to get accounts for user \"uid:%d\", because %s", uid, err.Error())
return nil, err
}
@@ -1088,7 +1088,7 @@ func (a *TransactionsApi) getTransactionListResult(c *core.Context, user *models
allTransactionTagIds, err := a.transactionTags.GetAllTagIdsOfTransactions(c, uid, transactionIds)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.getTransactionListResult] failed to get transactions tag ids for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.getTransactionListResult] failed to get transactions tag ids for user \"uid:%d\", because %s", uid, err.Error())
return nil, err
}
@@ -1099,7 +1099,7 @@ func (a *TransactionsApi) getTransactionListResult(c *core.Context, user *models
categoryMap, err = a.transactionCategories.GetCategoriesByCategoryIds(c, uid, utils.ToUniqueInt64Slice(categoryIds))
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.getTransactionListResult] failed to get transactions categories for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.getTransactionListResult] failed to get transactions categories for user \"uid:%d\", because %s", uid, err.Error())
return nil, err
}
}
@@ -1108,7 +1108,7 @@ func (a *TransactionsApi) getTransactionListResult(c *core.Context, user *models
tagMap, err = a.transactionTags.GetTagsByTagIds(c, uid, utils.ToUniqueInt64Slice(a.getTransactionTagIds(allTransactionTagIds)))
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.getTransactionListResult] failed to get transactions tags for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[transactions.getTransactionListResult] failed to get transactions tags for user \"uid:%d\", because %s", uid, err.Error())
return nil, err
}
}
+34 -34
View File
@@ -32,7 +32,7 @@ var (
)
// TwoFactorStatusHandler returns 2fa status of current user
func (a *TwoFactorAuthorizationsApi) TwoFactorStatusHandler(c *core.Context) (any, *errs.Error) {
func (a *TwoFactorAuthorizationsApi) TwoFactorStatusHandler(c *core.WebContext) (any, *errs.Error) {
uid := c.GetCurrentUid()
twoFactorSetting, err := a.twoFactorAuthorizations.GetUserTwoFactorSettingByUid(c, uid)
@@ -45,7 +45,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorStatusHandler(c *core.Context) (an
}
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorStatusHandler] failed to get two-factor setting, because %s", err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorStatusHandler] failed to get two-factor setting, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -58,12 +58,12 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorStatusHandler(c *core.Context) (an
}
// TwoFactorEnableRequestHandler returns a new 2fa secret and qr code for current user to set 2fa and verify passcode next
func (a *TwoFactorAuthorizationsApi) TwoFactorEnableRequestHandler(c *core.Context) (any, *errs.Error) {
func (a *TwoFactorAuthorizationsApi) TwoFactorEnableRequestHandler(c *core.WebContext) (any, *errs.Error) {
uid := c.GetCurrentUid()
enabled, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableRequestHandler] failed to check two-factor setting, because %s", err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorEnableRequestHandler] failed to check two-factor setting, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -75,7 +75,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableRequestHandler(c *core.Conte
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableRequestHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorEnableRequestHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -84,14 +84,14 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableRequestHandler(c *core.Conte
key, err := a.twoFactorAuthorizations.GenerateTwoFactorSecret(c, user)
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableRequestHandler] failed to generate two-factor secret, because %s", err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorEnableRequestHandler] failed to generate two-factor secret, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
img, err := key.Image(240, 240)
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableRequestHandler] failed to generate two-factor qrcode, because %s", err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorEnableRequestHandler] failed to generate two-factor qrcode, because %s", err.Error())
return nil, errs.ErrOperationFailed
}
@@ -110,12 +110,12 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableRequestHandler(c *core.Conte
}
// TwoFactorEnableConfirmHandler enables 2fa for current user
func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.Context) (any, *errs.Error) {
func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.WebContext) (any, *errs.Error) {
var confirmReq models.TwoFactorEnableConfirmRequest
err := c.ShouldBindJSON(&confirmReq)
if err != nil {
log.WarnfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -123,7 +123,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.Conte
exists, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to check two-factor setting, because %s", err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to check two-factor setting, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -135,7 +135,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.Conte
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -147,46 +147,46 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.Conte
}
if !totp.Validate(confirmReq.Passcode, confirmReq.Secret) {
log.WarnfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] passcode is invalid")
log.Warnf(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] passcode is invalid")
return nil, errs.ErrPasscodeInvalid
}
recoveryCodes, err := a.twoFactorAuthorizations.GenerateTwoFactorRecoveryCodes()
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to generate two-factor recovery codes for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to generate two-factor recovery codes for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
err = a.twoFactorAuthorizations.CreateTwoFactorRecoveryCodes(c, uid, recoveryCodes, user.Salt)
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to create two-factor recovery codes for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to create two-factor recovery codes for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
err = a.twoFactorAuthorizations.CreateTwoFactorSetting(c, twoFactorSetting)
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to create two-factor setting for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to create two-factor setting for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] user \"uid:%d\" has enabled two-factor authorization", uid)
log.Infof(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] user \"uid:%d\" has enabled two-factor authorization", uid)
now := time.Now().Unix()
err = a.tokens.DeleteTokensBeforeTime(c, uid, now)
if err == nil {
log.InfofWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] revoke old tokens before unix time \"%d\" for user \"uid:%d\"", now, user.Uid)
log.Infof(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] revoke old tokens before unix time \"%d\" for user \"uid:%d\"", now, user.Uid)
} else {
log.WarnfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to revoke old tokens for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Warnf(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to revoke old tokens for user \"uid:%d\", because %s", user.Uid, err.Error())
}
token, claims, err := a.tokens.CreateToken(c, user)
if err != nil {
log.WarnfWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Warnf(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
confirmResp := &models.TwoFactorEnableConfirmResponse{
RecoveryCodes: recoveryCodes,
@@ -198,7 +198,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.Conte
c.SetTextualToken(token)
c.SetTokenClaims(claims)
log.InfofWithRequestId(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] user \"uid:%d\" token refreshed, new token will be expired at %d", user.Uid, claims.ExpiresAt)
log.Infof(c, "[twofactor_authorizations.TwoFactorEnableConfirmHandler] user \"uid:%d\" token refreshed, new token will be expired at %d", user.Uid, claims.ExpiresAt)
confirmResp := &models.TwoFactorEnableConfirmResponse{
Token: token,
@@ -209,12 +209,12 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.Conte
}
// TwoFactorDisableHandler disables 2fa for current user
func (a *TwoFactorAuthorizationsApi) TwoFactorDisableHandler(c *core.Context) (any, *errs.Error) {
func (a *TwoFactorAuthorizationsApi) TwoFactorDisableHandler(c *core.WebContext) (any, *errs.Error) {
var disableReq models.TwoFactorDisableRequest
err := c.ShouldBindJSON(&disableReq)
if err != nil {
log.WarnfWithRequestId(c, "[twofactor_authorizations.TwoFactorDisableHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[twofactor_authorizations.TwoFactorDisableHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -223,7 +223,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorDisableHandler(c *core.Context) (a
if err != nil {
if !errs.IsCustomError(err) {
log.WarnfWithRequestId(c, "[twofactor_authorizations.TwoFactorDisableHandler] failed to get user for user \"uid:%d\", because %s", uid, err.Error())
log.Warnf(c, "[twofactor_authorizations.TwoFactorDisableHandler] failed to get user for user \"uid:%d\", because %s", uid, err.Error())
}
return nil, errs.ErrUserNotFound
@@ -236,7 +236,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorDisableHandler(c *core.Context) (a
enableTwoFactor, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorDisableHandler] failed to check two-factor setting, because %s", err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorDisableHandler] failed to check two-factor setting, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -247,29 +247,29 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorDisableHandler(c *core.Context) (a
err = a.twoFactorAuthorizations.DeleteTwoFactorRecoveryCodes(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorDisableHandler] failed to delete two-factor recovery codes for user \"uid:%d\"", uid)
log.Errorf(c, "[twofactor_authorizations.TwoFactorDisableHandler] failed to delete two-factor recovery codes for user \"uid:%d\"", uid)
return nil, errs.Or(err, errs.ErrOperationFailed)
}
err = a.twoFactorAuthorizations.DeleteTwoFactorSetting(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorDisableHandler] failed to delete two-factor setting for user \"uid:%d\"", uid)
log.Errorf(c, "[twofactor_authorizations.TwoFactorDisableHandler] failed to delete two-factor setting for user \"uid:%d\"", uid)
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[twofactor_authorizations.TwoFactorDisableHandler] user \"uid:%d\" has disabled two-factor authorization", uid)
log.Infof(c, "[twofactor_authorizations.TwoFactorDisableHandler] user \"uid:%d\" has disabled two-factor authorization", uid)
return true, nil
}
// TwoFactorRecoveryCodeRegenerateHandler returns new 2fa recovery codes and revokes old recovery codes for current user
func (a *TwoFactorAuthorizationsApi) TwoFactorRecoveryCodeRegenerateHandler(c *core.Context) (any, *errs.Error) {
func (a *TwoFactorAuthorizationsApi) TwoFactorRecoveryCodeRegenerateHandler(c *core.WebContext) (any, *errs.Error) {
var regenerateReq models.TwoFactorRegenerateRecoveryCodeRequest
err := c.ShouldBindJSON(&regenerateReq)
if err != nil {
log.WarnfWithRequestId(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -278,7 +278,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorRecoveryCodeRegenerateHandler(c *c
if err != nil {
if !errs.IsCustomError(err) {
log.WarnfWithRequestId(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] failed to get user for user \"uid:%d\", because %s", uid, err.Error())
log.Warnf(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] failed to get user for user \"uid:%d\", because %s", uid, err.Error())
}
return nil, errs.ErrUserNotFound
@@ -291,7 +291,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorRecoveryCodeRegenerateHandler(c *c
enableTwoFactor, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] failed to check two-factor setting, because %s", err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] failed to check two-factor setting, because %s", err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -302,14 +302,14 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorRecoveryCodeRegenerateHandler(c *c
recoveryCodes, err := a.twoFactorAuthorizations.GenerateTwoFactorRecoveryCodes()
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] failed to generate two-factor recovery codes for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] failed to generate two-factor recovery codes for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
err = a.twoFactorAuthorizations.CreateTwoFactorRecoveryCodes(c, uid, recoveryCodes, user.Salt)
if err != nil {
log.ErrorfWithRequestId(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] failed to create two-factor recovery codes for user \"uid:%d\", because %s", uid, err.Error())
log.Errorf(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] failed to create two-factor recovery codes for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -317,7 +317,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorRecoveryCodeRegenerateHandler(c *c
RecoveryCodes: recoveryCodes,
}
log.InfofWithRequestId(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] user \"uid:%d\" has regenerated two-factor recovery codes", uid)
log.Infof(c, "[twofactor_authorizations.TwoFactorRecoveryCodeRegenerateHandler] user \"uid:%d\" has regenerated two-factor recovery codes", uid)
return recoveryCodesResp, nil
}
+60 -60
View File
@@ -38,7 +38,7 @@ var (
)
// UserRegisterHandler saves a new user by request parameters
func (a *UsersApi) UserRegisterHandler(c *core.Context) (any, *errs.Error) {
func (a *UsersApi) UserRegisterHandler(c *core.WebContext) (any, *errs.Error) {
if !a.CurrentConfig().EnableUserRegister {
return nil, errs.ErrUserRegistrationNotAllowed
}
@@ -47,12 +47,12 @@ func (a *UsersApi) UserRegisterHandler(c *core.Context) (any, *errs.Error) {
err := c.ShouldBindBodyWith(&userRegisterReq, binding.JSON)
if err != nil {
log.WarnfWithRequestId(c, "[users.UserRegisterHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[users.UserRegisterHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
if userRegisterReq.DefaultCurrency == validators.ParentAccountCurrencyPlaceholder {
log.WarnfWithRequestId(c, "[users.UserRegisterHandler] user default currency is invalid")
log.Warnf(c, "[users.UserRegisterHandler] user default currency is invalid")
return nil, errs.ErrUserDefaultCurrencyIsInvalid
}
@@ -74,11 +74,11 @@ func (a *UsersApi) UserRegisterHandler(c *core.Context) (any, *errs.Error) {
err = a.users.CreateUser(c, user)
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserRegisterHandler] failed to create user \"%s\", because %s", user.Username, err.Error())
log.Errorf(c, "[users.UserRegisterHandler] failed to create user \"%s\", because %s", user.Username, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
log.InfofWithRequestId(c, "[users.UserRegisterHandler] user \"%s\" has registered successfully, uid is %d", user.Username, user.Uid)
log.Infof(c, "[users.UserRegisterHandler] user \"%s\" has registered successfully, uid is %d", user.Username, user.Uid)
presetCategoriesSaved := false
@@ -104,13 +104,13 @@ func (a *UsersApi) UserRegisterHandler(c *core.Context) (any, *errs.Error) {
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserRegisterHandler] failed to create email verify token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[users.UserRegisterHandler] failed to create email verify token for user \"uid:%d\", because %s", user.Uid, err.Error())
} else {
go func() {
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
if err != nil {
log.WarnfWithRequestId(c, "[users.UserRegisterHandler] cannot send verify email to \"%s\", because %s", user.Email, err.Error())
log.Warnf(c, "[users.UserRegisterHandler] cannot send verify email to \"%s\", because %s", user.Email, err.Error())
}
}()
}
@@ -123,7 +123,7 @@ func (a *UsersApi) UserRegisterHandler(c *core.Context) (any, *errs.Error) {
token, claims, err := a.tokens.CreateToken(c, user)
if err != nil {
log.WarnfWithRequestId(c, "[users.UserRegisterHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Warnf(c, "[users.UserRegisterHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return authResp, nil
}
@@ -131,13 +131,13 @@ func (a *UsersApi) UserRegisterHandler(c *core.Context) (any, *errs.Error) {
c.SetTextualToken(token)
c.SetTokenClaims(claims)
log.InfofWithRequestId(c, "[users.UserRegisterHandler] user \"uid:%d\" has logined, token will be expired at %d", user.Uid, claims.ExpiresAt)
log.Infof(c, "[users.UserRegisterHandler] user \"uid:%d\" has logined, token will be expired at %d", user.Uid, claims.ExpiresAt)
return authResp, nil
}
// UserEmailVerifyHandler sets user email address verified
func (a *UsersApi) UserEmailVerifyHandler(c *core.Context) (any, *errs.Error) {
func (a *UsersApi) UserEmailVerifyHandler(c *core.WebContext) (any, *errs.Error) {
var userVerifyEmailReq models.UserVerifyEmailRequest
err := c.ShouldBindJSON(&userVerifyEmailReq)
@@ -146,35 +146,35 @@ func (a *UsersApi) UserEmailVerifyHandler(c *core.Context) (any, *errs.Error) {
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[users.UserEmailVerifyHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[users.UserEmailVerifyHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
}
if user.Disabled {
log.WarnfWithRequestId(c, "[users.UserEmailVerifyHandler] user \"uid:%d\" is disabled", user.Uid)
log.Warnf(c, "[users.UserEmailVerifyHandler] user \"uid:%d\" is disabled", user.Uid)
return nil, errs.ErrUserIsDisabled
}
if user.EmailVerified {
log.WarnfWithRequestId(c, "[users.UserEmailVerifyHandler] user \"uid:%d\" email has been verified", user.Uid)
log.Warnf(c, "[users.UserEmailVerifyHandler] user \"uid:%d\" email has been verified", user.Uid)
return nil, errs.ErrEmailIsVerified
}
err = a.users.SetUserEmailVerified(c, user.Username)
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserEmailVerifyHandler] failed to update user \"uid:%d\" email address verified, because %s", user.Uid, err.Error())
log.Errorf(c, "[users.UserEmailVerifyHandler] failed to update user \"uid:%d\" email address verified, because %s", user.Uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
err = a.tokens.DeleteTokensByType(c, uid, core.USER_TOKEN_TYPE_EMAIL_VERIFY)
if err == nil {
log.InfofWithRequestId(c, "[users.UserEmailVerifyHandler] revoke old email verify tokens for user \"uid:%d\"", user.Uid)
log.Infof(c, "[users.UserEmailVerifyHandler] revoke old email verify tokens for user \"uid:%d\"", user.Uid)
} else {
log.WarnfWithRequestId(c, "[users.UserEmailVerifyHandler] failed to revoke old email verify tokens for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Warnf(c, "[users.UserEmailVerifyHandler] failed to revoke old email verify tokens for user \"uid:%d\", because %s", user.Uid, err.Error())
}
resp := &models.UserVerifyEmailResponse{}
@@ -183,7 +183,7 @@ func (a *UsersApi) UserEmailVerifyHandler(c *core.Context) (any, *errs.Error) {
token, claims, err := a.tokens.CreateToken(c, user)
if err != nil {
log.WarnfWithRequestId(c, "[users.UserEmailVerifyHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Warnf(c, "[users.UserEmailVerifyHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return resp, nil
}
@@ -194,20 +194,20 @@ func (a *UsersApi) UserEmailVerifyHandler(c *core.Context) (any, *errs.Error) {
c.SetTextualToken(token)
c.SetTokenClaims(claims)
log.InfofWithRequestId(c, "[users.UserEmailVerifyHandler] user \"uid:%d\" token created, new token will be expired at %d", user.Uid, claims.ExpiresAt)
log.Infof(c, "[users.UserEmailVerifyHandler] user \"uid:%d\" token created, new token will be expired at %d", user.Uid, claims.ExpiresAt)
}
return resp, nil
}
// UserProfileHandler returns user profile of current user
func (a *UsersApi) UserProfileHandler(c *core.Context) (any, *errs.Error) {
func (a *UsersApi) UserProfileHandler(c *core.WebContext) (any, *errs.Error) {
uid := c.GetCurrentUid()
user, err := a.users.GetUserById(c, uid)
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[users.UserRegisterHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[users.UserRegisterHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -218,12 +218,12 @@ func (a *UsersApi) UserProfileHandler(c *core.Context) (any, *errs.Error) {
}
// UserUpdateProfileHandler saves user profile by request parameters for current user
func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error) {
func (a *UsersApi) UserUpdateProfileHandler(c *core.WebContext) (any, *errs.Error) {
var userUpdateReq models.UserProfileUpdateRequest
err := c.ShouldBindJSON(&userUpdateReq)
if err != nil {
log.WarnfWithRequestId(c, "[users.UserUpdateProfileHandler] parse request failed, because %s", err.Error())
log.Warnf(c, "[users.UserUpdateProfileHandler] parse request failed, because %s", err.Error())
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
}
@@ -232,7 +232,7 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[users.UserUpdateProfileHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[users.UserUpdateProfileHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -278,12 +278,12 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
}
if _, exists := accountMap[userUpdateReq.DefaultAccountId]; !exists {
log.WarnfWithRequestId(c, "[users.UserUpdateProfileHandler] account \"id:%d\" does not exist for user \"uid:%d\"", userUpdateReq.DefaultAccountId, uid)
log.Warnf(c, "[users.UserUpdateProfileHandler] account \"id:%d\" does not exist for user \"uid:%d\"", userUpdateReq.DefaultAccountId, uid)
return nil, errs.ErrUserDefaultAccountIsInvalid
}
if accountMap[userUpdateReq.DefaultAccountId].Hidden {
log.WarnfWithRequestId(c, "[users.UserUpdateProfileHandler] account \"id:%d\" is hidden of user \"uid:%d\"", userUpdateReq.DefaultAccountId, uid)
log.Warnf(c, "[users.UserUpdateProfileHandler] account \"id:%d\" is hidden of user \"uid:%d\"", userUpdateReq.DefaultAccountId, uid)
return nil, errs.ErrUserDefaultAccountIsHidden
}
@@ -437,7 +437,7 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
keyProfileUpdated, emailSetToUnverified, err := a.users.UpdateUser(c, userNew, modifyUserLanguage)
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserUpdateProfileHandler] failed to update user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[users.UserUpdateProfileHandler] failed to update user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -445,7 +445,7 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
user.EmailVerified = false
}
log.InfofWithRequestId(c, "[users.UserUpdateProfileHandler] user \"uid:%d\" has updated successfully", user.Uid)
log.Infof(c, "[users.UserUpdateProfileHandler] user \"uid:%d\" has updated successfully", user.Uid)
resp := &models.UserProfileUpdateResponse{
User: a.GetUserBasicInfo(user),
@@ -455,18 +455,18 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
err = a.tokens.DeleteTokensByType(c, uid, core.USER_TOKEN_TYPE_EMAIL_VERIFY)
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserUpdateProfileHandler] failed to revoke old email verify tokens for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[users.UserUpdateProfileHandler] failed to revoke old email verify tokens for user \"uid:%d\", because %s", user.Uid, err.Error())
} else {
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserUpdateProfileHandler] failed to create email verify token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[users.UserUpdateProfileHandler] failed to create email verify token for user \"uid:%d\", because %s", user.Uid, err.Error())
} else {
go func() {
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
if err != nil {
log.WarnfWithRequestId(c, "[users.UserUpdateProfileHandler] cannot send verify email to \"%s\", because %s", user.Email, err.Error())
log.Warnf(c, "[users.UserUpdateProfileHandler] cannot send verify email to \"%s\", because %s", user.Email, err.Error())
}
}()
}
@@ -478,15 +478,15 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
err = a.tokens.DeleteTokensBeforeTime(c, uid, now)
if err == nil {
log.InfofWithRequestId(c, "[users.UserUpdateProfileHandler] revoke old tokens before unix time \"%d\" for user \"uid:%d\"", now, user.Uid)
log.Infof(c, "[users.UserUpdateProfileHandler] revoke old tokens before unix time \"%d\" for user \"uid:%d\"", now, user.Uid)
} else {
log.WarnfWithRequestId(c, "[users.UserUpdateProfileHandler] failed to revoke old tokens for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Warnf(c, "[users.UserUpdateProfileHandler] failed to revoke old tokens for user \"uid:%d\", because %s", user.Uid, err.Error())
}
token, claims, err := a.tokens.CreateToken(c, user)
if err != nil {
log.WarnfWithRequestId(c, "[users.UserUpdateProfileHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Warnf(c, "[users.UserUpdateProfileHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return resp, nil
}
@@ -494,7 +494,7 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
c.SetTextualToken(token)
c.SetTokenClaims(claims)
log.InfofWithRequestId(c, "[users.UserUpdateProfileHandler] user \"uid:%d\" token refreshed, new token will be expired at %d", user.Uid, claims.ExpiresAt)
log.Infof(c, "[users.UserUpdateProfileHandler] user \"uid:%d\" token refreshed, new token will be expired at %d", user.Uid, claims.ExpiresAt)
return resp, nil
}
@@ -503,13 +503,13 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
}
// UserUpdateAvatarHandler saves user avatar by request parameters for current user
func (a *UsersApi) UserUpdateAvatarHandler(c *core.Context) (any, *errs.Error) {
func (a *UsersApi) UserUpdateAvatarHandler(c *core.WebContext) (any, *errs.Error) {
uid := c.GetCurrentUid()
user, err := a.users.GetUserById(c, uid)
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[users.UserUpdateAvatarHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[users.UserUpdateAvatarHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -518,40 +518,40 @@ func (a *UsersApi) UserUpdateAvatarHandler(c *core.Context) (any, *errs.Error) {
form, err := c.MultipartForm()
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserUpdateAvatarHandler] failed to get multi-part form data for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[users.UserUpdateAvatarHandler] failed to get multi-part form data for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.ErrParameterInvalid
}
avatars := form.File["avatar"]
if len(avatars) < 1 {
log.WarnfWithRequestId(c, "[users.UserUpdateAvatarHandler] there is no user avatar in request for user \"uid:%d\"", user.Uid)
log.Warnf(c, "[users.UserUpdateAvatarHandler] there is no user avatar in request for user \"uid:%d\"", user.Uid)
return nil, errs.ErrNoUserAvatar
}
if avatars[0].Size < 1 {
log.WarnfWithRequestId(c, "[users.UserUpdateAvatarHandler] the size of user avatar in request is zero for user \"uid:%d\"", user.Uid)
log.Warnf(c, "[users.UserUpdateAvatarHandler] the size of user avatar in request is zero for user \"uid:%d\"", user.Uid)
return nil, errs.ErrUserAvatarIsEmpty
}
fileExtension := utils.GetFileNameExtension(avatars[0].Filename)
if utils.GetImageContentType(fileExtension) == "" {
log.WarnfWithRequestId(c, "[users.UserUpdateAvatarHandler] the file extension \"%s\" of user avatar in request is not supported for user \"uid:%d\"", fileExtension, user.Uid)
log.Warnf(c, "[users.UserUpdateAvatarHandler] the file extension \"%s\" of user avatar in request is not supported for user \"uid:%d\"", fileExtension, user.Uid)
return nil, errs.ErrImageTypeNotSupported
}
avatarFile, err := avatars[0].Open()
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserUpdateAvatarHandler] failed to get avatar file from request for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[users.UserUpdateAvatarHandler] failed to get avatar file from request for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.ErrOperationFailed
}
err = a.users.UpdateUserAvatar(c, user.Uid, avatarFile, fileExtension, user.CustomAvatarType)
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserUpdateAvatarHandler] failed to update avatar for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[users.UserUpdateAvatarHandler] failed to update avatar for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -561,13 +561,13 @@ func (a *UsersApi) UserUpdateAvatarHandler(c *core.Context) (any, *errs.Error) {
}
// UserRemoveAvatarHandler removes user avatar by request parameters for current user
func (a *UsersApi) UserRemoveAvatarHandler(c *core.Context) (any, *errs.Error) {
func (a *UsersApi) UserRemoveAvatarHandler(c *core.WebContext) (any, *errs.Error) {
uid := c.GetCurrentUid()
user, err := a.users.GetUserById(c, uid)
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[users.UserRemoveAvatarHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[users.UserRemoveAvatarHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
@@ -580,7 +580,7 @@ func (a *UsersApi) UserRemoveAvatarHandler(c *core.Context) (any, *errs.Error) {
err = a.users.RemoveUserAvatar(c, user.Uid, user.CustomAvatarType)
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserRemoveAvatarHandler] failed to remove avatar for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[users.UserRemoveAvatarHandler] failed to remove avatar for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
@@ -590,7 +590,7 @@ func (a *UsersApi) UserRemoveAvatarHandler(c *core.Context) (any, *errs.Error) {
}
// UserSendVerifyEmailByUnloginUserHandler sends unlogin user verify email
func (a *UsersApi) UserSendVerifyEmailByUnloginUserHandler(c *core.Context) (any, *errs.Error) {
func (a *UsersApi) UserSendVerifyEmailByUnloginUserHandler(c *core.WebContext) (any, *errs.Error) {
if !a.CurrentConfig().EnableUserVerifyEmail {
return nil, errs.ErrEmailValidationNotAllowed
}
@@ -602,24 +602,24 @@ func (a *UsersApi) UserSendVerifyEmailByUnloginUserHandler(c *core.Context) (any
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[users.UserSendVerifyEmailByUnloginUserHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[users.UserSendVerifyEmailByUnloginUserHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
}
if !a.users.IsPasswordEqualsUserPassword(userResendVerifyEmailReq.Password, user) {
log.WarnfWithRequestId(c, "[users.UserSendVerifyEmailByUnloginUserHandler] request password not equals to the user password")
log.Warnf(c, "[users.UserSendVerifyEmailByUnloginUserHandler] request password not equals to the user password")
return nil, errs.ErrUserPasswordWrong
}
if user.Disabled {
log.WarnfWithRequestId(c, "[users.UserSendVerifyEmailByUnloginUserHandler] user \"uid:%d\" is disabled", user.Uid)
log.Warnf(c, "[users.UserSendVerifyEmailByUnloginUserHandler] user \"uid:%d\" is disabled", user.Uid)
return nil, errs.ErrUserIsDisabled
}
if user.EmailVerified {
log.WarnfWithRequestId(c, "[users.UserSendVerifyEmailByUnloginUserHandler] user \"uid:%d\" email has been verified", user.Uid)
log.Warnf(c, "[users.UserSendVerifyEmailByUnloginUserHandler] user \"uid:%d\" email has been verified", user.Uid)
return nil, errs.ErrEmailIsVerified
}
@@ -630,7 +630,7 @@ func (a *UsersApi) UserSendVerifyEmailByUnloginUserHandler(c *core.Context) (any
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserSendVerifyEmailByUnloginUserHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[users.UserSendVerifyEmailByUnloginUserHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.ErrTokenGenerating
}
@@ -638,7 +638,7 @@ func (a *UsersApi) UserSendVerifyEmailByUnloginUserHandler(c *core.Context) (any
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
if err != nil {
log.WarnfWithRequestId(c, "[users.UserSendVerifyEmailByUnloginUserHandler] cannot send email to \"%s\", because %s", user.Email, err.Error())
log.Warnf(c, "[users.UserSendVerifyEmailByUnloginUserHandler] cannot send email to \"%s\", because %s", user.Email, err.Error())
}
}()
@@ -646,7 +646,7 @@ func (a *UsersApi) UserSendVerifyEmailByUnloginUserHandler(c *core.Context) (any
}
// UserSendVerifyEmailByLoginedUserHandler sends logined user verify email
func (a *UsersApi) UserSendVerifyEmailByLoginedUserHandler(c *core.Context) (any, *errs.Error) {
func (a *UsersApi) UserSendVerifyEmailByLoginedUserHandler(c *core.WebContext) (any, *errs.Error) {
if !a.CurrentConfig().EnableUserVerifyEmail {
return nil, errs.ErrEmailValidationNotAllowed
}
@@ -656,14 +656,14 @@ func (a *UsersApi) UserSendVerifyEmailByLoginedUserHandler(c *core.Context) (any
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[users.UserSendVerifyEmailByLoginedUserHandler] failed to get user, because %s", err.Error())
log.Errorf(c, "[users.UserSendVerifyEmailByLoginedUserHandler] failed to get user, because %s", err.Error())
}
return nil, errs.ErrUserNotFound
}
if user.EmailVerified {
log.WarnfWithRequestId(c, "[users.UserSendVerifyEmailByLoginedUserHandler] user \"uid:%d\" email has been verified", user.Uid)
log.Warnf(c, "[users.UserSendVerifyEmailByLoginedUserHandler] user \"uid:%d\" email has been verified", user.Uid)
return nil, errs.ErrEmailIsVerified
}
@@ -674,7 +674,7 @@ func (a *UsersApi) UserSendVerifyEmailByLoginedUserHandler(c *core.Context) (any
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
if err != nil {
log.ErrorfWithRequestId(c, "[users.UserSendVerifyEmailByLoginedUserHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.Errorf(c, "[users.UserSendVerifyEmailByLoginedUserHandler] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.ErrTokenGenerating
}
@@ -682,7 +682,7 @@ func (a *UsersApi) UserSendVerifyEmailByLoginedUserHandler(c *core.Context) (any
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
if err != nil {
log.WarnfWithRequestId(c, "[users.UserSendVerifyEmailByLoginedUserHandler] cannot send email to \"%s\", because %s", user.Email, err.Error())
log.Warnf(c, "[users.UserSendVerifyEmailByLoginedUserHandler] cannot send email to \"%s\", because %s", user.Email, err.Error())
}
}()
@@ -690,7 +690,7 @@ func (a *UsersApi) UserSendVerifyEmailByLoginedUserHandler(c *core.Context) (any
}
// UserGetAvatarHandler returns user avatar data for current user
func (a *UsersApi) UserGetAvatarHandler(c *core.Context) ([]byte, string, *errs.Error) {
func (a *UsersApi) UserGetAvatarHandler(c *core.WebContext) ([]byte, string, *errs.Error) {
fileName := c.Param("fileName")
fileExtension := utils.GetFileNameExtension(fileName)
contentType := utils.GetImageContentType(fileExtension)
@@ -703,7 +703,7 @@ func (a *UsersApi) UserGetAvatarHandler(c *core.Context) ([]byte, string, *errs.
fileBaseName := utils.GetFileNameWithoutExtension(fileName)
if utils.Int64ToString(uid) != fileBaseName {
log.WarnfWithRequestId(c, "[users.UserGetAvatarHandler] cannot get other user avatar \"uid:%s\" for user \"uid:%d\"", fileBaseName, uid)
log.Warnf(c, "[users.UserGetAvatarHandler] cannot get other user avatar \"uid:%s\" for user \"uid:%d\"", fileBaseName, uid)
return nil, "", errs.ErrUserIdInvalid
}
@@ -711,7 +711,7 @@ func (a *UsersApi) UserGetAvatarHandler(c *core.Context) ([]byte, string, *errs.
if err != nil {
if !errs.IsCustomError(err) {
log.ErrorfWithRequestId(c, "[users.UserGetAvatarHandler] failed to get user avatar, because %s", err.Error())
log.Errorf(c, "[users.UserGetAvatarHandler] failed to get user avatar, because %s", err.Error())
}
return nil, "", errs.Or(err, errs.ErrOperationFailed)
+140 -141
View File
@@ -3,9 +3,8 @@ package cli
import (
"time"
"github.com/urfave/cli/v2"
"github.com/mayswind/ezbookkeeping/pkg/converters"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/log"
"github.com/mayswind/ezbookkeeping/pkg/models"
@@ -52,34 +51,34 @@ var (
)
// AddNewUser adds a new user according to specified info
func (l *UserDataCli) AddNewUser(c *cli.Context, username string, email string, nickname string, password string, defaultCurrency string) (*models.User, error) {
func (l *UserDataCli) AddNewUser(c *core.CliContext, username string, email string, nickname string, password string, defaultCurrency string) (*models.User, error) {
if username == "" {
log.BootErrorf("[user_data.AddNewUser] user name is empty")
log.BootErrorf(c, "[user_data.AddNewUser] user name is empty")
return nil, errs.ErrUsernameIsEmpty
}
if email == "" {
log.BootErrorf("[user_data.AddNewUser] user email is empty")
log.BootErrorf(c, "[user_data.AddNewUser] user email is empty")
return nil, errs.ErrEmailIsEmpty
}
if nickname == "" {
log.BootErrorf("[user_data.AddNewUser] user nickname is empty")
log.BootErrorf(c, "[user_data.AddNewUser] user nickname is empty")
return nil, errs.ErrNicknameIsEmpty
}
if password == "" {
log.BootErrorf("[user_data.AddNewUser] user password is empty")
log.BootErrorf(c, "[user_data.AddNewUser] user password is empty")
return nil, errs.ErrPasswordIsEmpty
}
if defaultCurrency == "" {
log.BootErrorf("[user_data.AddNewUser] user default currency is empty")
log.BootErrorf(c, "[user_data.AddNewUser] user default currency is empty")
return nil, errs.ErrUserDefaultCurrencyIsEmpty
}
if _, ok := validators.AllCurrencyNames[defaultCurrency]; !ok {
log.BootErrorf("[user_data.AddNewUser] user default currency is invalid")
log.BootErrorf(c, "[user_data.AddNewUser] user default currency is invalid")
return nil, errs.ErrUserDefaultCurrencyIsInvalid
}
@@ -93,29 +92,29 @@ func (l *UserDataCli) AddNewUser(c *cli.Context, username string, email string,
TransactionEditScope: models.TRANSACTION_EDIT_SCOPE_ALL,
}
err := l.users.CreateUser(nil, user)
err := l.users.CreateUser(c, user)
if err != nil {
log.BootErrorf("[user_data.AddNewUser] failed to create user \"%s\", because %s", user.Username, err.Error())
log.BootErrorf(c, "[user_data.AddNewUser] failed to create user \"%s\", because %s", user.Username, err.Error())
return nil, err
}
log.BootInfof("[user_data.AddNewUser] user \"%s\" has add successfully, uid is %d", user.Username, user.Uid)
log.BootInfof(c, "[user_data.AddNewUser] user \"%s\" has add successfully, uid is %d", user.Username, user.Uid)
return user, nil
}
// GetUserByUsername returns user by user name
func (l *UserDataCli) GetUserByUsername(c *cli.Context, username string) (*models.User, error) {
func (l *UserDataCli) GetUserByUsername(c *core.CliContext, username string) (*models.User, error) {
if username == "" {
log.BootErrorf("[user_data.GetUserByUsername] user name is empty")
log.BootErrorf(c, "[user_data.GetUserByUsername] user name is empty")
return nil, errs.ErrUsernameIsEmpty
}
user, err := l.users.GetUserByUsername(nil, username)
user, err := l.users.GetUserByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.GetUserByUsername] failed to get user by user name \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.GetUserByUsername] failed to get user by user name \"%s\", because %s", username, err.Error())
return nil, err
}
@@ -123,21 +122,21 @@ func (l *UserDataCli) GetUserByUsername(c *cli.Context, username string) (*model
}
// ModifyUserPassword modifies user password
func (l *UserDataCli) ModifyUserPassword(c *cli.Context, username string, password string) error {
func (l *UserDataCli) ModifyUserPassword(c *core.CliContext, username string, password string) error {
if username == "" {
log.BootErrorf("[user_data.ModifyUserPassword] user name is empty")
log.BootErrorf(c, "[user_data.ModifyUserPassword] user name is empty")
return errs.ErrUsernameIsEmpty
}
if password == "" {
log.BootErrorf("[user_data.ModifyUserPassword] user password is empty")
log.BootErrorf(c, "[user_data.ModifyUserPassword] user password is empty")
return errs.ErrPasswordIsEmpty
}
user, err := l.users.GetUserByUsername(nil, username)
user, err := l.users.GetUserByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.ModifyUserPassword] failed to get user by user name \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.ModifyUserPassword] failed to get user by user name \"%s\", because %s", username, err.Error())
return err
}
@@ -151,55 +150,55 @@ func (l *UserDataCli) ModifyUserPassword(c *cli.Context, username string, passwo
Password: password,
}
_, _, err = l.users.UpdateUser(nil, userNew, false)
_, _, err = l.users.UpdateUser(c, userNew, false)
if err != nil {
log.BootErrorf("[user_data.ModifyUserPassword] failed to update user \"%s\" password, because %s", user.Username, err.Error())
log.BootErrorf(c, "[user_data.ModifyUserPassword] failed to update user \"%s\" password, because %s", user.Username, err.Error())
return err
}
now := time.Now().Unix()
err = l.tokens.DeleteTokensBeforeTime(nil, user.Uid, now)
err = l.tokens.DeleteTokensBeforeTime(c, user.Uid, now)
if err == nil {
log.BootInfof("[user_data.ModifyUserPassword] revoke old tokens before unix time \"%d\" for user \"%s\"", now, user.Username)
log.BootInfof(c, "[user_data.ModifyUserPassword] revoke old tokens before unix time \"%d\" for user \"%s\"", now, user.Username)
} else {
log.BootWarnf("[user_data.ModifyUserPassword] failed to revoke old tokens for user \"%s\", because %s", user.Username, err.Error())
log.BootWarnf(c, "[user_data.ModifyUserPassword] failed to revoke old tokens for user \"%s\", because %s", user.Username, err.Error())
}
return nil
}
// SendPasswordResetMail sends an email with password reset link
func (l *UserDataCli) SendPasswordResetMail(c *cli.Context, username string) error {
func (l *UserDataCli) SendPasswordResetMail(c *core.CliContext, username string) error {
if username == "" {
log.BootErrorf("[user_data.SendPasswordResetMail] user name is empty")
log.BootErrorf(c, "[user_data.SendPasswordResetMail] user name is empty")
return errs.ErrUsernameIsEmpty
}
user, err := l.users.GetUserByUsername(nil, username)
user, err := l.users.GetUserByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.SendPasswordResetMail] failed to get user by user name \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.SendPasswordResetMail] failed to get user by user name \"%s\", because %s", username, err.Error())
return err
}
if l.CurrentConfig().ForgetPasswordRequireVerifyEmail && !user.EmailVerified {
log.BootWarnf("[user_data.SendPasswordResetMail] user \"uid:%d\" has not verified email", user.Uid)
log.BootWarnf(c, "[user_data.SendPasswordResetMail] user \"uid:%d\" has not verified email", user.Uid)
return errs.ErrEmailIsNotVerified
}
token, _, err := l.tokens.CreatePasswordResetToken(nil, user)
token, _, err := l.tokens.CreatePasswordResetTokenWithoutUserAgent(c, user)
if err != nil {
log.BootErrorf("[user_data.SendPasswordResetMail] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.BootErrorf(c, "[user_data.SendPasswordResetMail] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return err
}
err = l.forgetPasswords.SendPasswordResetEmail(nil, user, token, "")
err = l.forgetPasswords.SendPasswordResetEmail(c, user, token, "")
if err != nil {
log.BootWarnf("[user_data.SendPasswordResetMail] cannot send email to \"%s\", because %s", user.Email, err.Error())
log.BootWarnf(c, "[user_data.SendPasswordResetMail] cannot send email to \"%s\", because %s", user.Email, err.Error())
return err
}
@@ -207,16 +206,16 @@ func (l *UserDataCli) SendPasswordResetMail(c *cli.Context, username string) err
}
// EnableUser sets user enabled according to the specified user name
func (l *UserDataCli) EnableUser(c *cli.Context, username string) error {
func (l *UserDataCli) EnableUser(c *core.CliContext, username string) error {
if username == "" {
log.BootErrorf("[user_data.EnableUser] user name is empty")
log.BootErrorf(c, "[user_data.EnableUser] user name is empty")
return errs.ErrUsernameIsEmpty
}
err := l.users.EnableUser(nil, username)
err := l.users.EnableUser(c, username)
if err != nil {
log.BootErrorf("[user_data.EnableUser] failed to set user enabled by user name \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.EnableUser] failed to set user enabled by user name \"%s\", because %s", username, err.Error())
return err
}
@@ -224,16 +223,16 @@ func (l *UserDataCli) EnableUser(c *cli.Context, username string) error {
}
// DisableUser sets user disabled according to the specified user name
func (l *UserDataCli) DisableUser(c *cli.Context, username string) error {
func (l *UserDataCli) DisableUser(c *core.CliContext, username string) error {
if username == "" {
log.BootErrorf("[user_data.DisableUser] user name is empty")
log.BootErrorf(c, "[user_data.DisableUser] user name is empty")
return errs.ErrUsernameIsEmpty
}
err := l.users.DisableUser(nil, username)
err := l.users.DisableUser(c, username)
if err != nil {
log.BootErrorf("[user_data.DisableUser] failed to set user disabled by user name \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.DisableUser] failed to set user disabled by user name \"%s\", because %s", username, err.Error())
return err
}
@@ -241,39 +240,39 @@ func (l *UserDataCli) DisableUser(c *cli.Context, username string) error {
}
// ResendVerifyEmail resends an email with account activation link
func (l *UserDataCli) ResendVerifyEmail(c *cli.Context, username string) error {
func (l *UserDataCli) ResendVerifyEmail(c *core.CliContext, username string) error {
if !l.CurrentConfig().EnableUserVerifyEmail {
return errs.ErrEmailValidationNotAllowed
}
if username == "" {
log.BootErrorf("[user_data.ResendVerifyEmail] user name is empty")
log.BootErrorf(c, "[user_data.ResendVerifyEmail] user name is empty")
return errs.ErrUsernameIsEmpty
}
user, err := l.users.GetUserByUsername(nil, username)
user, err := l.users.GetUserByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.ResendVerifyEmail] failed to get user by user name \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.ResendVerifyEmail] failed to get user by user name \"%s\", because %s", username, err.Error())
return err
}
if user.EmailVerified {
log.BootWarnf("[user_data.ResendVerifyEmail] user \"uid:%d\" email has been verified", user.Uid)
log.BootWarnf(c, "[user_data.ResendVerifyEmail] user \"uid:%d\" email has been verified", user.Uid)
return errs.ErrEmailIsVerified
}
token, _, err := l.tokens.CreateEmailVerifyToken(nil, user)
token, _, err := l.tokens.CreateEmailVerifyTokenWithoutUserAgent(c, user)
if err != nil {
log.BootErrorf("[user_data.ResendVerifyEmail] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
log.BootErrorf(c, "[user_data.ResendVerifyEmail] failed to create token for user \"uid:%d\", because %s", user.Uid, err.Error())
return errs.ErrTokenGenerating
}
err = l.users.SendVerifyEmail(user, token, "")
if err != nil {
log.BootErrorf("[user_data.ResendVerifyEmail] cannot send email to \"%s\", because %s", user.Email, err.Error())
log.BootErrorf(c, "[user_data.ResendVerifyEmail] cannot send email to \"%s\", because %s", user.Email, err.Error())
return err
}
@@ -281,16 +280,16 @@ func (l *UserDataCli) ResendVerifyEmail(c *cli.Context, username string) error {
}
// SetUserEmailVerified sets user email address verified
func (l *UserDataCli) SetUserEmailVerified(c *cli.Context, username string) error {
func (l *UserDataCli) SetUserEmailVerified(c *core.CliContext, username string) error {
if username == "" {
log.BootErrorf("[user_data.SetUserEmailVerified] user name is empty")
log.BootErrorf(c, "[user_data.SetUserEmailVerified] user name is empty")
return errs.ErrUsernameIsEmpty
}
err := l.users.SetUserEmailVerified(nil, username)
err := l.users.SetUserEmailVerified(c, username)
if err != nil {
log.BootErrorf("[user_data.SetUserEmailVerified] failed to set user email address verified by user name \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.SetUserEmailVerified] failed to set user email address verified by user name \"%s\", because %s", username, err.Error())
return err
}
@@ -298,16 +297,16 @@ func (l *UserDataCli) SetUserEmailVerified(c *cli.Context, username string) erro
}
// SetUserEmailUnverified sets user email address unverified
func (l *UserDataCli) SetUserEmailUnverified(c *cli.Context, username string) error {
func (l *UserDataCli) SetUserEmailUnverified(c *core.CliContext, username string) error {
if username == "" {
log.BootErrorf("[user_data.SetUserEmailUnverified] user name is empty")
log.BootErrorf(c, "[user_data.SetUserEmailUnverified] user name is empty")
return errs.ErrUsernameIsEmpty
}
err := l.users.SetUserEmailUnverified(nil, username)
err := l.users.SetUserEmailUnverified(c, username)
if err != nil {
log.BootErrorf("[user_data.SetUserEmailUnverified] failed to set user email address unverified by user name \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.SetUserEmailUnverified] failed to set user email address unverified by user name \"%s\", because %s", username, err.Error())
return err
}
@@ -315,16 +314,16 @@ func (l *UserDataCli) SetUserEmailUnverified(c *cli.Context, username string) er
}
// DeleteUser deletes user according to the specified user name
func (l *UserDataCli) DeleteUser(c *cli.Context, username string) error {
func (l *UserDataCli) DeleteUser(c *core.CliContext, username string) error {
if username == "" {
log.BootErrorf("[user_data.DeleteUser] user name is empty")
log.BootErrorf(c, "[user_data.DeleteUser] user name is empty")
return errs.ErrUsernameIsEmpty
}
err := l.users.DeleteUser(nil, username)
err := l.users.DeleteUser(c, username)
if err != nil {
log.BootErrorf("[user_data.DeleteUser] failed to delete user by user name \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.DeleteUser] failed to delete user by user name \"%s\", because %s", username, err.Error())
return err
}
@@ -332,23 +331,23 @@ func (l *UserDataCli) DeleteUser(c *cli.Context, username string) error {
}
// ListUserTokens returns all tokens of the specified user
func (l *UserDataCli) ListUserTokens(c *cli.Context, username string) ([]*models.TokenRecord, error) {
func (l *UserDataCli) ListUserTokens(c *core.CliContext, username string) ([]*models.TokenRecord, error) {
if username == "" {
log.BootErrorf("[user_data.ListUserTokens] user name is empty")
log.BootErrorf(c, "[user_data.ListUserTokens] user name is empty")
return nil, errs.ErrUsernameIsEmpty
}
uid, err := l.getUserIdByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.ListUserTokens] error occurs when getting user id by user name")
log.BootErrorf(c, "[user_data.ListUserTokens] error occurs when getting user id by user name")
return nil, err
}
tokens, err := l.tokens.GetAllUnexpiredNormalTokensByUid(nil, uid)
tokens, err := l.tokens.GetAllUnexpiredNormalTokensByUid(c, uid)
if err != nil {
log.BootErrorf("[user_data.ListUserTokens] failed to get tokens of user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.ListUserTokens] failed to get tokens of user \"%s\", because %s", username, err.Error())
return nil, err
}
@@ -356,24 +355,24 @@ func (l *UserDataCli) ListUserTokens(c *cli.Context, username string) ([]*models
}
// ClearUserTokens clears all tokens of the specified user
func (l *UserDataCli) ClearUserTokens(c *cli.Context, username string) error {
func (l *UserDataCli) ClearUserTokens(c *core.CliContext, username string) error {
if username == "" {
log.BootErrorf("[user_data.ClearUserTokens] user name is empty")
log.BootErrorf(c, "[user_data.ClearUserTokens] user name is empty")
return errs.ErrUsernameIsEmpty
}
uid, err := l.getUserIdByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.ClearUserTokens] error occurs when getting user id by user name")
log.BootErrorf(c, "[user_data.ClearUserTokens] error occurs when getting user id by user name")
return err
}
now := time.Now().Unix()
err = l.tokens.DeleteTokensBeforeTime(nil, uid, now)
err = l.tokens.DeleteTokensBeforeTime(c, uid, now)
if err != nil {
log.BootErrorf("[user_data.ClearUserTokens] failed to delete tokens of user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.ClearUserTokens] failed to delete tokens of user \"%s\", because %s", username, err.Error())
return err
}
@@ -381,23 +380,23 @@ func (l *UserDataCli) ClearUserTokens(c *cli.Context, username string) error {
}
// DisableUserTwoFactorAuthorization disables 2fa for the specified user
func (l *UserDataCli) DisableUserTwoFactorAuthorization(c *cli.Context, username string) error {
func (l *UserDataCli) DisableUserTwoFactorAuthorization(c *core.CliContext, username string) error {
if username == "" {
log.BootErrorf("[user_data.DisableUserTwoFactorAuthorization] user name is empty")
log.BootErrorf(c, "[user_data.DisableUserTwoFactorAuthorization] user name is empty")
return errs.ErrUsernameIsEmpty
}
uid, err := l.getUserIdByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.DisableUserTwoFactorAuthorization] error occurs when getting user id by user name")
log.BootErrorf(c, "[user_data.DisableUserTwoFactorAuthorization] error occurs when getting user id by user name")
return err
}
enableTwoFactor, err := l.twoFactorAuthorizations.ExistsTwoFactorSetting(nil, uid)
enableTwoFactor, err := l.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
if err != nil {
log.BootErrorf("[user_data.DisableUserTwoFactorAuthorization] failed to check two-factor setting, because %s", err.Error())
log.BootErrorf(c, "[user_data.DisableUserTwoFactorAuthorization] failed to check two-factor setting, because %s", err.Error())
return err
}
@@ -405,17 +404,17 @@ func (l *UserDataCli) DisableUserTwoFactorAuthorization(c *cli.Context, username
return errs.ErrTwoFactorIsNotEnabled
}
err = l.twoFactorAuthorizations.DeleteTwoFactorRecoveryCodes(nil, uid)
err = l.twoFactorAuthorizations.DeleteTwoFactorRecoveryCodes(c, uid)
if err != nil {
log.BootErrorf("[user_data.DisableUserTwoFactorAuthorization] failed to delete two-factor recovery codes for user \"%s\"", username)
log.BootErrorf(c, "[user_data.DisableUserTwoFactorAuthorization] failed to delete two-factor recovery codes for user \"%s\"", username)
return err
}
err = l.twoFactorAuthorizations.DeleteTwoFactorSetting(nil, uid)
err = l.twoFactorAuthorizations.DeleteTwoFactorSetting(c, uid)
if err != nil {
log.BootErrorf("[user_data.DisableUserTwoFactorAuthorization] failed to delete two-factor setting for user \"%s\"", username)
log.BootErrorf(c, "[user_data.DisableUserTwoFactorAuthorization] failed to delete two-factor setting for user \"%s\"", username)
return err
}
@@ -423,23 +422,23 @@ func (l *UserDataCli) DisableUserTwoFactorAuthorization(c *cli.Context, username
}
// CheckTransactionAndAccount checks whether all user transactions and all user accounts are correct
func (l *UserDataCli) CheckTransactionAndAccount(c *cli.Context, username string) (bool, error) {
func (l *UserDataCli) CheckTransactionAndAccount(c *core.CliContext, username string) (bool, error) {
if username == "" {
log.BootErrorf("[user_data.CheckTransactionAndAccount] user name is empty")
log.BootErrorf(c, "[user_data.CheckTransactionAndAccount] user name is empty")
return false, errs.ErrUsernameIsEmpty
}
uid, err := l.getUserIdByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.CheckTransactionAndAccount] error occurs when getting user id by user name")
log.BootErrorf(c, "[user_data.CheckTransactionAndAccount] error occurs when getting user id by user name")
return false, err
}
accountMap, categoryMap, tagMap, tagIndexes, tagIndexesMap, err := l.getUserEssentialData(uid, username)
accountMap, categoryMap, tagMap, tagIndexes, tagIndexesMap, err := l.getUserEssentialData(c, uid, username)
if err != nil {
log.BootErrorf("[user_data.CheckTransactionAndAccount] failed to get essential data for user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.CheckTransactionAndAccount] failed to get essential data for user \"%s\", because %s", username, err.Error())
return false, err
}
@@ -451,10 +450,10 @@ func (l *UserDataCli) CheckTransactionAndAccount(c *cli.Context, username string
}
}
allTransactions, err := l.transactions.GetAllTransactions(nil, uid, pageCountForGettingTransactions, false)
allTransactions, err := l.transactions.GetAllTransactions(c, uid, pageCountForGettingTransactions, false)
if err != nil {
log.BootErrorf("[user_data.CheckTransactionAndAccount] failed to all transactions for user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.CheckTransactionAndAccount] failed to all transactions for user \"%s\", because %s", username, err.Error())
return false, err
}
@@ -505,7 +504,7 @@ func (l *UserDataCli) CheckTransactionAndAccount(c *cli.Context, username string
} else if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_IN {
balance = balance + transaction.Amount
} else {
log.BootErrorf("[user_data.CheckTransactionAndAccount] transaction type of transaction \"id:%d\" is invalid", transaction.TransactionId)
log.BootErrorf(c, "[user_data.CheckTransactionAndAccount] transaction type of transaction \"id:%d\" is invalid", transaction.TransactionId)
return false, errs.ErrOperationFailed
}
@@ -520,12 +519,12 @@ func (l *UserDataCli) CheckTransactionAndAccount(c *cli.Context, username string
}
if !exists && account.Balance != 0 {
log.BootErrorf("[user_data.CheckTransactionAndAccount] account \"id:%d\" balance is not correct, expected balance is %d, but there is no transaction actually", account.AccountId, account.Balance)
log.BootErrorf(c, "[user_data.CheckTransactionAndAccount] account \"id:%d\" balance is not correct, expected balance is %d, but there is no transaction actually", account.AccountId, account.Balance)
return false, errs.ErrOperationFailed
}
if account.Balance != actualBalance {
log.BootErrorf("[user_data.CheckTransactionAndAccount] account \"id:%d\" balance is not correct, expected balance is %d, but actual balance is %d", account.AccountId, account.Balance, actualBalance)
log.BootErrorf(c, "[user_data.CheckTransactionAndAccount] account \"id:%d\" balance is not correct, expected balance is %d, but actual balance is %d", account.AccountId, account.Balance, actualBalance)
return false, errs.ErrOperationFailed
}
}
@@ -534,7 +533,7 @@ func (l *UserDataCli) CheckTransactionAndAccount(c *cli.Context, username string
_, exists := accountMap[accountId]
if !exists {
log.BootErrorf("[user_data.CheckTransactionAndAccount] account \"id:%d\" does not exist, but there are some transactions of this account actually, and actual balance is %d", accountId, actualBalance)
log.BootErrorf(c, "[user_data.CheckTransactionAndAccount] account \"id:%d\" does not exist, but there are some transactions of this account actually, and actual balance is %d", accountId, actualBalance)
return false, errs.ErrOperationFailed
}
}
@@ -543,7 +542,7 @@ func (l *UserDataCli) CheckTransactionAndAccount(c *cli.Context, username string
tagIndex := tagIndexes[i]
if tagIndex.TransactionTime < 1 {
log.BootErrorf("[user_data.CheckTransactionAndAccount] transaction tag index \"id:%d\" does not have transaction time", tagIndex.TagIndexId)
log.BootErrorf(c, "[user_data.CheckTransactionAndAccount] transaction tag index \"id:%d\" does not have transaction time", tagIndex.TagIndexId)
return false, errs.ErrOperationFailed
}
}
@@ -552,23 +551,23 @@ func (l *UserDataCli) CheckTransactionAndAccount(c *cli.Context, username string
}
// FixTransactionTagIndexWithTransactionTime fixes user transaction tag index data with transaction time
func (l *UserDataCli) FixTransactionTagIndexWithTransactionTime(c *cli.Context, username string) (bool, error) {
func (l *UserDataCli) FixTransactionTagIndexWithTransactionTime(c *core.CliContext, username string) (bool, error) {
if username == "" {
log.BootErrorf("[user_data.FixTransactionTagIndexWithTransactionTime] user name is empty")
log.BootErrorf(c, "[user_data.FixTransactionTagIndexWithTransactionTime] user name is empty")
return false, errs.ErrUsernameIsEmpty
}
uid, err := l.getUserIdByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.FixTransactionTagIndexWithTransactionTime] error occurs when getting user id by user name")
log.BootErrorf(c, "[user_data.FixTransactionTagIndexWithTransactionTime] error occurs when getting user id by user name")
return false, err
}
tagIndexes, err := l.tags.GetAllTagIdsOfAllTransactions(nil, uid)
tagIndexes, err := l.tags.GetAllTagIdsOfAllTransactions(c, uid)
if err != nil {
log.BootErrorf("[user_data.FixTransactionTagIndexWithTransactionTime] failed to get tag index for user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.FixTransactionTagIndexWithTransactionTime] failed to get tag index for user \"%s\", because %s", username, err.Error())
return false, err
}
@@ -583,14 +582,14 @@ func (l *UserDataCli) FixTransactionTagIndexWithTransactionTime(c *cli.Context,
}
if len(invalidTagIndexes) < 1 {
log.BootErrorf("[user_data.FixTransactionTagIndexWithTransactionTime] all user transaction tag index data has been checked, there is no problem with user data")
log.BootErrorf(c, "[user_data.FixTransactionTagIndexWithTransactionTime] all user transaction tag index data has been checked, there is no problem with user data")
return false, errs.ErrOperationFailed
}
allTransactions, err := l.transactions.GetAllTransactions(nil, uid, pageCountForGettingTransactions, false)
allTransactions, err := l.transactions.GetAllTransactions(c, uid, pageCountForGettingTransactions, false)
if err != nil {
log.BootErrorf("[user_data.FixTransactionTagIndexWithTransactionTime] failed to all transactions for user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.FixTransactionTagIndexWithTransactionTime] failed to all transactions for user \"%s\", because %s", username, err.Error())
return false, err
}
@@ -607,10 +606,10 @@ func (l *UserDataCli) FixTransactionTagIndexWithTransactionTime(c *cli.Context,
tagIndex.TransactionTime = transaction.TransactionTime
}
err = l.tags.ModifyTagIndexTransactionTime(nil, uid, invalidTagIndexes)
err = l.tags.ModifyTagIndexTransactionTime(c, uid, invalidTagIndexes)
if err != nil {
log.BootErrorf("[user_data.FixTransactionTagIndexWithTransactionTime] failed to update transaction tag index for user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.FixTransactionTagIndexWithTransactionTime] failed to update transaction tag index for user \"%s\", because %s", username, err.Error())
return false, err
}
@@ -618,30 +617,30 @@ func (l *UserDataCli) FixTransactionTagIndexWithTransactionTime(c *cli.Context,
}
// ExportTransaction returns csv file content according user all transactions
func (l *UserDataCli) ExportTransaction(c *cli.Context, username string, fileType string) ([]byte, error) {
func (l *UserDataCli) ExportTransaction(c *core.CliContext, username string, fileType string) ([]byte, error) {
if username == "" {
log.BootErrorf("[user_data.ExportTransaction] user name is empty")
log.BootErrorf(c, "[user_data.ExportTransaction] user name is empty")
return nil, errs.ErrUsernameIsEmpty
}
uid, err := l.getUserIdByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.ExportTransaction] error occurs when getting user id by user name")
log.BootErrorf(c, "[user_data.ExportTransaction] error occurs when getting user id by user name")
return nil, err
}
accountMap, categoryMap, tagMap, _, tagIndexesMap, err := l.getUserEssentialData(uid, username)
accountMap, categoryMap, tagMap, _, tagIndexesMap, err := l.getUserEssentialData(c, uid, username)
if err != nil {
log.BootErrorf("[user_data.ExportTransaction] failed to get essential data for user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.ExportTransaction] failed to get essential data for user \"%s\", because %s", username, err.Error())
return nil, err
}
allTransactions, err := l.transactions.GetAllTransactions(nil, uid, pageCountForDataExport, true)
allTransactions, err := l.transactions.GetAllTransactions(c, uid, pageCountForDataExport, true)
if err != nil {
log.BootErrorf("[user_data.ExportTransaction] failed to all transactions for user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.ExportTransaction] failed to all transactions for user \"%s\", because %s", username, err.Error())
return nil, err
}
@@ -656,61 +655,61 @@ func (l *UserDataCli) ExportTransaction(c *cli.Context, username string, fileTyp
result, err := dataExporter.ToExportedContent(uid, allTransactions, accountMap, categoryMap, tagMap, tagIndexesMap)
if err != nil {
log.BootErrorf("[user_data.ExportTransaction] failed to get csv format exported data for \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.ExportTransaction] failed to get csv format exported data for \"%s\", because %s", username, err.Error())
return nil, err
}
return result, nil
}
func (l *UserDataCli) getUserIdByUsername(c *cli.Context, username string) (int64, error) {
func (l *UserDataCli) getUserIdByUsername(c *core.CliContext, username string) (int64, error) {
user, err := l.GetUserByUsername(c, username)
if err != nil {
log.BootErrorf("[user_data.getUserIdByUsername] failed to get user by user name \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.getUserIdByUsername] failed to get user by user name \"%s\", because %s", username, err.Error())
return 0, err
}
return user.Uid, nil
}
func (l *UserDataCli) getUserEssentialData(uid int64, username string) (accountMap map[int64]*models.Account, categoryMap map[int64]*models.TransactionCategory, tagMap map[int64]*models.TransactionTag, tagIndexes []*models.TransactionTagIndex, tagIndexesMap map[int64][]int64, err error) {
func (l *UserDataCli) getUserEssentialData(c *core.CliContext, uid int64, username string) (accountMap map[int64]*models.Account, categoryMap map[int64]*models.TransactionCategory, tagMap map[int64]*models.TransactionTag, tagIndexes []*models.TransactionTagIndex, tagIndexesMap map[int64][]int64, err error) {
if uid <= 0 {
log.BootErrorf("[user_data.getUserEssentialData] user uid \"%d\" is invalid", uid)
log.BootErrorf(c, "[user_data.getUserEssentialData] user uid \"%d\" is invalid", uid)
return nil, nil, nil, nil, nil, errs.ErrUserIdInvalid
}
accounts, err := l.accounts.GetAllAccountsByUid(nil, uid)
accounts, err := l.accounts.GetAllAccountsByUid(c, uid)
if err != nil {
log.BootErrorf("[user_data.getUserEssentialData] failed to get accounts for user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.getUserEssentialData] failed to get accounts for user \"%s\", because %s", username, err.Error())
return nil, nil, nil, nil, nil, err
}
accountMap = l.accounts.GetAccountMapByList(accounts)
categories, err := l.categories.GetAllCategoriesByUid(nil, uid, 0, -1)
categories, err := l.categories.GetAllCategoriesByUid(c, uid, 0, -1)
if err != nil {
log.BootErrorf("[user_data.getUserEssentialData] failed to get categories for user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.getUserEssentialData] failed to get categories for user \"%s\", because %s", username, err.Error())
return nil, nil, nil, nil, nil, err
}
categoryMap = l.categories.GetCategoryMapByList(categories)
tags, err := l.tags.GetAllTagsByUid(nil, uid)
tags, err := l.tags.GetAllTagsByUid(c, uid)
if err != nil {
log.BootErrorf("[user_data.getUserEssentialData] failed to get tags for user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.getUserEssentialData] failed to get tags for user \"%s\", because %s", username, err.Error())
return nil, nil, nil, nil, nil, err
}
tagMap = l.tags.GetTagMapByList(tags)
tagIndexes, err = l.tags.GetAllTagIdsOfAllTransactions(nil, uid)
tagIndexes, err = l.tags.GetAllTagIdsOfAllTransactions(c, uid)
if err != nil {
log.BootErrorf("[user_data.getUserEssentialData] failed to get tag index for user \"%s\", because %s", username, err.Error())
log.BootErrorf(c, "[user_data.getUserEssentialData] failed to get tag index for user \"%s\", because %s", username, err.Error())
return nil, nil, nil, nil, nil, err
}
@@ -719,16 +718,16 @@ func (l *UserDataCli) getUserEssentialData(uid int64, username string) (accountM
return accountMap, categoryMap, tagMap, tagIndexes, tagIndexesMap, nil
}
func (l *UserDataCli) checkTransactionAccount(c *cli.Context, transaction *models.Transaction, accountMap map[int64]*models.Account, accountHasChild map[int64]bool) error {
func (l *UserDataCli) checkTransactionAccount(c *core.CliContext, transaction *models.Transaction, accountMap map[int64]*models.Account, accountHasChild map[int64]bool) error {
account, exists := accountMap[transaction.AccountId]
if !exists {
log.BootErrorf("[user_data.checkTransactionAccount] the account \"id:%d\" of transaction \"id:%d\" does not exist", transaction.AccountId, transaction.TransactionId)
log.BootErrorf(c, "[user_data.checkTransactionAccount] the account \"id:%d\" of transaction \"id:%d\" does not exist", transaction.AccountId, transaction.TransactionId)
return errs.ErrAccountNotFound
}
if account.ParentAccountId == models.LevelOneAccountParentId && accountHasChild[account.AccountId] {
log.BootErrorf("[user_data.checkTransactionAccount] the account \"id:%d\" of transaction \"id:%d\" is not a sub-account", transaction.AccountId, transaction.TransactionId)
log.BootErrorf(c, "[user_data.checkTransactionAccount] the account \"id:%d\" of transaction \"id:%d\" is not a sub-account", transaction.AccountId, transaction.TransactionId)
return errs.ErrOperationFailed
}
@@ -736,12 +735,12 @@ func (l *UserDataCli) checkTransactionAccount(c *cli.Context, transaction *model
relatedAccount, exists := accountMap[transaction.RelatedAccountId]
if !exists {
log.BootErrorf("[user_data.checkTransactionAccount] the related account \"id:%d\" of transaction \"id:%d\" does not exist", transaction.RelatedAccountId, transaction.TransactionId)
log.BootErrorf(c, "[user_data.checkTransactionAccount] the related account \"id:%d\" of transaction \"id:%d\" does not exist", transaction.RelatedAccountId, transaction.TransactionId)
return errs.ErrAccountNotFound
}
if relatedAccount.ParentAccountId == models.LevelOneAccountParentId && accountHasChild[relatedAccount.AccountId] {
log.BootErrorf("[user_data.checkTransactionAccount] the related account \"id:%d\" of transaction \"id:%d\" is not a sub-account", transaction.RelatedAccountId, transaction.TransactionId)
log.BootErrorf(c, "[user_data.checkTransactionAccount] the related account \"id:%d\" of transaction \"id:%d\" is not a sub-account", transaction.RelatedAccountId, transaction.TransactionId)
return errs.ErrOperationFailed
}
}
@@ -749,10 +748,10 @@ func (l *UserDataCli) checkTransactionAccount(c *cli.Context, transaction *model
return nil
}
func (l *UserDataCli) checkTransactionCategory(c *cli.Context, transaction *models.Transaction, categoryMap map[int64]*models.TransactionCategory) error {
func (l *UserDataCli) checkTransactionCategory(c *core.CliContext, transaction *models.Transaction, categoryMap map[int64]*models.TransactionCategory) error {
if transaction.Type == models.TRANSACTION_DB_TYPE_MODIFY_BALANCE {
if transaction.CategoryId > 0 {
log.BootErrorf("[user_data.checkTransactionCategory] transaction \"id:%d\" is balance modification transaction, but has category \"id:%d\"", transaction.TransactionId, transaction.CategoryId)
log.BootErrorf(c, "[user_data.checkTransactionCategory] transaction \"id:%d\" is balance modification transaction, but has category \"id:%d\"", transaction.TransactionId, transaction.CategoryId)
return errs.ErrBalanceModificationTransactionCannotSetCategory
} else {
return nil
@@ -762,19 +761,19 @@ func (l *UserDataCli) checkTransactionCategory(c *cli.Context, transaction *mode
category, exists := categoryMap[transaction.CategoryId]
if !exists {
log.BootErrorf("[user_data.checkTransactionCategory] the transaction category \"id:%d\" of transaction \"id:%d\" does not exist", transaction.CategoryId, transaction.TransactionId)
log.BootErrorf(c, "[user_data.checkTransactionCategory] the transaction category \"id:%d\" of transaction \"id:%d\" does not exist", transaction.CategoryId, transaction.TransactionId)
return errs.ErrTransactionCategoryNotFound
}
if category.ParentCategoryId == models.LevelOneTransactionParentId {
log.BootErrorf("[user_data.checkTransactionCategory] the transaction category \"id:%d\" of transaction \"id:%d\" is not a sub category", transaction.CategoryId, transaction.TransactionId)
log.BootErrorf(c, "[user_data.checkTransactionCategory] the transaction category \"id:%d\" of transaction \"id:%d\" is not a sub category", transaction.CategoryId, transaction.TransactionId)
return errs.ErrOperationFailed
}
return nil
}
func (l *UserDataCli) checkTransactionTag(c *cli.Context, transactionId int64, allTagIndexesMap map[int64][]int64, tagMap map[int64]*models.TransactionTag) error {
func (l *UserDataCli) checkTransactionTag(c *core.CliContext, transactionId int64, allTagIndexesMap map[int64][]int64, tagMap map[int64]*models.TransactionTag) error {
tagIndexes, exists := allTagIndexesMap[transactionId]
if !exists {
@@ -786,7 +785,7 @@ func (l *UserDataCli) checkTransactionTag(c *cli.Context, transactionId int64, a
tag, exists := tagMap[tagIndex]
if !exists {
log.BootErrorf("[user_data.checkTransactionTag] the transaction tag \"id:%d\" of transaction \"id:%d\" does not exist", tag.TagId, transactionId)
log.BootErrorf(c, "[user_data.checkTransactionTag] the transaction tag \"id:%d\" of transaction \"id:%d\" does not exist", tag.TagId, transactionId)
return errs.ErrTransactionTagNotFound
}
}
@@ -794,7 +793,7 @@ func (l *UserDataCli) checkTransactionTag(c *cli.Context, transactionId int64, a
return nil
}
func (l *UserDataCli) checkTransactionRelatedTransaction(c *cli.Context, transaction *models.Transaction, transactionMap map[int64]*models.Transaction, accountMap map[int64]*models.Account) error {
func (l *UserDataCli) checkTransactionRelatedTransaction(c *core.CliContext, transaction *models.Transaction, transactionMap map[int64]*models.Transaction, accountMap map[int64]*models.Account) error {
if transaction.Type != models.TRANSACTION_DB_TYPE_TRANSFER_OUT && transaction.Type != models.TRANSACTION_DB_TYPE_TRANSFER_IN {
return nil
}
@@ -802,22 +801,22 @@ func (l *UserDataCli) checkTransactionRelatedTransaction(c *cli.Context, transac
relatedTransaction, exists := transactionMap[transaction.RelatedId]
if !exists {
log.BootErrorf("[user_data.checkTransactionRelatedTransaction] the related transaction \"id:%d\" of transaction \"id:%d\" does not exist", transaction.RelatedId, transaction.TransactionId)
log.BootErrorf(c, "[user_data.checkTransactionRelatedTransaction] the related transaction \"id:%d\" of transaction \"id:%d\" does not exist", transaction.RelatedId, transaction.TransactionId)
return errs.ErrTransactionNotFound
}
if transaction.RelatedId != relatedTransaction.TransactionId || transaction.TransactionId != relatedTransaction.RelatedId {
log.BootErrorf("[user_data.checkTransactionRelatedTransaction] related ids of transaction \"id:%d\" and transaction \"id:%d\" are not equal", transaction.RelatedId, transaction.TransactionId)
log.BootErrorf(c, "[user_data.checkTransactionRelatedTransaction] related ids of transaction \"id:%d\" and transaction \"id:%d\" are not equal", transaction.RelatedId, transaction.TransactionId)
return errs.ErrOperationFailed
}
if transaction.RelatedAccountId != relatedTransaction.AccountId || transaction.AccountId != relatedTransaction.RelatedAccountId {
log.BootErrorf("[user_data.checkTransactionRelatedTransaction] related account ids of transaction \"id:%d\" and transaction \"id:%d\" are not equal", transaction.RelatedId, transaction.TransactionId)
log.BootErrorf(c, "[user_data.checkTransactionRelatedTransaction] related account ids of transaction \"id:%d\" and transaction \"id:%d\" are not equal", transaction.RelatedId, transaction.TransactionId)
return errs.ErrOperationFailed
}
if transaction.RelatedAccountAmount != relatedTransaction.Amount || transaction.Amount != relatedTransaction.RelatedAccountAmount {
log.BootErrorf("[user_data.checkTransactionRelatedTransaction] related amounts of transaction \"id:%d\" and transaction \"id:%d\" are not equal", transaction.RelatedId, transaction.TransactionId)
log.BootErrorf(c, "[user_data.checkTransactionRelatedTransaction] related amounts of transaction \"id:%d\" and transaction \"id:%d\" are not equal", transaction.RelatedId, transaction.TransactionId)
return errs.ErrOperationFailed
}
@@ -825,7 +824,7 @@ func (l *UserDataCli) checkTransactionRelatedTransaction(c *cli.Context, transac
relatedAccount := accountMap[transaction.RelatedAccountId]
if account.Currency == relatedAccount.Currency && transaction.Amount != transaction.RelatedAccountAmount {
log.BootWarnf("[user_data.checkTransactionRelatedTransaction] transfer-in amount and transfer-out amount of transaction \"id:%d\" are not equal", transaction.TransactionId)
log.BootWarnf(c, "[user_data.checkTransactionRelatedTransaction] transfer-in amount and transfer-out amount of transaction \"id:%d\" are not equal", transaction.TransactionId)
}
return nil
+3 -158
View File
@@ -1,161 +1,6 @@
package core
import (
"net"
"strconv"
"github.com/gin-gonic/gin"
"github.com/mayswind/ezbookkeeping/pkg/errs"
)
const requestIdFieldKey = "REQUEST_ID"
const textualTokenFieldKey = "TOKEN_STRING"
const tokenClaimsFieldKey = "TOKEN_CLAIMS"
const responseErrorFieldKey = "RESPONSE_ERROR"
// AcceptLanguageHeaderName represents the header name of accept language
const AcceptLanguageHeaderName = "Accept-Language"
// RemoteClientPortHeader represents the header name of remote client source port
const RemoteClientPortHeader = "X-Real-Port"
// ClientTimezoneOffsetHeaderName represents the header name of client timezone offset
const ClientTimezoneOffsetHeaderName = "X-Timezone-Offset"
// Context represents the request and response context
type Context struct {
*gin.Context
// DO NOT ADD ANY FIELD IN THIS CONTEXT, THIS CONTEXT IS JUST A WRAPPER
}
func (c *Context) ClientPort() uint16 {
remotePort := c.GetHeader(RemoteClientPortHeader)
if remotePort != "" {
remotePortNum, err := strconv.ParseInt(remotePort, 10, 32)
if err == nil {
return uint16(remotePortNum)
}
}
if c.Request == nil {
return 0
}
_, remotePort, err := net.SplitHostPort(c.Request.RemoteAddr)
if err != nil {
return 0
}
remotePortNum, err := strconv.ParseInt(remotePort, 10, 32)
if err != nil {
return 0
}
return uint16(remotePortNum)
}
// SetRequestId sets the given request id to context
func (c *Context) SetRequestId(requestId string) {
c.Set(requestIdFieldKey, requestId)
}
// GetRequestId returns the current request id
func (c *Context) GetRequestId() string {
requestId, exists := c.Get(requestIdFieldKey)
if !exists {
return ""
}
return requestId.(string)
}
// SetTextualToken sets the given user token to context
func (c *Context) SetTextualToken(token string) {
c.Set(textualTokenFieldKey, token)
}
// GetTextualToken returns the current user textual token
func (c *Context) GetTextualToken() string {
token, exists := c.Get(textualTokenFieldKey)
if !exists {
return ""
}
return token.(string)
}
// SetTokenClaims sets the given user token to context
func (c *Context) SetTokenClaims(claims *UserTokenClaims) {
c.Set(tokenClaimsFieldKey, claims)
}
// GetTokenClaims returns the current user token
func (c *Context) GetTokenClaims() *UserTokenClaims {
claims, exists := c.Get(tokenClaimsFieldKey)
if !exists {
return nil
}
return claims.(*UserTokenClaims)
}
// GetCurrentUid returns the current user uid by the current user token
func (c *Context) GetCurrentUid() int64 {
claims := c.GetTokenClaims()
if claims == nil {
return 0
}
return claims.Uid
}
// GetClientLocale returns the client locale name
func (c *Context) GetClientLocale() string {
value := c.GetHeader(AcceptLanguageHeaderName)
return value
}
// GetClientTimezoneOffset returns the client timezone offset
func (c *Context) GetClientTimezoneOffset() (int16, error) {
value := c.GetHeader(ClientTimezoneOffsetHeaderName)
offset, err := strconv.Atoi(value)
if err != nil {
return 0, err
}
return int16(offset), nil
}
// SetResponseError sets the response error
func (c *Context) SetResponseError(error *errs.Error) {
c.Set(responseErrorFieldKey, error)
}
// GetResponseError returns the response error
func (c *Context) GetResponseError() *errs.Error {
err, exists := c.Get(responseErrorFieldKey)
if !exists {
return nil
}
return err.(*errs.Error)
}
// WrapContext returns a context wrapped by this file
func WrapContext(ginCtx *gin.Context) *Context {
return &Context{
Context: ginCtx,
}
// Context is the base context of ezBookkeeping
type Context interface {
GetContextId() string
}
+22
View File
@@ -0,0 +1,22 @@
package core
import (
"github.com/urfave/cli/v2"
)
// CliContext represents the command-line context
type CliContext struct {
*cli.Context
}
// GetContextId returns the current context id
func (c *CliContext) GetContextId() string {
return ""
}
// WrapCliContext returns a context wrapped by this file
func WrapCilContext(cliCtx *cli.Context) *CliContext {
return &CliContext{
Context: cliCtx,
}
}
+37
View File
@@ -0,0 +1,37 @@
package core
import (
"context"
"strconv"
"strings"
"time"
)
// CronContext represents the cron job context
type CronContext struct {
context.Context
contextId string
}
// GetContextId returns the current context id
func (c *CronContext) GetContextId() string {
return c.contextId
}
// NewCronJobContext returns a new cron job context
func NewCronJobContext(cronJobName string) *CronContext {
return &CronContext{
Context: context.Background(),
contextId: generateNewRandomCronContextId(cronJobName),
}
}
func generateNewRandomCronContextId(cronJobName string) string {
var ret strings.Builder
ret.WriteString("cron-job-")
ret.WriteString(strings.ToLower(cronJobName))
ret.WriteRune('-')
ret.WriteString(strconv.FormatInt(time.Now().Unix(), 10))
return ret.String()
}
+22
View File
@@ -0,0 +1,22 @@
package core
import "context"
const nullContextId = "00000000-0000-0000-0000-00000000"
// NullContext represents the null context
type NullContext struct {
context.Context
}
// GetContextId returns the current context id
func (c *NullContext) GetContextId() string {
return nullContextId
}
// NewCronJobContext returns a new null context
func NewNullContext() *NullContext {
return &NullContext{
Context: context.Background(),
}
}
+161
View File
@@ -0,0 +1,161 @@
package core
import (
"net"
"strconv"
"github.com/gin-gonic/gin"
"github.com/mayswind/ezbookkeeping/pkg/errs"
)
const webContextRequestIdFieldKey = "REQUEST_ID"
const webContextTextualTokenFieldKey = "TOKEN_STRING"
const webContextTokenClaimsFieldKey = "TOKEN_CLAIMS"
const webContextResponseErrorFieldKey = "RESPONSE_ERROR"
// AcceptLanguageHeaderName represents the header name of accept language
const AcceptLanguageHeaderName = "Accept-Language"
// RemoteClientPortHeader represents the header name of remote client source port
const RemoteClientPortHeader = "X-Real-Port"
// ClientTimezoneOffsetHeaderName represents the header name of client timezone offset
const ClientTimezoneOffsetHeaderName = "X-Timezone-Offset"
// WebContext represents the request and response context
type WebContext struct {
*gin.Context
// DO NOT ADD ANY FIELD IN THIS CONTEXT, THIS CONTEXT IS JUST A WRAPPER
}
func (c *WebContext) ClientPort() uint16 {
remotePort := c.GetHeader(RemoteClientPortHeader)
if remotePort != "" {
remotePortNum, err := strconv.ParseInt(remotePort, 10, 32)
if err == nil {
return uint16(remotePortNum)
}
}
if c.Request == nil {
return 0
}
_, remotePort, err := net.SplitHostPort(c.Request.RemoteAddr)
if err != nil {
return 0
}
remotePortNum, err := strconv.ParseInt(remotePort, 10, 32)
if err != nil {
return 0
}
return uint16(remotePortNum)
}
// SetContextId sets the given request id to context
func (c *WebContext) SetContextId(requestId string) {
c.Set(webContextRequestIdFieldKey, requestId)
}
// GetContextId returns the current request id
func (c *WebContext) GetContextId() string {
requestId, exists := c.Get(webContextRequestIdFieldKey)
if !exists {
return ""
}
return requestId.(string)
}
// SetTextualToken sets the given user token to context
func (c *WebContext) SetTextualToken(token string) {
c.Set(webContextTextualTokenFieldKey, token)
}
// GetTextualToken returns the current user textual token
func (c *WebContext) GetTextualToken() string {
token, exists := c.Get(webContextTextualTokenFieldKey)
if !exists {
return ""
}
return token.(string)
}
// SetTokenClaims sets the given user token to context
func (c *WebContext) SetTokenClaims(claims *UserTokenClaims) {
c.Set(webContextTokenClaimsFieldKey, claims)
}
// GetTokenClaims returns the current user token
func (c *WebContext) GetTokenClaims() *UserTokenClaims {
claims, exists := c.Get(webContextTokenClaimsFieldKey)
if !exists {
return nil
}
return claims.(*UserTokenClaims)
}
// GetCurrentUid returns the current user uid by the current user token
func (c *WebContext) GetCurrentUid() int64 {
claims := c.GetTokenClaims()
if claims == nil {
return 0
}
return claims.Uid
}
// GetClientLocale returns the client locale name
func (c *WebContext) GetClientLocale() string {
value := c.GetHeader(AcceptLanguageHeaderName)
return value
}
// GetClientTimezoneOffset returns the client timezone offset
func (c *WebContext) GetClientTimezoneOffset() (int16, error) {
value := c.GetHeader(ClientTimezoneOffsetHeaderName)
offset, err := strconv.Atoi(value)
if err != nil {
return 0, err
}
return int16(offset), nil
}
// SetResponseError sets the response error
func (c *WebContext) SetResponseError(error *errs.Error) {
c.Set(webContextResponseErrorFieldKey, error)
}
// GetResponseError returns the response error
func (c *WebContext) GetResponseError() *errs.Error {
err, exists := c.Get(webContextResponseErrorFieldKey)
if !exists {
return nil
}
return err.(*errs.Error)
}
// WrapWebContext returns a context wrapped by this file
func WrapWebContext(ginCtx *gin.Context) *WebContext {
return &WebContext{
Context: ginCtx,
}
}
+8 -5
View File
@@ -6,17 +6,20 @@ import (
"github.com/mayswind/ezbookkeeping/pkg/errs"
)
// CliHandlerFunc represents the cli handler function
type CliHandlerFunc func(*CliContext) error
// MiddlewareHandlerFunc represents the middleware handler function
type MiddlewareHandlerFunc func(*Context)
type MiddlewareHandlerFunc func(*WebContext)
// ApiHandlerFunc represents the api handler function
type ApiHandlerFunc func(*Context) (any, *errs.Error)
type ApiHandlerFunc func(*WebContext) (any, *errs.Error)
// DataHandlerFunc represents the handler function that returns file data byte array and file name
type DataHandlerFunc func(*Context) ([]byte, string, *errs.Error)
type DataHandlerFunc func(*WebContext) ([]byte, string, *errs.Error)
// ImageHandlerFunc represents the handler function that returns image byte array and content type
type ImageHandlerFunc func(*Context) ([]byte, string, *errs.Error)
type ImageHandlerFunc func(*WebContext) ([]byte, string, *errs.Error)
// ProxyHandlerFunc represents the reverse proxy handler function
type ProxyHandlerFunc func(*Context) (*httputil.ReverseProxy, *errs.Error)
type ProxyHandlerFunc func(*WebContext) (*httputil.ReverseProxy, *errs.Error)
+9 -8
View File
@@ -5,6 +5,7 @@ import (
"github.com/go-co-op/gocron/v2"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/log"
"github.com/mayswind/ezbookkeeping/pkg/settings"
@@ -27,7 +28,7 @@ var (
)
// InitializeCronJobSchedulerContainer initializes the cron job scheduler according to the config
func InitializeCronJobSchedulerContainer(config *settings.Config, startScheduler bool) error {
func InitializeCronJobSchedulerContainer(ctx core.Context, config *settings.Config, startScheduler bool) error {
var err error
Container.scheduler, err = gocron.NewScheduler(
@@ -39,7 +40,7 @@ func InitializeCronJobSchedulerContainer(config *settings.Config, startScheduler
return err
}
Container.registerAllJobs(config)
Container.registerAllJobs(ctx, config)
if startScheduler {
Container.scheduler.Start()
@@ -75,13 +76,13 @@ func (c *CronJobSchedulerContainer) SyncRunJobNow(jobName string) error {
return nil
}
func (c *CronJobSchedulerContainer) registerAllJobs(config *settings.Config) {
func (c *CronJobSchedulerContainer) registerAllJobs(ctx core.Context, config *settings.Config) {
if config.EnableRemoveExpiredTokens {
Container.registerIntervalJob(RemoveExpiredTokensJob)
Container.registerIntervalJob(ctx, RemoveExpiredTokensJob)
}
}
func (c *CronJobSchedulerContainer) registerIntervalJob(job *CronJob) {
func (c *CronJobSchedulerContainer) registerIntervalJob(ctx core.Context, job *CronJob) {
gocronJob, err := c.scheduler.NewJob(
job.Period.ToJobDefinition(),
gocron.NewTask(job.doRun),
@@ -93,9 +94,9 @@ func (c *CronJobSchedulerContainer) registerIntervalJob(job *CronJob) {
c.allJobs = append(c.allJobs, job)
c.allJobsMap[job.Name] = job
c.allGocronJobsMap[job.Name] = gocronJob
log.Infof("[cron_container.registerJob] job \"%s\" has been registered", job.Name)
log.Debugf("[cron_container.registerJob] job \"%s\" gocron id is %s", job.Name, gocronJob.ID())
log.Infof(ctx, "[cron_container.registerJob] job \"%s\" has been registered", job.Name)
log.Debugf(ctx, "[cron_container.registerJob] job \"%s\" gocron id is %s", job.Name, gocronJob.ID())
} else {
log.Errorf("[cron_container.registerJob] job \"%s\" cannot be been registered, because %s", job.Name, err.Error())
log.Errorf(ctx, "[cron_container.registerJob] job \"%s\" cannot be been registered, because %s", job.Name, err.Error())
}
}
+11 -10
View File
@@ -8,6 +8,7 @@ import (
"github.com/go-co-op/gocron/v2"
"github.com/stretchr/testify/assert"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/duplicatechecker"
"github.com/mayswind/ezbookkeeping/pkg/settings"
)
@@ -33,13 +34,13 @@ func TestCronJobSchedulerContainerRegisterIntervalJob(t *testing.T) {
Period: CronJobIntervalPeriod{
Interval: 1 * time.Second,
},
Run: func() error {
Run: func(c *core.CronContext) error {
actualValue = true
return nil
},
}
container.registerIntervalJob(job)
container.registerIntervalJob(core.NewNullContext(), job)
container.scheduler.Start()
assert.Equal(t, 1, len(container.GetAllJobs()))
@@ -73,13 +74,13 @@ func TestCronJobSchedulerContainerSyncRunJobNow(t *testing.T) {
Period: CronJobIntervalPeriod{
Interval: 24 * time.Hour,
},
Run: func() error {
Run: func(c *core.CronContext) error {
actualValue = true
return nil
},
}
container.registerIntervalJob(job)
container.registerIntervalJob(core.NewNullContext(), job)
err = container.SyncRunJobNow("TestSyncRunJob")
assert.Nil(t, err)
@@ -115,17 +116,17 @@ func TestCronJobSchedulerContainerRepeatRun(t *testing.T) {
Period: CronJobFixedTimePeriod{
Time: runTime,
},
Run: func() error {
Run: func(c *core.CronContext) error {
runCount.Add(1)
return nil
},
}
container.registerIntervalJob(job)
container.registerIntervalJob(job)
container.registerIntervalJob(job)
container.registerIntervalJob(job)
container.registerIntervalJob(job)
container.registerIntervalJob(core.NewNullContext(), job)
container.registerIntervalJob(core.NewNullContext(), job)
container.registerIntervalJob(core.NewNullContext(), job)
container.registerIntervalJob(core.NewNullContext(), job)
container.registerIntervalJob(core.NewNullContext(), job)
container.scheduler.Start()
time.Sleep(10 * time.Second)
+10 -8
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"time"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/duplicatechecker"
"github.com/mayswind/ezbookkeeping/pkg/log"
"github.com/mayswind/ezbookkeeping/pkg/utils"
@@ -14,38 +15,39 @@ type CronJob struct {
Name string
Description string
Period CronJobPeriod
Run func() error
Run func(*core.CronContext) error
}
func (c *CronJob) doRun() {
func (j *CronJob) doRun() {
start := time.Now()
c := core.NewCronJobContext(j.Name)
if duplicatechecker.Container.Current != nil {
localAddr, err := utils.GetLocalIPAddressesString()
if err != nil {
log.Warnf("[cron_job.doRun] job \"%s\" cannot get local ipv4 address, because %s", c.Name, err.Error())
log.Warnf(c, "[cron_job.doRun] job \"%s\" cannot get local ipv4 address, because %s", j.Name, err.Error())
return
}
currentInfo := fmt.Sprintf("ip: %s, startTime: %d", localAddr, time.Now().Unix())
found, runningInfo := duplicatechecker.Container.GetOrSetCronJobRunningInfo(c.Name, currentInfo, c.Period.GetInterval())
found, runningInfo := duplicatechecker.Container.GetOrSetCronJobRunningInfo(j.Name, currentInfo, j.Period.GetInterval())
if found {
log.Warnf("[cron_job.doRun] job \"%s\" is already running (%s)", c.Name, runningInfo)
log.Warnf(c, "[cron_job.doRun] job \"%s\" is already running (%s)", j.Name, runningInfo)
return
}
}
err := c.Run()
err := j.Run(c)
now := time.Now()
if err != nil {
log.Errorf("[cron_job.doRun] failed to run job \"%s\", because %s", c.Name, err.Error())
log.Errorf(c, "[cron_job.doRun] failed to run job \"%s\", because %s", j.Name, err.Error())
return
}
cost := now.Sub(start).Nanoseconds() / 1e6
log.Infof("[cron_job.doRun] run job \"%s\" successfully, cost %dms", c.Name, cost)
log.Infof(c, "[cron_job.doRun] run job \"%s\" successfully, cost %dms", j.Name, cost)
}
@@ -6,6 +6,8 @@ import (
"github.com/go-co-op/gocron/v2"
"github.com/stretchr/testify/assert"
"github.com/mayswind/ezbookkeeping/pkg/core"
)
func TestCronJobNextRunTimeWithIntervalPeriod(t *testing.T) {
@@ -20,7 +22,7 @@ func TestCronJobNextRunTimeWithIntervalPeriod(t *testing.T) {
Period: CronJobIntervalPeriod{
Interval: 2*time.Hour + 34*time.Minute + 56*time.Second,
},
Run: func() error {
Run: func(c *core.CronContext) error {
return nil
},
}
@@ -64,7 +66,7 @@ func TestCronJobNextRunTimeWithFixedHourPeriod(t *testing.T) {
Period: CronJobFixedHourPeriod{
Hour: 0,
},
Run: func() error {
Run: func(c *core.CronContext) error {
return nil
},
}
@@ -109,7 +111,7 @@ func TestCronJobNextRunTimeWithFixedTimePeriod(t *testing.T) {
Period: CronJobFixedTimePeriod{
Time: expectedTime,
},
Run: func() error {
Run: func(c *core.CronContext) error {
return nil
},
}
+3 -2
View File
@@ -1,6 +1,7 @@
package cron
import (
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/services"
)
@@ -11,7 +12,7 @@ var RemoveExpiredTokensJob = &CronJob{
Period: CronJobFixedHourPeriod{
Hour: 0,
},
Run: func() error {
return services.Tokens.DeleteAllExpiredTokens(nil)
Run: func(c *core.CronContext) error {
return services.Tokens.DeleteAllExpiredTokens(c)
},
}
+5 -4
View File
@@ -3,6 +3,7 @@ package cron
import (
"github.com/go-co-op/gocron/v2"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/log"
)
@@ -12,22 +13,22 @@ type GocronLoggerAdapter struct {
// Debug logs debug log
func (logger GocronLoggerAdapter) Debug(msg string, args ...any) {
log.Debugf(msg, args...)
log.Debugf(core.NewNullContext(), msg, args...)
}
// Info logs info log
func (logger GocronLoggerAdapter) Info(msg string, args ...any) {
log.Infof(msg, args...)
log.Infof(core.NewNullContext(), msg, args...)
}
// Warn logs warn log
func (logger GocronLoggerAdapter) Warn(msg string, args ...any) {
log.Warnf(msg, args...)
log.Warnf(core.NewNullContext(), msg, args...)
}
// Error logs error log
func (logger GocronLoggerAdapter) Error(msg string, args ...any) {
log.Errorf(msg, args...)
log.Errorf(core.NewNullContext(), msg, args...)
}
// NewGocronLoggerAdapter returns a new GocronLoggerAdapter instance
+2 -2
View File
@@ -12,12 +12,12 @@ type Database struct {
}
// NewSession starts a new session with the specified context
func (db *Database) NewSession(c *core.Context) *xorm.Session {
func (db *Database) NewSession(c core.Context) *xorm.Session {
return db.engineGroup.Context(NewXOrmContextAdapter(c))
}
// DoTransaction runs a new database transaction
func (db *Database) DoTransaction(c *core.Context, fn func(sess *xorm.Session) error) (err error) {
func (db *Database) DoTransaction(c core.Context, fn func(sess *xorm.Session) error) (err error) {
sess := db.engineGroup.NewSession()
if c != nil {
+2 -2
View File
@@ -28,12 +28,12 @@ func (s *DataStore) Choose(key int64) *Database {
}
// Query returns a new database session in a specific database by sharding key
func (s *DataStore) Query(c *core.Context, key int64) *xorm.Session {
func (s *DataStore) Query(c core.Context, key int64) *xorm.Session {
return s.Choose(key).NewSession(c)
}
// DoTransaction runs a new database transaction in a specific database by sharding key
func (s *DataStore) DoTransaction(key int64, c *core.Context, fn func(sess *xorm.Session) error) (err error) {
func (s *DataStore) DoTransaction(key int64, c core.Context, fn func(sess *xorm.Session) error) (err error) {
return s.Choose(key).DoTransaction(c, fn)
}
+2 -2
View File
@@ -39,10 +39,10 @@ func (c *XOrmContextAdapter) Value(key any) any {
return nil
}
func NewXOrmContextAdapter(c *core.Context) *XOrmContextAdapter {
func NewXOrmContextAdapter(c core.Context) *XOrmContextAdapter {
if c != nil {
return &XOrmContextAdapter{
requestId: c.GetRequestId(),
requestId: c.GetContextId(),
}
}
@@ -36,9 +36,9 @@ type BankOfCanadaExchangeRateData struct {
type BankOfCanadaObservationData map[string]any
// ToLatestExchangeRateResponse returns a view-object according to original data from bank of Canada
func (e *BankOfCanadaExchangeRateData) ToLatestExchangeRateResponse(c *core.Context) *models.LatestExchangeRateResponse {
func (e *BankOfCanadaExchangeRateData) ToLatestExchangeRateResponse(c core.Context) *models.LatestExchangeRateResponse {
if len(e.Observations) < 1 {
log.ErrorfWithRequestId(c, "[bank_of_canada_datasource.ToLatestExchangeRateResponse] observations is empty")
log.Errorf(c, "[bank_of_canada_datasource.ToLatestExchangeRateResponse] observations is empty")
return nil
}
@@ -82,12 +82,12 @@ func (e *BankOfCanadaExchangeRateData) ToLatestExchangeRateResponse(c *core.Cont
rate, err := utils.StringToFloat64(exchangeRate)
if err != nil {
log.WarnfWithRequestId(c, "[bank_of_canada_datasource.ToLatestExchangeRateResponse] failed to parse rate, rate is %s", exchangeRate)
log.Warnf(c, "[bank_of_canada_datasource.ToLatestExchangeRateResponse] failed to parse rate, rate is %s", exchangeRate)
continue
}
if rate <= 0 {
log.WarnfWithRequestId(c, "[bank_of_canada_datasource.ToLatestExchangeRateResponse] rate is invalid, rate is %s", exchangeRate)
log.Warnf(c, "[bank_of_canada_datasource.ToLatestExchangeRateResponse] rate is invalid, rate is %s", exchangeRate)
continue
}
@@ -106,7 +106,7 @@ func (e *BankOfCanadaExchangeRateData) ToLatestExchangeRateResponse(c *core.Cont
timezone, err := time.LoadLocation(bankOfCanadaDataUpdateDateTimezone)
if err != nil {
log.ErrorfWithRequestId(c, "[bank_of_canada_datasource.ToLatestExchangeRateResponse] failed to get timezone, timezone name is %s", bankOfCanadaDataUpdateDateTimezone)
log.Errorf(c, "[bank_of_canada_datasource.ToLatestExchangeRateResponse] failed to get timezone, timezone name is %s", bankOfCanadaDataUpdateDateTimezone)
return nil
}
@@ -114,7 +114,7 @@ func (e *BankOfCanadaExchangeRateData) ToLatestExchangeRateResponse(c *core.Cont
updateTime, err := time.ParseInLocation(bankOfCanadaDataUpdateDateFormat, updateDateTime, timezone)
if err != nil {
log.ErrorfWithRequestId(c, "[bank_of_canada_datasource.ToLatestExchangeRateResponse] failed to parse update date, datetime is %s", updateDateTime)
log.Errorf(c, "[bank_of_canada_datasource.ToLatestExchangeRateResponse] failed to parse update date, datetime is %s", updateDateTime)
return nil
}
@@ -135,19 +135,19 @@ func (e *BankOfCanadaDataSource) GetRequestUrls() []string {
}
// Parse returns the common response entity according to the bank of Canada data source raw response
func (e *BankOfCanadaDataSource) Parse(c *core.Context, content []byte) (*models.LatestExchangeRateResponse, error) {
func (e *BankOfCanadaDataSource) Parse(c core.Context, content []byte) (*models.LatestExchangeRateResponse, error) {
bankOfCanadaData := &BankOfCanadaExchangeRateData{}
err := json.Unmarshal(content, bankOfCanadaData)
if err != nil {
log.ErrorfWithRequestId(c, "[bank_of_canada_datasource.Parse] failed to parse json data, content is %s, because %s", string(content), err.Error())
log.Errorf(c, "[bank_of_canada_datasource.Parse] failed to parse json data, content is %s, because %s", string(content), err.Error())
return nil, errs.ErrFailedToRequestRemoteApi
}
latestExchangeRateResponse := bankOfCanadaData.ToLatestExchangeRateResponse(c)
if latestExchangeRateResponse == nil {
log.ErrorfWithRequestId(c, "[bank_of_canada_datasource.Parse] failed to parse latest exchange rate data, content is %s", string(content))
log.Errorf(c, "[bank_of_canada_datasource.Parse] failed to parse latest exchange rate data, content is %s", string(content))
return nil, errs.ErrFailedToRequestRemoteApi
}
@@ -3,7 +3,6 @@ package exchangerates
import (
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/mayswind/ezbookkeeping/pkg/core"
@@ -32,9 +31,7 @@ const bankOfCanadaMinimumRequiredContent = "{\n" +
func TestBankOfCanadaDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
dataSource := &BankOfCanadaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(bankOfCanadaMinimumRequiredContent))
assert.Equal(t, nil, err)
@@ -43,9 +40,7 @@ func TestBankOfCanadaDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
func TestBankOfCanadaDataSource_StandardDataExtractExchangeRates(t *testing.T) {
dataSource := &BankOfCanadaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(bankOfCanadaMinimumRequiredContent))
assert.Equal(t, nil, err)
@@ -65,9 +60,7 @@ func TestBankOfCanadaDataSource_StandardDataExtractExchangeRates(t *testing.T) {
func TestBankOfCanadaDataSource_BlankContent(t *testing.T) {
dataSource := &BankOfCanadaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte(""))
assert.NotEqual(t, nil, err)
@@ -75,9 +68,7 @@ func TestBankOfCanadaDataSource_BlankContent(t *testing.T) {
func TestBankOfCanadaDataSource_EmptyJsonObject(t *testing.T) {
dataSource := &BankOfCanadaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("{}"))
assert.NotEqual(t, nil, err)
@@ -85,9 +76,7 @@ func TestBankOfCanadaDataSource_EmptyJsonObject(t *testing.T) {
func TestBankOfCanadaDataSource_EmptyObservationsContent(t *testing.T) {
dataSource := &BankOfCanadaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("{"+
" \"observations\": []"+
@@ -97,9 +86,7 @@ func TestBankOfCanadaDataSource_EmptyObservationsContent(t *testing.T) {
func TestBankOfCanadaDataSource_InvalidObservationFormat(t *testing.T) {
dataSource := &BankOfCanadaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
" \"observations\": [\n"+
@@ -117,9 +104,7 @@ func TestBankOfCanadaDataSource_InvalidObservationFormat(t *testing.T) {
func TestBankOfCanadaDataSource_InvalidObservationFormat2(t *testing.T) {
dataSource := &BankOfCanadaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
" \"observations\": [\n"+
@@ -137,9 +122,7 @@ func TestBankOfCanadaDataSource_InvalidObservationFormat2(t *testing.T) {
func TestBankOfCanadaDataSource_InvalidCurrency(t *testing.T) {
dataSource := &BankOfCanadaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
" \"observations\": [\n"+
@@ -157,9 +140,7 @@ func TestBankOfCanadaDataSource_InvalidCurrency(t *testing.T) {
func TestBankOfCanadaDataSource_EmptyRate(t *testing.T) {
dataSource := &BankOfCanadaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
" \"observations\": [\n"+
@@ -177,9 +158,7 @@ func TestBankOfCanadaDataSource_EmptyRate(t *testing.T) {
func TestBankOfCanadaDataSource_InvalidRate(t *testing.T) {
dataSource := &BankOfCanadaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
" \"observations\": [\n"+
@@ -33,18 +33,18 @@ func (e *CzechNationalBankDataSource) GetRequestUrls() []string {
}
// Parse returns the common response entity according to the czech nation bank data source raw response
func (e *CzechNationalBankDataSource) Parse(c *core.Context, content []byte) (*models.LatestExchangeRateResponse, error) {
func (e *CzechNationalBankDataSource) Parse(c core.Context, content []byte) (*models.LatestExchangeRateResponse, error) {
lines := strings.Split(string(content), "\n")
if len(lines) < 3 {
log.ErrorfWithRequestId(c, "[czech_national_bank_datasource.Parse] content is invalid, content is %s", string(content))
log.Errorf(c, "[czech_national_bank_datasource.Parse] content is invalid, content is %s", string(content))
return nil, errs.ErrFailedToRequestRemoteApi
}
headerLineItems := strings.Split(lines[0], "#")
if len(headerLineItems) != 2 {
log.ErrorfWithRequestId(c, "[czech_national_bank_datasource.Parse] first line of content is invalid, content is %s", lines[0])
log.Errorf(c, "[czech_national_bank_datasource.Parse] first line of content is invalid, content is %s", lines[0])
return nil, errs.ErrFailedToRequestRemoteApi
}
@@ -60,21 +60,21 @@ func (e *CzechNationalBankDataSource) Parse(c *core.Context, content []byte) (*m
currencyCodeColumnIndex, exists := titleItemMap["Code"]
if !exists {
log.ErrorfWithRequestId(c, "[czech_national_bank_datasource.Parse] missing currency code column in title line, title line is %s", lines[1])
log.Errorf(c, "[czech_national_bank_datasource.Parse] missing currency code column in title line, title line is %s", lines[1])
return nil, errs.ErrFailedToRequestRemoteApi
}
amountColumnIndex, exists := titleItemMap["Amount"]
if !exists {
log.ErrorfWithRequestId(c, "[czech_national_bank_datasource.Parse] missing amount column in title line, title line is %s", lines[1])
log.Errorf(c, "[czech_national_bank_datasource.Parse] missing amount column in title line, title line is %s", lines[1])
return nil, errs.ErrFailedToRequestRemoteApi
}
rateColumnIndex, exists := titleItemMap["Rate"]
if !exists {
log.ErrorfWithRequestId(c, "[czech_national_bank_datasource.Parse] missing rate column in title line, title line is %s", lines[1])
log.Errorf(c, "[czech_national_bank_datasource.Parse] missing rate column in title line, title line is %s", lines[1])
return nil, errs.ErrFailedToRequestRemoteApi
}
@@ -92,7 +92,7 @@ func (e *CzechNationalBankDataSource) Parse(c *core.Context, content []byte) (*m
timezone, err := time.LoadLocation(czechNationalBankDataUpdateDateTimezone)
if err != nil {
log.ErrorfWithRequestId(c, "[czech_national_bank_datasource.Parse] failed to get timezone, timezone name is %s", czechNationalBankDataUpdateDateTimezone)
log.Errorf(c, "[czech_national_bank_datasource.Parse] failed to get timezone, timezone name is %s", czechNationalBankDataUpdateDateTimezone)
return nil, errs.ErrFailedToRequestRemoteApi
}
@@ -100,7 +100,7 @@ func (e *CzechNationalBankDataSource) Parse(c *core.Context, content []byte) (*m
updateTime, err := time.ParseInLocation(czechNationalBankDataUpdateDateFormat, updateDateTime, timezone)
if err != nil {
log.ErrorfWithRequestId(c, "[czech_national_bank_datasource.Parse] failed to parse update date, datetime is %s", updateDateTime)
log.Errorf(c, "[czech_national_bank_datasource.Parse] failed to parse update date, datetime is %s", updateDateTime)
return nil, errs.ErrFailedToRequestRemoteApi
}
@@ -115,7 +115,7 @@ func (e *CzechNationalBankDataSource) Parse(c *core.Context, content []byte) (*m
return latestExchangeRateResp, nil
}
func (e *CzechNationalBankDataSource) parseExchangeRate(c *core.Context, line string, currencyCodeColumnIndex int, amountColumnIndex int, rateColumnIndex int) *models.LatestExchangeRate {
func (e *CzechNationalBankDataSource) parseExchangeRate(c core.Context, line string, currencyCodeColumnIndex int, amountColumnIndex int, rateColumnIndex int) *models.LatestExchangeRate {
if len(line) < 1 {
return nil
}
@@ -123,7 +123,7 @@ func (e *CzechNationalBankDataSource) parseExchangeRate(c *core.Context, line st
items := strings.Split(line, "|")
if currencyCodeColumnIndex >= len(items) || amountColumnIndex >= len(items) || rateColumnIndex >= len(items) {
log.WarnfWithRequestId(c, "[czech_national_bank_datasource.parseExchangeRate] missing column in data line, line is %s", line)
log.Warnf(c, "[czech_national_bank_datasource.parseExchangeRate] missing column in data line, line is %s", line)
return nil
}
@@ -136,19 +136,19 @@ func (e *CzechNationalBankDataSource) parseExchangeRate(c *core.Context, line st
amount, err := utils.StringToInt64(items[amountColumnIndex])
if err != nil {
log.WarnfWithRequestId(c, "[czech_national_bank_datasource.parseExchangeRate] failed to parse amount, line is %s", line)
log.Warnf(c, "[czech_national_bank_datasource.parseExchangeRate] failed to parse amount, line is %s", line)
return nil
}
rate, err := utils.StringToFloat64(items[rateColumnIndex])
if err != nil {
log.WarnfWithRequestId(c, "[czech_national_bank_datasource.parseExchangeRate] failed to parse rate, line is %s", line)
log.Warnf(c, "[czech_national_bank_datasource.parseExchangeRate] failed to parse rate, line is %s", line)
return nil
}
if rate <= 0 {
log.WarnfWithRequestId(c, "[czech_national_bank_datasource.parseExchangeRate] rate is invalid, line is %s", line)
log.Warnf(c, "[czech_national_bank_datasource.parseExchangeRate] rate is invalid, line is %s", line)
return nil
}
@@ -3,7 +3,6 @@ package exchangerates
import (
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/mayswind/ezbookkeeping/pkg/core"
@@ -17,9 +16,7 @@ const czechNationalBankMinimumRequiredContent = "01 Apr 2021 #64\n" +
func TestCzechNationalBankDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
dataSource := &CzechNationalBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(czechNationalBankMinimumRequiredContent))
assert.Equal(t, nil, err)
@@ -28,9 +25,7 @@ func TestCzechNationalBankDataSource_StandardDataExtractBaseCurrency(t *testing.
func TestCzechNationalBankDataSource_StandardDataExtractExchangeRates(t *testing.T) {
dataSource := &CzechNationalBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(czechNationalBankMinimumRequiredContent))
assert.Equal(t, nil, err)
@@ -46,9 +41,7 @@ func TestCzechNationalBankDataSource_StandardDataExtractExchangeRates(t *testing
func TestCzechNationalBankDataSource_BlankContent(t *testing.T) {
dataSource := &CzechNationalBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte(""))
assert.NotEqual(t, nil, err)
@@ -56,9 +49,7 @@ func TestCzechNationalBankDataSource_BlankContent(t *testing.T) {
func TestCzechNationalBankDataSource_OnlyHeader(t *testing.T) {
dataSource := &CzechNationalBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64"))
assert.NotEqual(t, nil, err)
@@ -66,9 +57,7 @@ func TestCzechNationalBankDataSource_OnlyHeader(t *testing.T) {
func TestCzechNationalBankDataSource_OnlyHeaderAndTitle(t *testing.T) {
dataSource := &CzechNationalBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
"Country|Currency|Amount|Code|Rate"))
@@ -77,9 +66,7 @@ func TestCzechNationalBankDataSource_OnlyHeaderAndTitle(t *testing.T) {
func TestCzechNationalBankDataSource_TitleMissingCode(t *testing.T) {
dataSource := &CzechNationalBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
"Country|Currency|Amount|Rate\n"+
@@ -90,9 +77,7 @@ func TestCzechNationalBankDataSource_TitleMissingCode(t *testing.T) {
func TestCzechNationalBankDataSource_TitleMissingRate(t *testing.T) {
dataSource := &CzechNationalBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
"Country|Currency|Amount|Code\n"+
@@ -103,9 +88,7 @@ func TestCzechNationalBankDataSource_TitleMissingRate(t *testing.T) {
func TestCzechNationalBankDataSource_InvalidCurrency(t *testing.T) {
dataSource := &CzechNationalBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
"Country|Currency|Amount|Code|Rate\n"+
@@ -116,9 +99,7 @@ func TestCzechNationalBankDataSource_InvalidCurrency(t *testing.T) {
func TestCzechNationalBankDataSource_EmptyRate(t *testing.T) {
dataSource := &CzechNationalBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
"Country|Currency|Amount|Code|Rate\n"+
@@ -129,9 +110,7 @@ func TestCzechNationalBankDataSource_EmptyRate(t *testing.T) {
func TestCzechNationalBankDataSource_InvalidRate(t *testing.T) {
dataSource := &CzechNationalBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
"Country|Currency|Amount|Code|Rate\n"+
@@ -44,16 +44,16 @@ type EuroCentralBankExchangeRate struct {
}
// ToLatestExchangeRateResponse returns a view-object according to original data from euro central bank
func (e *EuroCentralBankExchangeRateData) ToLatestExchangeRateResponse(c *core.Context) *models.LatestExchangeRateResponse {
func (e *EuroCentralBankExchangeRateData) ToLatestExchangeRateResponse(c core.Context) *models.LatestExchangeRateResponse {
if len(e.AllExchangeRates) < 1 {
log.ErrorfWithRequestId(c, "[euro_central_bank_datasource.ToLatestExchangeRateResponse] all exchange rates is empty")
log.Errorf(c, "[euro_central_bank_datasource.ToLatestExchangeRateResponse] all exchange rates is empty")
return nil
}
latestEuroCentralBankExchangeRate := e.AllExchangeRates[0]
if len(latestEuroCentralBankExchangeRate.ExchangeRates) < 1 {
log.ErrorfWithRequestId(c, "[euro_central_bank_datasource.ToLatestExchangeRateResponse] exchange rates is empty")
log.Errorf(c, "[euro_central_bank_datasource.ToLatestExchangeRateResponse] exchange rates is empty")
return nil
}
@@ -76,7 +76,7 @@ func (e *EuroCentralBankExchangeRateData) ToLatestExchangeRateResponse(c *core.C
timezone, err := time.LoadLocation(euroCentralBankDataUpdateDateTimezone)
if err != nil {
log.ErrorfWithRequestId(c, "[euro_central_bank_datasource.ToLatestExchangeRateResponse] failed to get timezone, timezone name is %s", euroCentralBankDataUpdateDateTimezone)
log.Errorf(c, "[euro_central_bank_datasource.ToLatestExchangeRateResponse] failed to get timezone, timezone name is %s", euroCentralBankDataUpdateDateTimezone)
return nil
}
@@ -84,7 +84,7 @@ func (e *EuroCentralBankExchangeRateData) ToLatestExchangeRateResponse(c *core.C
updateTime, err := time.ParseInLocation(euroCentralBankDataUpdateDateFormat, updateDateTime, timezone)
if err != nil {
log.ErrorfWithRequestId(c, "[euro_central_bank_datasource.ToLatestExchangeRateResponse] failed to parse update date, datetime is %s", updateDateTime)
log.Errorf(c, "[euro_central_bank_datasource.ToLatestExchangeRateResponse] failed to parse update date, datetime is %s", updateDateTime)
return nil
}
@@ -113,19 +113,19 @@ func (e *EuroCentralBankDataSource) GetRequestUrls() []string {
}
// Parse returns the common response entity according to the euro central bank data source raw response
func (e *EuroCentralBankDataSource) Parse(c *core.Context, content []byte) (*models.LatestExchangeRateResponse, error) {
func (e *EuroCentralBankDataSource) Parse(c core.Context, content []byte) (*models.LatestExchangeRateResponse, error) {
euroCentralBankData := &EuroCentralBankExchangeRateData{}
err := xml.Unmarshal(content, euroCentralBankData)
if err != nil {
log.ErrorfWithRequestId(c, "[euro_central_bank_datasource.Parse] failed to parse xml data, content is %s, because %s", string(content), err.Error())
log.Errorf(c, "[euro_central_bank_datasource.Parse] failed to parse xml data, content is %s, because %s", string(content), err.Error())
return nil, errs.ErrFailedToRequestRemoteApi
}
latestExchangeRateResponse := euroCentralBankData.ToLatestExchangeRateResponse(c)
if latestExchangeRateResponse == nil {
log.ErrorfWithRequestId(c, "[euro_central_bank_datasource.Parse] failed to parse latest exchange rate data, content is %s", string(content))
log.Errorf(c, "[euro_central_bank_datasource.Parse] failed to parse latest exchange rate data, content is %s", string(content))
return nil, errs.ErrFailedToRequestRemoteApi
}
@@ -3,7 +3,6 @@ package exchangerates
import (
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/mayswind/ezbookkeeping/pkg/core"
@@ -22,9 +21,7 @@ const euroCentralBankMinimumRequiredContent = "<?xml version=\"1.0\" encoding=\"
func TestEuroCentralBankDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
dataSource := &EuroCentralBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(euroCentralBankMinimumRequiredContent))
assert.Equal(t, nil, err)
@@ -33,9 +30,7 @@ func TestEuroCentralBankDataSource_StandardDataExtractBaseCurrency(t *testing.T)
func TestEuroCentralBankDataSource_StandardDataExtractExchangeRates(t *testing.T) {
dataSource := &EuroCentralBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(euroCentralBankMinimumRequiredContent))
assert.Equal(t, nil, err)
@@ -51,9 +46,7 @@ func TestEuroCentralBankDataSource_StandardDataExtractExchangeRates(t *testing.T
func TestEuroCentralBankDataSource_BlankContent(t *testing.T) {
dataSource := &EuroCentralBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte(""))
assert.NotEqual(t, nil, err)
@@ -61,9 +54,7 @@ func TestEuroCentralBankDataSource_BlankContent(t *testing.T) {
func TestEuroCentralBankDataSource_OnlyXMLHeader(t *testing.T) {
dataSource := &EuroCentralBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"))
assert.NotEqual(t, nil, err)
@@ -71,9 +62,7 @@ func TestEuroCentralBankDataSource_OnlyXMLHeader(t *testing.T) {
func TestEuroCentralBankDataSource_EmptyEnvelopeContent(t *testing.T) {
dataSource := &EuroCentralBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<gesmes:Envelope xmlns:gesmes=\"http://www.gesmes.org/xml/2002-08-01\" xmlns=\"http://www.ecb.int/vocabulary/2002-08-01/eurofxref\">"+
@@ -83,9 +72,7 @@ func TestEuroCentralBankDataSource_EmptyEnvelopeContent(t *testing.T) {
func TestEuroCentralBankDataSource_EmptyCubeContent(t *testing.T) {
dataSource := &EuroCentralBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<gesmes:Envelope xmlns:gesmes=\"http://www.gesmes.org/xml/2002-08-01\" xmlns=\"http://www.ecb.int/vocabulary/2002-08-01/eurofxref\">"+
@@ -97,9 +84,7 @@ func TestEuroCentralBankDataSource_EmptyCubeContent(t *testing.T) {
func TestEuroCentralBankDataSource_InvalidCurrency(t *testing.T) {
dataSource := &EuroCentralBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<gesmes:Envelope xmlns:gesmes=\"http://www.gesmes.org/xml/2002-08-01\" xmlns=\"http://www.ecb.int/vocabulary/2002-08-01/eurofxref\">"+
@@ -115,9 +100,7 @@ func TestEuroCentralBankDataSource_InvalidCurrency(t *testing.T) {
func TestEuroCentralBankDataSource_EmptyRate(t *testing.T) {
dataSource := &EuroCentralBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<gesmes:Envelope xmlns:gesmes=\"http://www.gesmes.org/xml/2002-08-01\" xmlns=\"http://www.ecb.int/vocabulary/2002-08-01/eurofxref\">"+
@@ -133,9 +116,7 @@ func TestEuroCentralBankDataSource_EmptyRate(t *testing.T) {
func TestEuroCentralBankDataSource_InvalidRate(t *testing.T) {
dataSource := &EuroCentralBankDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<gesmes:Envelope xmlns:gesmes=\"http://www.gesmes.org/xml/2002-08-01\" xmlns=\"http://www.ecb.int/vocabulary/2002-08-01/eurofxref\">"+
@@ -11,5 +11,5 @@ type ExchangeRatesDataSource interface {
GetRequestUrls() []string
// Parse returns the common response entity according to the data source raw response
Parse(c *core.Context, content []byte) (*models.LatestExchangeRateResponse, error)
Parse(c core.Context, content []byte) (*models.LatestExchangeRateResponse, error)
}
@@ -42,9 +42,9 @@ type NationalBankOfPolandExchangeRate struct {
}
// ToLatestExchangeRateResponse returns a view-object according to original data from National Bank of Poland
func (e *NationalBankOfPolandExchangeRateData) ToLatestExchangeRateResponse(c *core.Context) *models.LatestExchangeRateResponse {
func (e *NationalBankOfPolandExchangeRateData) ToLatestExchangeRateResponse(c core.Context) *models.LatestExchangeRateResponse {
if len(e.AllExchangeRates) < 1 {
log.ErrorfWithRequestId(c, "[national_bank_of_poland_datasource.ToLatestExchangeRateResponse] all exchange rates is empty")
log.Errorf(c, "[national_bank_of_poland_datasource.ToLatestExchangeRateResponse] all exchange rates is empty")
return nil
}
@@ -69,7 +69,7 @@ func (e *NationalBankOfPolandExchangeRateData) ToLatestExchangeRateResponse(c *c
timezone, err := time.LoadLocation(nationalBankOfPolandDataUpdateDateTimezone)
if err != nil {
log.ErrorfWithRequestId(c, "[national_bank_of_poland_datasource.ToLatestExchangeRateResponse] failed to get timezone, timezone name is %s", nationalBankOfPolandDataUpdateDateTimezone)
log.Errorf(c, "[national_bank_of_poland_datasource.ToLatestExchangeRateResponse] failed to get timezone, timezone name is %s", nationalBankOfPolandDataUpdateDateTimezone)
return nil
}
@@ -77,7 +77,7 @@ func (e *NationalBankOfPolandExchangeRateData) ToLatestExchangeRateResponse(c *c
updateTime, err := time.ParseInLocation(nationalBankOfPolandDataUpdateDateFormat, updateDateTime, timezone)
if err != nil {
log.ErrorfWithRequestId(c, "[national_bank_of_poland_datasource.ToLatestExchangeRateResponse] failed to parse update date, datetime is %s", updateDateTime)
log.Errorf(c, "[national_bank_of_poland_datasource.ToLatestExchangeRateResponse] failed to parse update date, datetime is %s", updateDateTime)
return nil
}
@@ -93,16 +93,16 @@ func (e *NationalBankOfPolandExchangeRateData) ToLatestExchangeRateResponse(c *c
}
// ToLatestExchangeRate returns a data pair according to original data from National Bank of Poland
func (e *NationalBankOfPolandExchangeRate) ToLatestExchangeRate(c *core.Context) *models.LatestExchangeRate {
func (e *NationalBankOfPolandExchangeRate) ToLatestExchangeRate(c core.Context) *models.LatestExchangeRate {
rate, err := utils.StringToFloat64(e.Rate)
if err != nil {
log.WarnfWithRequestId(c, "[national_bank_of_poland_datasource.ToLatestExchangeRate] failed to parse rate, currency is %s, rate is %s", e.Currency, e.Rate)
log.Warnf(c, "[national_bank_of_poland_datasource.ToLatestExchangeRate] failed to parse rate, currency is %s, rate is %s", e.Currency, e.Rate)
return nil
}
if rate <= 0 {
log.WarnfWithRequestId(c, "[national_bank_of_poland_datasource.ToLatestExchangeRate] rate is invalid, currency is %s, rate is %s", e.Currency, e.Rate)
log.Warnf(c, "[national_bank_of_poland_datasource.ToLatestExchangeRate] rate is invalid, currency is %s, rate is %s", e.Currency, e.Rate)
return nil
}
@@ -124,7 +124,7 @@ func (e *NationalBankOfPolandDataSource) GetRequestUrls() []string {
}
// Parse returns the common response entity according to the National Bank of Poland data source raw response
func (e *NationalBankOfPolandDataSource) Parse(c *core.Context, content []byte) (*models.LatestExchangeRateResponse, error) {
func (e *NationalBankOfPolandDataSource) Parse(c core.Context, content []byte) (*models.LatestExchangeRateResponse, error) {
nationalBankOfPolandData := &NationalBankOfPolandExchangeRateData{}
xmlDecoder := xml.NewDecoder(bytes.NewReader(content))
@@ -132,14 +132,14 @@ func (e *NationalBankOfPolandDataSource) Parse(c *core.Context, content []byte)
err := xmlDecoder.Decode(&nationalBankOfPolandData)
if err != nil {
log.ErrorfWithRequestId(c, "[national_bank_of_poland_datasource.Parse] failed to parse xml data, content is %s, because %s", string(content), err.Error())
log.Errorf(c, "[national_bank_of_poland_datasource.Parse] failed to parse xml data, content is %s, because %s", string(content), err.Error())
return nil, errs.ErrFailedToRequestRemoteApi
}
latestExchangeRateResponse := nationalBankOfPolandData.ToLatestExchangeRateResponse(c)
if latestExchangeRateResponse == nil {
log.ErrorfWithRequestId(c, "[national_bank_of_poland_datasource.Parse] failed to parse latest exchange rate data, content is %s", string(content))
log.Errorf(c, "[national_bank_of_poland_datasource.Parse] failed to parse latest exchange rate data, content is %s", string(content))
return nil, errs.ErrFailedToRequestRemoteApi
}
@@ -3,7 +3,6 @@ package exchangerates
import (
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/mayswind/ezbookkeeping/pkg/core"
@@ -29,9 +28,7 @@ const nationalBankOfPolandMinimumRequiredContent = "<?xml version=\"1.0\" encodi
func TestNationalBankOfPolandDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
dataSource := &NationalBankOfPolandDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(nationalBankOfPolandMinimumRequiredContent))
assert.Equal(t, nil, err)
@@ -40,9 +37,7 @@ func TestNationalBankOfPolandDataSource_StandardDataExtractBaseCurrency(t *testi
func TestNationalBankOfPolandDataSource_StandardDataExtractExchangeRates(t *testing.T) {
dataSource := &NationalBankOfPolandDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(nationalBankOfPolandMinimumRequiredContent))
assert.Equal(t, nil, err)
@@ -58,9 +53,7 @@ func TestNationalBankOfPolandDataSource_StandardDataExtractExchangeRates(t *test
func TestNationalBankOfPolandDataSource_BlankContent(t *testing.T) {
dataSource := &NationalBankOfPolandDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte(""))
assert.NotEqual(t, nil, err)
@@ -68,9 +61,7 @@ func TestNationalBankOfPolandDataSource_BlankContent(t *testing.T) {
func TestNationalBankOfPolandDataSource_OnlyXMLHeader(t *testing.T) {
dataSource := &NationalBankOfPolandDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>"))
assert.NotEqual(t, nil, err)
@@ -78,9 +69,7 @@ func TestNationalBankOfPolandDataSource_OnlyXMLHeader(t *testing.T) {
func TestNationalBankOfPolandDataSource_EmptyArrayOfExchangeRatesTable(t *testing.T) {
dataSource := &NationalBankOfPolandDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
"<ArrayOfExchangeRatesTable xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"+
@@ -90,9 +79,7 @@ func TestNationalBankOfPolandDataSource_EmptyArrayOfExchangeRatesTable(t *testin
func TestNationalBankOfPolandDataSource_EmptyExchangeRatesTable(t *testing.T) {
dataSource := &NationalBankOfPolandDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
"<ArrayOfExchangeRatesTable xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"+
@@ -104,9 +91,7 @@ func TestNationalBankOfPolandDataSource_EmptyExchangeRatesTable(t *testing.T) {
func TestNationalBankOfPolandDataSource_EmptyExchangeRatesContent(t *testing.T) {
dataSource := &NationalBankOfPolandDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
"<ArrayOfExchangeRatesTable xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"+
@@ -121,9 +106,7 @@ func TestNationalBankOfPolandDataSource_EmptyExchangeRatesContent(t *testing.T)
func TestNationalBankOfPolandDataSource_InvalidCurrency(t *testing.T) {
dataSource := &NationalBankOfPolandDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
"<ArrayOfExchangeRatesTable xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"+
@@ -143,9 +126,7 @@ func TestNationalBankOfPolandDataSource_InvalidCurrency(t *testing.T) {
func TestNationalBankOfPolandDataSource_EmptyRate(t *testing.T) {
dataSource := &NationalBankOfPolandDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
"<ArrayOfExchangeRatesTable xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"+
@@ -165,9 +146,7 @@ func TestNationalBankOfPolandDataSource_EmptyRate(t *testing.T) {
func TestNationalBankOfPolandDataSource_InvalidRate(t *testing.T) {
dataSource := &NationalBankOfPolandDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
"<ArrayOfExchangeRatesTable xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"+
@@ -60,14 +60,14 @@ type ReserveBankOfAustraliaExchangeRateObservation struct {
}
// ToLatestExchangeRateResponse returns a view-object according to original data from the reserve bank of Australia
func (e *ReserveBankOfAustraliaData) ToLatestExchangeRateResponse(c *core.Context) *models.LatestExchangeRateResponse {
func (e *ReserveBankOfAustraliaData) ToLatestExchangeRateResponse(c core.Context) *models.LatestExchangeRateResponse {
if e.Channel == nil {
log.ErrorfWithRequestId(c, "[reserve_bank_of_australia_datasource.ToLatestExchangeRateResponse] rss channel does not exist")
log.Errorf(c, "[reserve_bank_of_australia_datasource.ToLatestExchangeRateResponse] rss channel does not exist")
return nil
}
if len(e.Items) < 1 {
log.ErrorfWithRequestId(c, "[reserve_bank_of_australia_datasource.ToLatestExchangeRateResponse] rss items is empty")
log.Errorf(c, "[reserve_bank_of_australia_datasource.ToLatestExchangeRateResponse] rss items is empty")
return nil
}
@@ -99,7 +99,7 @@ func (e *ReserveBankOfAustraliaData) ToLatestExchangeRateResponse(c *core.Contex
updateTime, err := time.Parse(reserveBankOfAustraliaDataUpdateDateFormat, updateDateTime)
if err != nil {
log.ErrorfWithRequestId(c, "[reserve_bank_of_australia_datasource.ToLatestExchangeRateResponse] failed to parse update date, datetime is %s", updateDateTime)
log.Errorf(c, "[reserve_bank_of_australia_datasource.ToLatestExchangeRateResponse] failed to parse update date, datetime is %s", updateDateTime)
return nil
}
@@ -128,19 +128,19 @@ func (e *ReserveBankOfAustraliaDataSource) GetRequestUrls() []string {
}
// Parse returns the common response entity according to the the reserve bank of Australia data source raw response
func (e *ReserveBankOfAustraliaDataSource) Parse(c *core.Context, content []byte) (*models.LatestExchangeRateResponse, error) {
func (e *ReserveBankOfAustraliaDataSource) Parse(c core.Context, content []byte) (*models.LatestExchangeRateResponse, error) {
reserveBankOfAustraliaData := &ReserveBankOfAustraliaData{}
err := xml.Unmarshal(content, reserveBankOfAustraliaData)
if err != nil {
log.ErrorfWithRequestId(c, "[reserve_bank_of_australia_datasource.Parse] failed to parse xml data, content is %s, because %s", string(content), err.Error())
log.Errorf(c, "[reserve_bank_of_australia_datasource.Parse] failed to parse xml data, content is %s, because %s", string(content), err.Error())
return nil, errs.ErrFailedToRequestRemoteApi
}
latestExchangeRateResponse := reserveBankOfAustraliaData.ToLatestExchangeRateResponse(c)
if latestExchangeRateResponse == nil {
log.ErrorfWithRequestId(c, "[reserve_bank_of_australia_datasource.Parse] failed to parse latest exchange rate data, content is %s", string(content))
log.Errorf(c, "[reserve_bank_of_australia_datasource.Parse] failed to parse latest exchange rate data, content is %s", string(content))
return nil, errs.ErrFailedToRequestRemoteApi
}
@@ -3,7 +3,6 @@ package exchangerates
import (
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/mayswind/ezbookkeeping/pkg/core"
@@ -43,9 +42,7 @@ const reserveBankOfAustraliaMinimumRequiredContent = "<?xml version=\"1.0\" enco
func TestReserveBankOfAustraliaDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(reserveBankOfAustraliaMinimumRequiredContent))
assert.Equal(t, nil, err)
@@ -54,9 +51,7 @@ func TestReserveBankOfAustraliaDataSource_StandardDataExtractBaseCurrency(t *tes
func TestReserveBankOfAustraliaDataSource_StandardDataExtractExchangeRates(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(reserveBankOfAustraliaMinimumRequiredContent))
assert.Equal(t, nil, err)
@@ -72,9 +67,7 @@ func TestReserveBankOfAustraliaDataSource_StandardDataExtractExchangeRates(t *te
func TestReserveBankOfAustraliaDataSource_BlankContent(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte(""))
assert.NotEqual(t, nil, err)
@@ -82,9 +75,7 @@ func TestReserveBankOfAustraliaDataSource_BlankContent(t *testing.T) {
func TestReserveBankOfAustraliaDataSource_OnlyXMLHeader(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"))
assert.NotEqual(t, nil, err)
@@ -92,9 +83,7 @@ func TestReserveBankOfAustraliaDataSource_OnlyXMLHeader(t *testing.T) {
func TestReserveBankOfAustraliaDataSource_EmptyRDFContent(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:rba=\"https://www.rba.gov.au/statistics/frequency/exchange-rates.html\" xmlns:cb=\"http://www.cbwiki.net/wiki/index.php/Specification_1.2/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://purl.org/rss/1.0/\" xsi:schemaLocation=\"http://www.w3.org/1999/02/22-rdf-syntax-ns# rdf.xsd\">\n"+
@@ -104,9 +93,7 @@ func TestReserveBankOfAustraliaDataSource_EmptyRDFContent(t *testing.T) {
func TestReserveBankOfAustraliaDataSource_EmptyChannelContent(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:rba=\"https://www.rba.gov.au/statistics/frequency/exchange-rates.html\" xmlns:cb=\"http://www.cbwiki.net/wiki/index.php/Specification_1.2/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://purl.org/rss/1.0/\" xsi:schemaLocation=\"http://www.w3.org/1999/02/22-rdf-syntax-ns# rdf.xsd\">\n"+
@@ -130,9 +117,7 @@ func TestReserveBankOfAustraliaDataSource_EmptyChannelContent(t *testing.T) {
func TestReserveBankOfAustraliaDataSource_NoItem(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:rba=\"https://www.rba.gov.au/statistics/frequency/exchange-rates.html\" xmlns:cb=\"http://www.cbwiki.net/wiki/index.php/Specification_1.2/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://purl.org/rss/1.0/\" xsi:schemaLocation=\"http://www.w3.org/1999/02/22-rdf-syntax-ns# rdf.xsd\">\n"+
@@ -145,9 +130,7 @@ func TestReserveBankOfAustraliaDataSource_NoItem(t *testing.T) {
func TestReserveBankOfAustraliaDataSource_BaseCurrencyNotEqualPreset(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:rba=\"https://www.rba.gov.au/statistics/frequency/exchange-rates.html\" xmlns:cb=\"http://www.cbwiki.net/wiki/index.php/Specification_1.2/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://purl.org/rss/1.0/\" xsi:schemaLocation=\"http://www.w3.org/1999/02/22-rdf-syntax-ns# rdf.xsd\">\n"+
@@ -173,9 +156,7 @@ func TestReserveBankOfAustraliaDataSource_BaseCurrencyNotEqualPreset(t *testing.
func TestReserveBankOfAustraliaDataSource_UnitCurrencyNotEqualPreset(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:rba=\"https://www.rba.gov.au/statistics/frequency/exchange-rates.html\" xmlns:cb=\"http://www.cbwiki.net/wiki/index.php/Specification_1.2/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://purl.org/rss/1.0/\" xsi:schemaLocation=\"http://www.w3.org/1999/02/22-rdf-syntax-ns# rdf.xsd\">\n"+
@@ -201,9 +182,7 @@ func TestReserveBankOfAustraliaDataSource_UnitCurrencyNotEqualPreset(t *testing.
func TestReserveBankOfAustraliaDataSource_InvalidCurrency(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:rba=\"https://www.rba.gov.au/statistics/frequency/exchange-rates.html\" xmlns:cb=\"http://www.cbwiki.net/wiki/index.php/Specification_1.2/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://purl.org/rss/1.0/\" xsi:schemaLocation=\"http://www.w3.org/1999/02/22-rdf-syntax-ns# rdf.xsd\">\n"+
@@ -229,9 +208,7 @@ func TestReserveBankOfAustraliaDataSource_InvalidCurrency(t *testing.T) {
func TestReserveBankOfAustraliaDataSource_EmptyRate(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:rba=\"https://www.rba.gov.au/statistics/frequency/exchange-rates.html\" xmlns:cb=\"http://www.cbwiki.net/wiki/index.php/Specification_1.2/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://purl.org/rss/1.0/\" xsi:schemaLocation=\"http://www.w3.org/1999/02/22-rdf-syntax-ns# rdf.xsd\">\n"+
@@ -257,9 +234,7 @@ func TestReserveBankOfAustraliaDataSource_EmptyRate(t *testing.T) {
func TestReserveBankOfAustraliaDataSource_InvalidRate(t *testing.T) {
dataSource := &ReserveBankOfAustraliaDataSource{}
context := &core.Context{
Context: &gin.Context{},
}
context := core.NewNullContext()
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:rba=\"https://www.rba.gov.au/statistics/frequency/exchange-rates.html\" xmlns:cb=\"http://www.cbwiki.net/wiki/index.php/Specification_1.2/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://purl.org/rss/1.0/\" xsi:schemaLocation=\"http://www.w3.org/1999/02/22-rdf-syntax-ns# rdf.xsd\">\n"+
+1 -1
View File
@@ -41,7 +41,7 @@ func (f *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
b.WriteString("] ")
}
if requestId, exists := entry.Data[logFieldRequestId]; exists {
if requestId, exists := entry.Data[logFieldRequestId]; exists && requestId != "" {
b.WriteString(fmt.Sprintf("[%s] ", requestId))
}
+53 -42
View File
@@ -132,76 +132,87 @@ func SetLoggerConfiguration(config *settings.Config, isDisableBootLog bool) erro
return nil
}
// Debugf logs debug log with custom format
func Debugf(format string, args ...any) {
defaultLogger.Debug(getFinalLog(format, args...))
}
// DebugfWithRequestId logs debug log with custom format and request id
func DebugfWithRequestId(c *core.Context, format string, args ...any) {
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Debug(getFinalLog(format, args...))
// DebugfWithRequestId logs debug log with custom format
func Debugf(c core.Context, format string, args ...any) {
if c == nil {
defaultLogger.Debug(getFinalLog(format, args...))
} else {
defaultLogger.WithField(logFieldRequestId, c.GetContextId()).Debug(getFinalLog(format, args...))
}
}
// Infof logs info log with custom format
func Infof(format string, args ...any) {
defaultLogger.Info(getFinalLog(format, args...))
}
// InfofWithRequestId logs info log with custom format and request id
func InfofWithRequestId(c *core.Context, format string, args ...any) {
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Info(getFinalLog(format, args...))
func Infof(c core.Context, format string, args ...any) {
if c == nil {
defaultLogger.Info(getFinalLog(format, args...))
} else {
defaultLogger.WithField(logFieldRequestId, c.GetContextId()).Info(getFinalLog(format, args...))
}
}
// Warnf logs warn log with custom format
func Warnf(format string, args ...any) {
defaultLogger.Warn(getFinalLog(format, args...))
}
// WarnfWithRequestId logs warn log with custom format and request id
func WarnfWithRequestId(c *core.Context, format string, args ...any) {
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Warn(getFinalLog(format, args...))
func Warnf(c core.Context, format string, args ...any) {
if c == nil {
defaultLogger.Warn(getFinalLog(format, args...))
} else {
defaultLogger.WithField(logFieldRequestId, c.GetContextId()).Warn(getFinalLog(format, args...))
}
}
// Errorf logs error log with custom format
func Errorf(format string, args ...any) {
defaultLogger.Error(getFinalLog(format, args...))
func Errorf(c core.Context, format string, args ...any) {
if c == nil {
defaultLogger.Error(getFinalLog(format, args...))
} else {
defaultLogger.WithField(logFieldRequestId, c.GetContextId()).Error(getFinalLog(format, args...))
}
}
// ErrorfWithRequestId logs error log with custom format and request id
func ErrorfWithRequestId(c *core.Context, format string, args ...any) {
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Error(getFinalLog(format, args...))
}
// ErrorfWithRequestIdAndExtra logs error log with custom format and request id and extra info
func ErrorfWithRequestIdAndExtra(c *core.Context, extraString string, format string, args ...any) {
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).WithField(logFieldExtra, extraString).Error(getFinalLog(format, args...))
// ErrorfWithExtra logs error log with custom format and extra info
func ErrorfWithExtra(c core.Context, extraString string, format string, args ...any) {
if c == nil {
defaultLogger.WithField(logFieldExtra, extraString).Error(getFinalLog(format, args...))
} else {
defaultLogger.WithField(logFieldRequestId, c.GetContextId()).WithField(logFieldExtra, extraString).Error(getFinalLog(format, args...))
}
}
// BootInfof logs boot info log
func BootInfof(format string, args ...any) {
func BootInfof(c core.Context, format string, args ...any) {
if bootLogger != nil {
bootLogger.Info(getFinalLog(format, args...))
if c == nil {
bootLogger.Info(getFinalLog(format, args...))
} else {
bootLogger.WithField(logFieldRequestId, c.GetContextId()).Info(getFinalLog(format, args...))
}
}
}
// BootWarnf logs boot warn log
func BootWarnf(format string, args ...any) {
func BootWarnf(c core.Context, format string, args ...any) {
if bootLogger != nil {
bootLogger.Warn(getFinalLog(format, args...))
if c == nil {
bootLogger.Warn(getFinalLog(format, args...))
} else {
bootLogger.WithField(logFieldRequestId, c.GetContextId()).Warn(getFinalLog(format, args...))
}
}
}
// BootErrorf logs boot error log
func BootErrorf(format string, args ...any) {
func BootErrorf(c core.Context, format string, args ...any) {
if bootLogger != nil {
bootLogger.Error(getFinalLog(format, args...))
}
}
if c == nil {
bootLogger.Error(getFinalLog(format, args...))
} else {
bootLogger.WithField(logFieldRequestId, c.GetContextId()).Error(getFinalLog(format, args...))
}
}}
// Requestf logs http request log with custom format
func Requestf(c *core.Context, format string, args ...any) {
func Requestf(c core.Context, format string, args ...any) {
if requestLogger != nil {
requestLogger.WithField(logFieldRequestId, c.GetRequestId()).Info(getFinalLog(format, args...))
requestLogger.WithField(logFieldRequestId, c.GetContextId()).Info(getFinalLog(format, args...))
}
}
@@ -8,7 +8,7 @@ import (
const tokenCookieParam = "ebk_auth_token"
// AmapApiProxyAuthCookie adds amap api proxy auth cookie to cookies in response
func AmapApiProxyAuthCookie(c *core.Context, config *settings.Config) {
func AmapApiProxyAuthCookie(c *core.WebContext, config *settings.Config) {
token := c.GetTextualToken()
if token != "" {
+17 -17
View File
@@ -23,22 +23,22 @@ const (
const tokenQueryStringParam = "token"
// JWTAuthorization verifies whether current request is valid by jwt token in header
func JWTAuthorization(c *core.Context) {
func JWTAuthorization(c *core.WebContext) {
jwtAuthorization(c, TOKEN_SOURCE_TYPE_HEADER)
}
// JWTAuthorizationByQueryString verifies whether current request is valid by jwt token in query string
func JWTAuthorizationByQueryString(c *core.Context) {
func JWTAuthorizationByQueryString(c *core.WebContext) {
jwtAuthorization(c, TOKEN_SOURCE_TYPE_ARGUMENT)
}
// JWTAuthorizationByCookie verifies whether current request is valid by jwt token in cookie
func JWTAuthorizationByCookie(c *core.Context) {
func JWTAuthorizationByCookie(c *core.WebContext) {
jwtAuthorization(c, TOKEN_SOURCE_TYPE_COOKIE)
}
// JWTTwoFactorAuthorization verifies whether current request is valid by 2fa passcode
func JWTTwoFactorAuthorization(c *core.Context) {
func JWTTwoFactorAuthorization(c *core.WebContext) {
claims, err := getTokenClaims(c, TOKEN_SOURCE_TYPE_HEADER)
if err != nil {
@@ -47,7 +47,7 @@ func JWTTwoFactorAuthorization(c *core.Context) {
}
if claims.Type != core.USER_TOKEN_TYPE_REQUIRE_2FA {
log.WarnfWithRequestId(c, "[authorization.JWTTwoFactorAuthorization] user \"uid:%d\" token is not need two-factor authorization", claims.Uid)
log.Warnf(c, "[authorization.JWTTwoFactorAuthorization] user \"uid:%d\" token is not need two-factor authorization", claims.Uid)
utils.PrintJsonErrorResult(c, errs.ErrCurrentTokenNotRequire2FA)
return
}
@@ -57,7 +57,7 @@ func JWTTwoFactorAuthorization(c *core.Context) {
}
// JWTEmailVerifyAuthorization verifies whether current request is email verification
func JWTEmailVerifyAuthorization(c *core.Context) {
func JWTEmailVerifyAuthorization(c *core.WebContext) {
claims, err := getTokenClaims(c, TOKEN_SOURCE_TYPE_ARGUMENT)
if err != nil {
@@ -66,7 +66,7 @@ func JWTEmailVerifyAuthorization(c *core.Context) {
}
if claims.Type != core.USER_TOKEN_TYPE_EMAIL_VERIFY {
log.WarnfWithRequestId(c, "[authorization.JWTEmailVerifyAuthorization] user \"uid:%d\" token is not for email verification", claims.Uid)
log.Warnf(c, "[authorization.JWTEmailVerifyAuthorization] user \"uid:%d\" token is not for email verification", claims.Uid)
utils.PrintJsonErrorResult(c, errs.ErrCurrentInvalidToken)
return
}
@@ -76,7 +76,7 @@ func JWTEmailVerifyAuthorization(c *core.Context) {
}
// JWTResetPasswordAuthorization verifies whether current request is password reset
func JWTResetPasswordAuthorization(c *core.Context) {
func JWTResetPasswordAuthorization(c *core.WebContext) {
claims, err := getTokenClaims(c, TOKEN_SOURCE_TYPE_ARGUMENT)
if err != nil {
@@ -85,7 +85,7 @@ func JWTResetPasswordAuthorization(c *core.Context) {
}
if claims.Type != core.USER_TOKEN_TYPE_PASSWORD_RESET {
log.WarnfWithRequestId(c, "[authorization.JWTResetPasswordAuthorization] user \"uid:%d\" token is not for password request", claims.Uid)
log.Warnf(c, "[authorization.JWTResetPasswordAuthorization] user \"uid:%d\" token is not for password request", claims.Uid)
utils.PrintJsonErrorResult(c, errs.ErrCurrentInvalidToken)
return
}
@@ -94,7 +94,7 @@ func JWTResetPasswordAuthorization(c *core.Context) {
c.Next()
}
func jwtAuthorization(c *core.Context, source TokenSourceType) {
func jwtAuthorization(c *core.WebContext, source TokenSourceType) {
claims, err := getTokenClaims(c, source)
if err != nil {
@@ -103,13 +103,13 @@ func jwtAuthorization(c *core.Context, source TokenSourceType) {
}
if claims.Type == core.USER_TOKEN_TYPE_REQUIRE_2FA {
log.WarnfWithRequestId(c, "[authorization.jwtAuthorization] user \"uid:%d\" token requires 2fa", claims.Uid)
log.Warnf(c, "[authorization.jwtAuthorization] user \"uid:%d\" token requires 2fa", claims.Uid)
utils.PrintJsonErrorResult(c, errs.ErrCurrentTokenRequire2FA)
return
}
if claims.Type != core.USER_TOKEN_TYPE_NORMAL {
log.WarnfWithRequestId(c, "[authorization.jwtAuthorization] user \"uid:%d\" token type is invalid", claims.Uid)
log.Warnf(c, "[authorization.jwtAuthorization] user \"uid:%d\" token type is invalid", claims.Uid)
utils.PrintJsonErrorResult(c, errs.ErrCurrentInvalidTokenType)
return
}
@@ -118,28 +118,28 @@ func jwtAuthorization(c *core.Context, source TokenSourceType) {
c.Next()
}
func getTokenClaims(c *core.Context, source TokenSourceType) (*core.UserTokenClaims, *errs.Error) {
func getTokenClaims(c *core.WebContext, source TokenSourceType) (*core.UserTokenClaims, *errs.Error) {
token, claims, err := parseToken(c, source)
if err != nil {
log.WarnfWithRequestId(c, "[authorization.getTokenClaims] failed to parse token, because %s", err.Error())
log.Warnf(c, "[authorization.getTokenClaims] failed to parse token, because %s", err.Error())
return nil, errs.Or(err, errs.ErrUnauthorizedAccess)
}
if !token.Valid {
log.WarnfWithRequestId(c, "[authorization.getTokenClaims] token is invalid")
log.Warnf(c, "[authorization.getTokenClaims] token is invalid")
return nil, errs.ErrCurrentInvalidToken
}
if claims.Uid <= 0 {
log.WarnfWithRequestId(c, "[authorization.getTokenClaims] user id in token is invalid")
log.Warnf(c, "[authorization.getTokenClaims] user id in token is invalid")
return nil, errs.ErrCurrentInvalidToken
}
return claims, nil
}
func parseToken(c *core.Context, source TokenSourceType) (*jwt.Token, *core.UserTokenClaims, error) {
func parseToken(c *core.WebContext, source TokenSourceType) (*jwt.Token, *core.UserTokenClaims, error) {
if source == TOKEN_SOURCE_TYPE_ARGUMENT {
return services.Tokens.ParseTokenByArgument(c, tokenQueryStringParam)
} else if source == TOKEN_SOURCE_TYPE_COOKIE {
+2 -2
View File
@@ -20,12 +20,12 @@ var (
)
// Recovery logs error message when error occurs
func Recovery(c *core.Context) {
func Recovery(c *core.WebContext) {
defer func() {
if err := recover(); err != nil {
stack := stack(3)
log.ErrorfWithRequestIdAndExtra(c, string(stack), "System Error! because %s", err)
log.ErrorfWithExtra(c, string(stack), "System Error! because %s", err)
utils.PrintJsonErrorResult(c, errs.ErrSystemError)
}
}()
+2 -2
View File
@@ -10,14 +10,14 @@ const requestIdHeader = "X-Request-ID"
// RequestId generates a new request id and add it to context and response header
func RequestId(config *settings.Config) core.MiddlewareHandlerFunc {
return func(c *core.Context) {
return func(c *core.WebContext) {
if requestid.Container.Current == nil {
c.Next()
return
}
requestId := requestid.Container.Current.GenerateRequestId(c.ClientIP(), c.ClientPort())
c.SetRequestId(requestId)
c.SetContextId(requestId)
if config.EnableRequestIdHeader {
c.Header(requestIdHeader, requestId)
+1 -1
View File
@@ -9,7 +9,7 @@ import (
)
// RequestLog logs the http request log
func RequestLog(c *core.Context) {
func RequestLog(c *core.WebContext) {
start := time.Now()
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
+1 -1
View File
@@ -14,7 +14,7 @@ const settingsCookieName = "ebk_server_settings"
// ServerSettingsCookie adds server settings to cookies in response
func ServerSettingsCookie(config *settings.Config) core.MiddlewareHandlerFunc {
return func(c *core.Context) {
return func(c *core.WebContext) {
settingsArr := []string{
buildBooleanSetting("r", config.EnableUserRegister),
buildBooleanSetting("f", config.EnableUserForgetPassword),
@@ -10,6 +10,7 @@ import (
"sync/atomic"
"time"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/log"
"github.com/mayswind/ezbookkeeping/pkg/settings"
@@ -51,8 +52,8 @@ type DefaultRequestIdGenerator struct {
}
// NewDefaultRequestIdGenerator returns a new default request id generator
func NewDefaultRequestIdGenerator(config *settings.Config) (*DefaultRequestIdGenerator, error) {
serverUniqId, err := getServerUniqId(config)
func NewDefaultRequestIdGenerator(c core.Context, config *settings.Config) (*DefaultRequestIdGenerator, error) {
serverUniqId, err := getServerUniqId(c, config)
if err != nil {
return nil, err
@@ -68,7 +69,7 @@ func NewDefaultRequestIdGenerator(config *settings.Config) (*DefaultRequestIdGen
return generator, nil
}
func getServerUniqId(config *settings.Config) (uint16, error) {
func getServerUniqId(c core.Context, config *settings.Config) (uint16, error) {
localAddr := ""
settingAddr := net.ParseIP(config.HttpAddr)
@@ -79,7 +80,7 @@ func getServerUniqId(config *settings.Config) (uint16, error) {
localAddr, err = utils.GetLocalIPAddressesString()
if err != nil {
log.Warnf("[default_request_id_generator.getServerUniqId] failed to get local ipv4 address, because %s", err.Error())
log.Warnf(c, "[default_request_id_generator.getServerUniqId] failed to get local ipv4 address, because %s", err.Error())
return 0, err
}
}
@@ -5,11 +5,16 @@ import (
"github.com/stretchr/testify/assert"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/settings"
)
func TestNewDefaultRequestIdGenerator_Http(t *testing.T) {
generator, _ := NewDefaultRequestIdGenerator(&settings.Config{HttpAddr: "123.234.123.234", HttpPort: 8080, SecretKey: "secretkey"})
generator, _ := NewDefaultRequestIdGenerator(core.NewNullContext(), &settings.Config{
HttpAddr: "123.234.123.234",
HttpPort: 8080,
SecretKey: "secretkey",
})
requestId := generator.GenerateRequestId("127.0.0.1", 20000)
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
@@ -23,7 +28,12 @@ func TestNewDefaultRequestIdGenerator_Http(t *testing.T) {
}
func TestNewDefaultRequestIdGenerator_UnixSocket(t *testing.T) {
generator, _ := NewDefaultRequestIdGenerator(&settings.Config{HttpAddr: "1.2.3.4", UnixSocketPath: "/var/lib/ezbookkeeping/ezbookkeeping.sock", Protocol: "socket", SecretKey: "secretkey"})
generator, _ := NewDefaultRequestIdGenerator(core.NewNullContext(), &settings.Config{
HttpAddr: "1.2.3.4",
UnixSocketPath: "/var/lib/ezbookkeeping/ezbookkeeping.sock",
Protocol: "socket",
SecretKey: "secretkey",
})
requestId := generator.GenerateRequestId("127.0.0.1", 20000)
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
@@ -37,7 +47,12 @@ func TestNewDefaultRequestIdGenerator_UnixSocket(t *testing.T) {
}
func TestNewDefaultRequestIdGenerator_ClientIpv4(t *testing.T) {
generator, _ := NewDefaultRequestIdGenerator(&settings.Config{HttpAddr: "1.2.3.4", UnixSocketPath: "/var/lib/ezbookkeeping/ezbookkeeping.sock", Protocol: "socket", SecretKey: "secretkey"})
generator, _ := NewDefaultRequestIdGenerator(core.NewNullContext(), &settings.Config{
HttpAddr: "1.2.3.4",
UnixSocketPath: "/var/lib/ezbookkeeping/ezbookkeeping.sock",
Protocol: "socket",
SecretKey: "secretkey",
})
requestId := generator.GenerateRequestId("127.0.0.1", 20000)
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
@@ -62,7 +77,12 @@ func TestNewDefaultRequestIdGenerator_ClientIpv4(t *testing.T) {
}
func TestNewDefaultRequestIdGenerator_ClientIpv6(t *testing.T) {
generator, _ := NewDefaultRequestIdGenerator(&settings.Config{HttpAddr: "1.2.3.4", UnixSocketPath: "/var/lib/ezbookkeeping/ezbookkeeping.sock", Protocol: "socket", SecretKey: "secretkey"})
generator, _ := NewDefaultRequestIdGenerator(core.NewNullContext(), &settings.Config{
HttpAddr: "1.2.3.4",
UnixSocketPath: "/var/lib/ezbookkeeping/ezbookkeeping.sock",
Protocol: "socket",
SecretKey: "secretkey",
})
requestId := generator.GenerateRequestId("2001:abc:def:1234::1", 20000)
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
@@ -87,7 +107,12 @@ func TestNewDefaultRequestIdGenerator_ClientIpv6(t *testing.T) {
}
func TestNewDefaultRequestIdGenerator_ClientPort(t *testing.T) {
generator, _ := NewDefaultRequestIdGenerator(&settings.Config{HttpAddr: "1.2.3.4", UnixSocketPath: "/var/lib/ezbookkeeping/ezbookkeeping.sock", Protocol: "socket", SecretKey: "secretkey"})
generator, _ := NewDefaultRequestIdGenerator(core.NewNullContext(), &settings.Config{
HttpAddr: "1.2.3.4",
UnixSocketPath: "/var/lib/ezbookkeeping/ezbookkeeping.sock",
Protocol: "socket",
SecretKey: "secretkey",
})
requestId := generator.GenerateRequestId("127.0.0.1", 0)
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
@@ -132,7 +157,11 @@ func TestNewDefaultRequestIdGenerator_ClientPort(t *testing.T) {
}
func TestGenerateRequestId_100Times(t *testing.T) {
generator, _ := NewDefaultRequestIdGenerator(&settings.Config{HttpAddr: "1.2.3.4", HttpPort: 1234, SecretKey: "secretkey"})
generator, _ := NewDefaultRequestIdGenerator(core.NewNullContext(), &settings.Config{
HttpAddr: "1.2.3.4",
HttpPort: 1234,
SecretKey: "secretkey",
})
for i := 1; i <= 100; i++ {
requestId := generator.GenerateRequestId("127.0.0.1", 20000)
+3 -2
View File
@@ -1,6 +1,7 @@
package requestid
import (
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/settings"
)
@@ -15,8 +16,8 @@ var (
)
// InitializeRequestIdGenerator initializes the current request id generator according to the config
func InitializeRequestIdGenerator(config *settings.Config) error {
generator, err := NewDefaultRequestIdGenerator(config)
func InitializeRequestIdGenerator(c core.Context, config *settings.Config) error {
generator, err := NewDefaultRequestIdGenerator(c, config)
if err != nil {
return err
+13 -13
View File
@@ -33,7 +33,7 @@ var (
)
// GetTotalAccountCountByUid returns total account count of user
func (s *AccountService) GetTotalAccountCountByUid(c *core.Context, uid int64) (int64, error) {
func (s *AccountService) GetTotalAccountCountByUid(c core.Context, uid int64) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -44,7 +44,7 @@ func (s *AccountService) GetTotalAccountCountByUid(c *core.Context, uid int64) (
}
// GetAllAccountsByUid returns all account models of user
func (s *AccountService) GetAllAccountsByUid(c *core.Context, uid int64) ([]*models.Account, error) {
func (s *AccountService) GetAllAccountsByUid(c core.Context, uid int64) ([]*models.Account, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -56,7 +56,7 @@ func (s *AccountService) GetAllAccountsByUid(c *core.Context, uid int64) ([]*mod
}
// GetAccountAndSubAccountsByAccountId returns account model and sub-account models according to account id
func (s *AccountService) GetAccountAndSubAccountsByAccountId(c *core.Context, uid int64, accountId int64) ([]*models.Account, error) {
func (s *AccountService) GetAccountAndSubAccountsByAccountId(c core.Context, uid int64, accountId int64) ([]*models.Account, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -72,7 +72,7 @@ func (s *AccountService) GetAccountAndSubAccountsByAccountId(c *core.Context, ui
}
// GetSubAccountsByAccountId returns sub-account models according to account id
func (s *AccountService) GetSubAccountsByAccountId(c *core.Context, uid int64, accountId int64) ([]*models.Account, error) {
func (s *AccountService) GetSubAccountsByAccountId(c core.Context, uid int64, accountId int64) ([]*models.Account, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -88,7 +88,7 @@ func (s *AccountService) GetSubAccountsByAccountId(c *core.Context, uid int64, a
}
// GetSubAccountsByAccountIds returns sub-account models according to account ids
func (s *AccountService) GetSubAccountsByAccountIds(c *core.Context, uid int64, accountIds []int64) ([]*models.Account, error) {
func (s *AccountService) GetSubAccountsByAccountIds(c core.Context, uid int64, accountIds []int64) ([]*models.Account, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -130,7 +130,7 @@ func (s *AccountService) GetSubAccountsByAccountIds(c *core.Context, uid int64,
}
// GetAccountsByAccountIds returns account models according to account ids
func (s *AccountService) GetAccountsByAccountIds(c *core.Context, uid int64, accountIds []int64) (map[int64]*models.Account, error) {
func (s *AccountService) GetAccountsByAccountIds(c core.Context, uid int64, accountIds []int64) (map[int64]*models.Account, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -151,7 +151,7 @@ func (s *AccountService) GetAccountsByAccountIds(c *core.Context, uid int64, acc
}
// GetMaxDisplayOrder returns the max display order according to account category
func (s *AccountService) GetMaxDisplayOrder(c *core.Context, uid int64, category models.AccountCategory) (int32, error) {
func (s *AccountService) GetMaxDisplayOrder(c core.Context, uid int64, category models.AccountCategory) (int32, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -171,7 +171,7 @@ func (s *AccountService) GetMaxDisplayOrder(c *core.Context, uid int64, category
}
// GetMaxSubAccountDisplayOrder returns the max display order of sub-account according to account category and parent account id
func (s *AccountService) GetMaxSubAccountDisplayOrder(c *core.Context, uid int64, category models.AccountCategory, parentAccountId int64) (int32, error) {
func (s *AccountService) GetMaxSubAccountDisplayOrder(c core.Context, uid int64, category models.AccountCategory, parentAccountId int64) (int32, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -195,7 +195,7 @@ func (s *AccountService) GetMaxSubAccountDisplayOrder(c *core.Context, uid int64
}
// CreateAccounts saves a new account model to database
func (s *AccountService) CreateAccounts(c *core.Context, mainAccount *models.Account, childrenAccounts []*models.Account, utcOffset int16) error {
func (s *AccountService) CreateAccounts(c core.Context, mainAccount *models.Account, childrenAccounts []*models.Account, utcOffset int16) error {
if mainAccount.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -288,7 +288,7 @@ func (s *AccountService) CreateAccounts(c *core.Context, mainAccount *models.Acc
}
// ModifyAccounts saves an existed account model to database
func (s *AccountService) ModifyAccounts(c *core.Context, uid int64, accounts []*models.Account) error {
func (s *AccountService) ModifyAccounts(c core.Context, uid int64, accounts []*models.Account) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -316,7 +316,7 @@ func (s *AccountService) ModifyAccounts(c *core.Context, uid int64, accounts []*
}
// HideAccount updates hidden field of given accounts
func (s *AccountService) HideAccount(c *core.Context, uid int64, ids []int64, hidden bool) error {
func (s *AccountService) HideAccount(c core.Context, uid int64, ids []int64, hidden bool) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -342,7 +342,7 @@ func (s *AccountService) HideAccount(c *core.Context, uid int64, ids []int64, hi
}
// ModifyAccountDisplayOrders updates display order of given accounts
func (s *AccountService) ModifyAccountDisplayOrders(c *core.Context, uid int64, accounts []*models.Account) error {
func (s *AccountService) ModifyAccountDisplayOrders(c core.Context, uid int64, accounts []*models.Account) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -368,7 +368,7 @@ func (s *AccountService) ModifyAccountDisplayOrders(c *core.Context, uid int64,
}
// DeleteAccount deletes an existed account from database
func (s *AccountService) DeleteAccount(c *core.Context, uid int64, accountId int64) error {
func (s *AccountService) DeleteAccount(c core.Context, uid int64, accountId int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
+1 -1
View File
@@ -35,7 +35,7 @@ var (
)
// SendPasswordResetEmail sends password reset email according to specified parameters
func (s *ForgetPasswordService) SendPasswordResetEmail(c *core.Context, user *models.User, passwordResetToken string, backupLocale string) error {
func (s *ForgetPasswordService) SendPasswordResetEmail(c core.Context, user *models.User, passwordResetToken string, backupLocale string) error {
if !s.CurrentConfig().EnableSMTP {
return errs.ErrSMTPServerNotEnabled
}
+39 -29
View File
@@ -38,7 +38,7 @@ var (
)
// GetAllTokensByUid returns all token models of given user
func (s *TokenService) GetAllTokensByUid(c *core.Context, uid int64) ([]*models.TokenRecord, error) {
func (s *TokenService) GetAllTokensByUid(c core.Context, uid int64) ([]*models.TokenRecord, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -50,7 +50,7 @@ func (s *TokenService) GetAllTokensByUid(c *core.Context, uid int64) ([]*models.
}
// GetAllUnexpiredNormalTokensByUid returns all available token models of given user
func (s *TokenService) GetAllUnexpiredNormalTokensByUid(c *core.Context, uid int64) ([]*models.TokenRecord, error) {
func (s *TokenService) GetAllUnexpiredNormalTokensByUid(c core.Context, uid int64) ([]*models.TokenRecord, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -64,42 +64,52 @@ func (s *TokenService) GetAllUnexpiredNormalTokensByUid(c *core.Context, uid int
}
// ParseTokenByHeader returns the token model according to request data
func (s *TokenService) ParseTokenByHeader(c *core.Context) (*jwt.Token, *core.UserTokenClaims, error) {
func (s *TokenService) ParseTokenByHeader(c *core.WebContext) (*jwt.Token, *core.UserTokenClaims, error) {
return s.parseToken(c, request.BearerExtractor{})
}
// ParseTokenByArgument returns the token model according to request data
func (s *TokenService) ParseTokenByArgument(c *core.Context, tokenParameterName string) (*jwt.Token, *core.UserTokenClaims, error) {
func (s *TokenService) ParseTokenByArgument(c *core.WebContext, tokenParameterName string) (*jwt.Token, *core.UserTokenClaims, error) {
return s.parseToken(c, request.ArgumentExtractor{tokenParameterName})
}
// ParseTokenByCookie returns the token model according to request data
func (s *TokenService) ParseTokenByCookie(c *core.Context, tokenCookieName string) (*jwt.Token, *core.UserTokenClaims, error) {
func (s *TokenService) ParseTokenByCookie(c *core.WebContext, tokenCookieName string) (*jwt.Token, *core.UserTokenClaims, error) {
return s.parseToken(c, utils.CookieExtractor{tokenCookieName})
}
// CreateToken generates a new normal token and saves to database
func (s *TokenService) CreateToken(c *core.Context, user *models.User) (string, *core.UserTokenClaims, error) {
func (s *TokenService) CreateToken(c *core.WebContext, user *models.User) (string, *core.UserTokenClaims, error) {
return s.createToken(c, user, core.USER_TOKEN_TYPE_NORMAL, s.getUserAgent(c), s.CurrentConfig().TokenExpiredTimeDuration)
}
// CreateRequire2FAToken generates a new token requiring user to verify 2fa passcode and saves to database
func (s *TokenService) CreateRequire2FAToken(c *core.Context, user *models.User) (string, *core.UserTokenClaims, error) {
func (s *TokenService) CreateRequire2FAToken(c *core.WebContext, user *models.User) (string, *core.UserTokenClaims, error) {
return s.createToken(c, user, core.USER_TOKEN_TYPE_REQUIRE_2FA, s.getUserAgent(c), s.CurrentConfig().TemporaryTokenExpiredTimeDuration)
}
// CreateEmailVerifyToken generates a new email verify token and saves to database
func (s *TokenService) CreateEmailVerifyToken(c *core.Context, user *models.User) (string, *core.UserTokenClaims, error) {
func (s *TokenService) CreateEmailVerifyToken(c *core.WebContext, user *models.User) (string, *core.UserTokenClaims, error) {
return s.createToken(c, user, core.USER_TOKEN_TYPE_EMAIL_VERIFY, s.getUserAgent(c), s.CurrentConfig().EmailVerifyTokenExpiredTimeDuration)
}
// CreateEmailVerifyTokenWithoutUserAgent generates a new email verify token and saves to database
func (s *TokenService) CreateEmailVerifyTokenWithoutUserAgent(c core.Context, user *models.User) (string, *core.UserTokenClaims, error) {
return s.createToken(c, user, core.USER_TOKEN_TYPE_EMAIL_VERIFY, "", s.CurrentConfig().EmailVerifyTokenExpiredTimeDuration)
}
// CreatePasswordResetToken generates a new password reset token and saves to database
func (s *TokenService) CreatePasswordResetToken(c *core.Context, user *models.User) (string, *core.UserTokenClaims, error) {
func (s *TokenService) CreatePasswordResetToken(c *core.WebContext, user *models.User) (string, *core.UserTokenClaims, error) {
return s.createToken(c, user, core.USER_TOKEN_TYPE_PASSWORD_RESET, s.getUserAgent(c), s.CurrentConfig().PasswordResetTokenExpiredTimeDuration)
}
// CreatePasswordResetTokenWithoutUserAgent generates a new password reset token and saves to database
func (s *TokenService) CreatePasswordResetTokenWithoutUserAgent(c core.Context, user *models.User) (string, *core.UserTokenClaims, error) {
return s.createToken(c, user, core.USER_TOKEN_TYPE_PASSWORD_RESET, "", s.CurrentConfig().PasswordResetTokenExpiredTimeDuration)
}
// UpdateTokenLastSeen updates the last seen time of specified token
func (s *TokenService) UpdateTokenLastSeen(c *core.Context, tokenRecord *models.TokenRecord) error {
func (s *TokenService) UpdateTokenLastSeen(c core.Context, tokenRecord *models.TokenRecord) error {
if tokenRecord.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -124,7 +134,7 @@ func (s *TokenService) UpdateTokenLastSeen(c *core.Context, tokenRecord *models.
}
// DeleteToken deletes given token from database
func (s *TokenService) DeleteToken(c *core.Context, tokenRecord *models.TokenRecord) error {
func (s *TokenService) DeleteToken(c core.Context, tokenRecord *models.TokenRecord) error {
if tokenRecord.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -147,7 +157,7 @@ func (s *TokenService) DeleteToken(c *core.Context, tokenRecord *models.TokenRec
}
// DeleteTokens deletes given tokens from database
func (s *TokenService) DeleteTokens(c *core.Context, uid int64, tokenRecords []*models.TokenRecord) error {
func (s *TokenService) DeleteTokens(c core.Context, uid int64, tokenRecords []*models.TokenRecord) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -169,7 +179,7 @@ func (s *TokenService) DeleteTokens(c *core.Context, uid int64, tokenRecords []*
}
// DeleteTokenByClaims deletes given token from database
func (s *TokenService) DeleteTokenByClaims(c *core.Context, claims *core.UserTokenClaims) error {
func (s *TokenService) DeleteTokenByClaims(c core.Context, claims *core.UserTokenClaims) error {
userTokenId, err := utils.StringToInt64(claims.UserTokenId)
if err != nil {
@@ -184,7 +194,7 @@ func (s *TokenService) DeleteTokenByClaims(c *core.Context, claims *core.UserTok
}
// DeleteTokensBeforeTime deletes tokens that is created before specific time
func (s *TokenService) DeleteTokensBeforeTime(c *core.Context, uid int64, createTime int64) error {
func (s *TokenService) DeleteTokensBeforeTime(c core.Context, uid int64, createTime int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -196,7 +206,7 @@ func (s *TokenService) DeleteTokensBeforeTime(c *core.Context, uid int64, create
}
// DeleteTokensByType deletes specified type tokens
func (s *TokenService) DeleteTokensByType(c *core.Context, uid int64, tokenType core.TokenType) error {
func (s *TokenService) DeleteTokensByType(c core.Context, uid int64, tokenType core.TokenType) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -208,7 +218,7 @@ func (s *TokenService) DeleteTokensByType(c *core.Context, uid int64, tokenType
}
// DeleteAllExpiredTokens deletes all expired tokens
func (s *TokenService) DeleteAllExpiredTokens(c *core.Context) error {
func (s *TokenService) DeleteAllExpiredTokens(c core.Context) error {
var errors []error
totalCount := int64(0)
@@ -225,16 +235,16 @@ func (s *TokenService) DeleteAllExpiredTokens(c *core.Context) error {
}
if totalCount > 0 {
log.Infof("[tokens.DeleteAllExpiredTokens] %d expired tokens have been deleted", totalCount)
log.Infof(c, "[tokens.DeleteAllExpiredTokens] %d expired tokens have been deleted", totalCount)
} else if len(errors) == 0 {
log.Infof("[tokens.DeleteAllExpiredTokens] no expired tokens have been deleted")
log.Infof(c, "[tokens.DeleteAllExpiredTokens] no expired tokens have been deleted")
}
return errs.NewMultiErrorOrNil(errors...)
}
// ExistsValidTokenByType returns whether the given token type exists
func (s *TokenService) ExistsValidTokenByType(c *core.Context, uid int64, tokenType core.TokenType) (bool, error) {
func (s *TokenService) ExistsValidTokenByType(c core.Context, uid int64, tokenType core.TokenType) (bool, error) {
if uid <= 0 {
return false, errs.ErrUserIdInvalid
}
@@ -284,7 +294,7 @@ func (s *TokenService) GenerateTokenId(tokenRecord *models.TokenRecord) string {
return fmt.Sprintf("%d:%d:%d", tokenRecord.Uid, tokenRecord.CreatedUnixTime, tokenRecord.UserTokenId)
}
func (s *TokenService) parseToken(c *core.Context, extractor request.Extractor) (*jwt.Token, *core.UserTokenClaims, error) {
func (s *TokenService) parseToken(c *core.WebContext, extractor request.Extractor) (*jwt.Token, *core.UserTokenClaims, error) {
claims := &core.UserTokenClaims{}
token, err := request.ParseFromRequest(c.Request, extractor,
@@ -293,19 +303,19 @@ func (s *TokenService) parseToken(c *core.Context, extractor request.Extractor)
userTokenId, err := utils.StringToInt64(claims.UserTokenId)
if err != nil {
log.WarnfWithRequestId(c, "[tokens.ParseToken] token \"utid:%s\" in token of user \"uid:%d\" is invalid, because %s", claims.UserTokenId, claims.Uid, err.Error())
log.Warnf(c, "[tokens.ParseToken] token \"utid:%s\" in token of user \"uid:%d\" is invalid, because %s", claims.UserTokenId, claims.Uid, err.Error())
return nil, errs.ErrInvalidUserTokenId
}
tokenRecord, err := s.getTokenRecord(c, claims.Uid, userTokenId, claims.IssuedAt)
if err != nil {
log.WarnfWithRequestId(c, "[tokens.ParseToken] token \"utid:%s\" of user \"uid:%d\" record not found, because %s", claims.UserTokenId, claims.Uid, err.Error())
log.Warnf(c, "[tokens.ParseToken] token \"utid:%s\" of user \"uid:%d\" record not found, because %s", claims.UserTokenId, claims.Uid, err.Error())
return nil, errs.ErrTokenRecordNotFound
}
if tokenRecord.ExpiredUnixTime < now {
log.WarnfWithRequestId(c, "[tokens.ParseToken] token \"utid:%s\" of user \"uid:%d\" record is expired", claims.UserTokenId, claims.Uid)
log.Warnf(c, "[tokens.ParseToken] token \"utid:%s\" of user \"uid:%d\" record is expired", claims.UserTokenId, claims.Uid)
return nil, errs.ErrTokenExpired
}
@@ -321,7 +331,7 @@ func (s *TokenService) parseToken(c *core.Context, extractor request.Extractor)
}
if err == jwt.ErrTokenMalformed || err == jwt.ErrTokenUnverifiable || err == jwt.ErrTokenSignatureInvalid {
log.WarnfWithRequestId(c, "[tokens.ParseToken] token is invalid, because %s", err.Error())
log.Warnf(c, "[tokens.ParseToken] token is invalid, because %s", err.Error())
return nil, nil, errs.ErrCurrentInvalidToken
}
@@ -330,7 +340,7 @@ func (s *TokenService) parseToken(c *core.Context, extractor request.Extractor)
}
if err == jwt.ErrTokenUsedBeforeIssued {
log.WarnfWithRequestId(c, "[tokens.ParseToken] token is invalid, because issue time is later than now")
log.Warnf(c, "[tokens.ParseToken] token is invalid, because issue time is later than now")
return nil, nil, errs.ErrCurrentInvalidToken
}
@@ -340,7 +350,7 @@ func (s *TokenService) parseToken(c *core.Context, extractor request.Extractor)
return token, claims, err
}
func (s *TokenService) createToken(c *core.Context, user *models.User, tokenType core.TokenType, userAgent string, expiryDate time.Duration) (string, *core.UserTokenClaims, error) {
func (s *TokenService) createToken(c core.Context, user *models.User, tokenType core.TokenType, userAgent string, expiryDate time.Duration) (string, *core.UserTokenClaims, error) {
var err error
now := time.Now()
@@ -383,7 +393,7 @@ func (s *TokenService) createToken(c *core.Context, user *models.User, tokenType
return tokenString, claims, err
}
func (s *TokenService) getTokenRecord(c *core.Context, uid int64, userTokenId int64, createUnixTime int64) (*models.TokenRecord, error) {
func (s *TokenService) getTokenRecord(c core.Context, uid int64, userTokenId int64, createUnixTime int64) (*models.TokenRecord, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -406,7 +416,7 @@ func (s *TokenService) getTokenRecord(c *core.Context, uid int64, userTokenId in
return tokenRecord, nil
}
func (s *TokenService) createTokenRecord(c *core.Context, tokenRecord *models.TokenRecord) error {
func (s *TokenService) createTokenRecord(c core.Context, tokenRecord *models.TokenRecord) error {
if tokenRecord.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -429,7 +439,7 @@ func (s *TokenService) getUserTokenId() int64 {
return userTokenId
}
func (s *TokenService) getUserAgent(ctx *core.Context) string {
func (s *TokenService) getUserAgent(ctx *core.WebContext) string {
userAgent := ""
if ctx != nil && ctx.Request != nil {
+14 -14
View File
@@ -32,7 +32,7 @@ var (
)
// GetTotalCategoryCountByUid returns total category count of user
func (s *TransactionCategoryService) GetTotalCategoryCountByUid(c *core.Context, uid int64) (int64, error) {
func (s *TransactionCategoryService) GetTotalCategoryCountByUid(c core.Context, uid int64) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -43,7 +43,7 @@ func (s *TransactionCategoryService) GetTotalCategoryCountByUid(c *core.Context,
}
// GetAllCategoriesByUid returns all transaction category models of user
func (s *TransactionCategoryService) GetAllCategoriesByUid(c *core.Context, uid int64, categoryType models.TransactionCategoryType, parentCategoryId int64) ([]*models.TransactionCategory, error) {
func (s *TransactionCategoryService) GetAllCategoriesByUid(c core.Context, uid int64, categoryType models.TransactionCategoryType, parentCategoryId int64) ([]*models.TransactionCategory, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -70,7 +70,7 @@ func (s *TransactionCategoryService) GetAllCategoriesByUid(c *core.Context, uid
}
// GetSubCategoriesByCategoryIds returns sub-category models according to category ids
func (s *TransactionCategoryService) GetSubCategoriesByCategoryIds(c *core.Context, uid int64, categoryIds []int64) ([]*models.TransactionCategory, error) {
func (s *TransactionCategoryService) GetSubCategoriesByCategoryIds(c core.Context, uid int64, categoryIds []int64) ([]*models.TransactionCategory, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -112,7 +112,7 @@ func (s *TransactionCategoryService) GetSubCategoriesByCategoryIds(c *core.Conte
}
// GetCategoryByCategoryId returns a transaction category model according to transaction category id
func (s *TransactionCategoryService) GetCategoryByCategoryId(c *core.Context, uid int64, categoryId int64) (*models.TransactionCategory, error) {
func (s *TransactionCategoryService) GetCategoryByCategoryId(c core.Context, uid int64, categoryId int64) (*models.TransactionCategory, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -134,7 +134,7 @@ func (s *TransactionCategoryService) GetCategoryByCategoryId(c *core.Context, ui
}
// GetCategoriesByCategoryIds returns transaction category models according to transaction category ids
func (s *TransactionCategoryService) GetCategoriesByCategoryIds(c *core.Context, uid int64, categoryIds []int64) (map[int64]*models.TransactionCategory, error) {
func (s *TransactionCategoryService) GetCategoriesByCategoryIds(c core.Context, uid int64, categoryIds []int64) (map[int64]*models.TransactionCategory, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -155,7 +155,7 @@ func (s *TransactionCategoryService) GetCategoriesByCategoryIds(c *core.Context,
}
// GetMaxDisplayOrder returns the max display order according to transaction category type
func (s *TransactionCategoryService) GetMaxDisplayOrder(c *core.Context, uid int64, categoryType models.TransactionCategoryType) (int32, error) {
func (s *TransactionCategoryService) GetMaxDisplayOrder(c core.Context, uid int64, categoryType models.TransactionCategoryType) (int32, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -175,7 +175,7 @@ func (s *TransactionCategoryService) GetMaxDisplayOrder(c *core.Context, uid int
}
// GetMaxSubCategoryDisplayOrder returns the max display order of sub transaction category according to transaction category type and parent transaction category id
func (s *TransactionCategoryService) GetMaxSubCategoryDisplayOrder(c *core.Context, uid int64, categoryType models.TransactionCategoryType, parentCategoryId int64) (int32, error) {
func (s *TransactionCategoryService) GetMaxSubCategoryDisplayOrder(c core.Context, uid int64, categoryType models.TransactionCategoryType, parentCategoryId int64) (int32, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -199,7 +199,7 @@ func (s *TransactionCategoryService) GetMaxSubCategoryDisplayOrder(c *core.Conte
}
// CreateCategory saves a new transaction category model to database
func (s *TransactionCategoryService) CreateCategory(c *core.Context, category *models.TransactionCategory) error {
func (s *TransactionCategoryService) CreateCategory(c core.Context, category *models.TransactionCategory) error {
if category.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -221,7 +221,7 @@ func (s *TransactionCategoryService) CreateCategory(c *core.Context, category *m
}
// CreateCategories saves a few transaction category models to database
func (s *TransactionCategoryService) CreateCategories(c *core.Context, uid int64, categories map[*models.TransactionCategory][]*models.TransactionCategory) ([]*models.TransactionCategory, error) {
func (s *TransactionCategoryService) CreateCategories(c core.Context, uid int64, categories map[*models.TransactionCategory][]*models.TransactionCategory) ([]*models.TransactionCategory, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -284,7 +284,7 @@ func (s *TransactionCategoryService) CreateCategories(c *core.Context, uid int64
}
// ModifyCategory saves an existed transaction category model to database
func (s *TransactionCategoryService) ModifyCategory(c *core.Context, category *models.TransactionCategory) error {
func (s *TransactionCategoryService) ModifyCategory(c core.Context, category *models.TransactionCategory) error {
if category.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -305,7 +305,7 @@ func (s *TransactionCategoryService) ModifyCategory(c *core.Context, category *m
}
// HideCategory updates hidden field of given transaction categories
func (s *TransactionCategoryService) HideCategory(c *core.Context, uid int64, ids []int64, hidden bool) error {
func (s *TransactionCategoryService) HideCategory(c core.Context, uid int64, ids []int64, hidden bool) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -331,7 +331,7 @@ func (s *TransactionCategoryService) HideCategory(c *core.Context, uid int64, id
}
// ModifyCategoryDisplayOrders updates display order of given transaction categories
func (s *TransactionCategoryService) ModifyCategoryDisplayOrders(c *core.Context, uid int64, categories []*models.TransactionCategory) error {
func (s *TransactionCategoryService) ModifyCategoryDisplayOrders(c core.Context, uid int64, categories []*models.TransactionCategory) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -357,7 +357,7 @@ func (s *TransactionCategoryService) ModifyCategoryDisplayOrders(c *core.Context
}
// DeleteCategory deletes an existed transaction category from database
func (s *TransactionCategoryService) DeleteCategory(c *core.Context, uid int64, categoryId int64) error {
func (s *TransactionCategoryService) DeleteCategory(c core.Context, uid int64, categoryId int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -406,7 +406,7 @@ func (s *TransactionCategoryService) DeleteCategory(c *core.Context, uid int64,
}
// DeleteAllCategories deletes all existed transaction categories from database
func (s *TransactionCategoryService) DeleteAllCategories(c *core.Context, uid int64) error {
func (s *TransactionCategoryService) DeleteAllCategories(c core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
+16 -16
View File
@@ -33,7 +33,7 @@ var (
)
// GetTotalTagCountByUid returns total tag count of user
func (s *TransactionTagService) GetTotalTagCountByUid(c *core.Context, uid int64) (int64, error) {
func (s *TransactionTagService) GetTotalTagCountByUid(c core.Context, uid int64) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -44,7 +44,7 @@ func (s *TransactionTagService) GetTotalTagCountByUid(c *core.Context, uid int64
}
// GetAllTagsByUid returns all transaction tag models of user
func (s *TransactionTagService) GetAllTagsByUid(c *core.Context, uid int64) ([]*models.TransactionTag, error) {
func (s *TransactionTagService) GetAllTagsByUid(c core.Context, uid int64) ([]*models.TransactionTag, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -56,7 +56,7 @@ func (s *TransactionTagService) GetAllTagsByUid(c *core.Context, uid int64) ([]*
}
// GetTagByTagId returns a transaction tag model according to transaction tag id
func (s *TransactionTagService) GetTagByTagId(c *core.Context, uid int64, tagId int64) (*models.TransactionTag, error) {
func (s *TransactionTagService) GetTagByTagId(c core.Context, uid int64, tagId int64) (*models.TransactionTag, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -78,7 +78,7 @@ func (s *TransactionTagService) GetTagByTagId(c *core.Context, uid int64, tagId
}
// GetTagsByTagIds returns transaction tag models according to transaction tag ids
func (s *TransactionTagService) GetTagsByTagIds(c *core.Context, uid int64, tagIds []int64) (map[int64]*models.TransactionTag, error) {
func (s *TransactionTagService) GetTagsByTagIds(c core.Context, uid int64, tagIds []int64) (map[int64]*models.TransactionTag, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -99,7 +99,7 @@ func (s *TransactionTagService) GetTagsByTagIds(c *core.Context, uid int64, tagI
}
// GetMaxDisplayOrder returns the max display order
func (s *TransactionTagService) GetMaxDisplayOrder(c *core.Context, uid int64) (int32, error) {
func (s *TransactionTagService) GetMaxDisplayOrder(c core.Context, uid int64) (int32, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -119,7 +119,7 @@ func (s *TransactionTagService) GetMaxDisplayOrder(c *core.Context, uid int64) (
}
// GetAllTagIdsOfAllTransactions returns all transaction tag ids
func (s *TransactionTagService) GetAllTagIdsOfAllTransactions(c *core.Context, uid int64) ([]*models.TransactionTagIndex, error) {
func (s *TransactionTagService) GetAllTagIdsOfAllTransactions(c core.Context, uid int64) ([]*models.TransactionTagIndex, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -165,7 +165,7 @@ func (s *TransactionTagService) GetAllTagIdsOfAllTransactions(c *core.Context, u
}
// GetAllTagIdsMapOfAllTransactions returns all transaction tag ids map grouped by transaction id
func (s *TransactionTagService) GetAllTagIdsMapOfAllTransactions(c *core.Context, uid int64) (map[int64][]int64, error) {
func (s *TransactionTagService) GetAllTagIdsMapOfAllTransactions(c core.Context, uid int64) (map[int64][]int64, error) {
tagIndexes, err := s.GetAllTagIdsOfAllTransactions(c, uid)
if err != nil {
@@ -178,7 +178,7 @@ func (s *TransactionTagService) GetAllTagIdsMapOfAllTransactions(c *core.Context
}
// GetAllTagIdsOfTransactions returns transaction tag ids for given transactions
func (s *TransactionTagService) GetAllTagIdsOfTransactions(c *core.Context, uid int64, transactionIds []int64) (map[int64][]int64, error) {
func (s *TransactionTagService) GetAllTagIdsOfTransactions(c core.Context, uid int64, transactionIds []int64) (map[int64][]int64, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -192,7 +192,7 @@ func (s *TransactionTagService) GetAllTagIdsOfTransactions(c *core.Context, uid
}
// CreateTag saves a new transaction tag model to database
func (s *TransactionTagService) CreateTag(c *core.Context, tag *models.TransactionTag) error {
func (s *TransactionTagService) CreateTag(c core.Context, tag *models.TransactionTag) error {
if tag.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -222,7 +222,7 @@ func (s *TransactionTagService) CreateTag(c *core.Context, tag *models.Transacti
}
// ModifyTag saves an existed transaction tag model to database
func (s *TransactionTagService) ModifyTag(c *core.Context, tag *models.TransactionTag) error {
func (s *TransactionTagService) ModifyTag(c core.Context, tag *models.TransactionTag) error {
if tag.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -251,7 +251,7 @@ func (s *TransactionTagService) ModifyTag(c *core.Context, tag *models.Transacti
}
// HideTag updates hidden field of given transaction tags
func (s *TransactionTagService) HideTag(c *core.Context, uid int64, ids []int64, hidden bool) error {
func (s *TransactionTagService) HideTag(c core.Context, uid int64, ids []int64, hidden bool) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -277,7 +277,7 @@ func (s *TransactionTagService) HideTag(c *core.Context, uid int64, ids []int64,
}
// ModifyTagDisplayOrders updates display order of given transaction tags
func (s *TransactionTagService) ModifyTagDisplayOrders(c *core.Context, uid int64, tags []*models.TransactionTag) error {
func (s *TransactionTagService) ModifyTagDisplayOrders(c core.Context, uid int64, tags []*models.TransactionTag) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -303,7 +303,7 @@ func (s *TransactionTagService) ModifyTagDisplayOrders(c *core.Context, uid int6
}
// DeleteTag deletes an existed transaction tag from database
func (s *TransactionTagService) DeleteTag(c *core.Context, uid int64, tagId int64) error {
func (s *TransactionTagService) DeleteTag(c core.Context, uid int64, tagId int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -337,7 +337,7 @@ func (s *TransactionTagService) DeleteTag(c *core.Context, uid int64, tagId int6
}
// DeleteAllTags deletes all existed transaction tags from database
func (s *TransactionTagService) DeleteAllTags(c *core.Context, uid int64) error {
func (s *TransactionTagService) DeleteAllTags(c core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -369,7 +369,7 @@ func (s *TransactionTagService) DeleteAllTags(c *core.Context, uid int64) error
}
// ExistsTagName returns whether the given tag name exists
func (s *TransactionTagService) ExistsTagName(c *core.Context, uid int64, name string) (bool, error) {
func (s *TransactionTagService) ExistsTagName(c core.Context, uid int64, name string) (bool, error) {
if name == "" {
return false, errs.ErrTransactionTagNameIsEmpty
}
@@ -378,7 +378,7 @@ func (s *TransactionTagService) ExistsTagName(c *core.Context, uid int64, name s
}
// ModifyTagIndexTransactionTime updates transaction time of given transaction tag indexes
func (s *TransactionTagService) ModifyTagIndexTransactionTime(c *core.Context, uid int64, tagIndexes []*models.TransactionTagIndex) error {
func (s *TransactionTagService) ModifyTagIndexTransactionTime(c core.Context, uid int64, tagIndexes []*models.TransactionTagIndex) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
+10 -10
View File
@@ -30,7 +30,7 @@ var (
)
// GetTotalNormalTemplateCountByUid returns total template count of user
func (s *TransactionTemplateService) GetTotalNormalTemplateCountByUid(c *core.Context, uid int64) (int64, error) {
func (s *TransactionTemplateService) GetTotalNormalTemplateCountByUid(c core.Context, uid int64) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -41,7 +41,7 @@ func (s *TransactionTemplateService) GetTotalNormalTemplateCountByUid(c *core.Co
}
// GetAllTemplatesByUid returns all transaction template models of user
func (s *TransactionTemplateService) GetAllTemplatesByUid(c *core.Context, uid int64, templateType models.TransactionTemplateType) ([]*models.TransactionTemplate, error) {
func (s *TransactionTemplateService) GetAllTemplatesByUid(c core.Context, uid int64, templateType models.TransactionTemplateType) ([]*models.TransactionTemplate, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -53,7 +53,7 @@ func (s *TransactionTemplateService) GetAllTemplatesByUid(c *core.Context, uid i
}
// GetTemplateByTemplateId returns a transaction template model according to transaction template id
func (s *TransactionTemplateService) GetTemplateByTemplateId(c *core.Context, uid int64, templateId int64) (*models.TransactionTemplate, error) {
func (s *TransactionTemplateService) GetTemplateByTemplateId(c core.Context, uid int64, templateId int64) (*models.TransactionTemplate, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -75,7 +75,7 @@ func (s *TransactionTemplateService) GetTemplateByTemplateId(c *core.Context, ui
}
// GetMaxDisplayOrder returns the max display order
func (s *TransactionTemplateService) GetMaxDisplayOrder(c *core.Context, uid int64, templateType models.TransactionTemplateType) (int32, error) {
func (s *TransactionTemplateService) GetMaxDisplayOrder(c core.Context, uid int64, templateType models.TransactionTemplateType) (int32, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -95,7 +95,7 @@ func (s *TransactionTemplateService) GetMaxDisplayOrder(c *core.Context, uid int
}
// CreateTemplate saves a new transaction template model to database
func (s *TransactionTemplateService) CreateTemplate(c *core.Context, template *models.TransactionTemplate) error {
func (s *TransactionTemplateService) CreateTemplate(c core.Context, template *models.TransactionTemplate) error {
if template.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -117,7 +117,7 @@ func (s *TransactionTemplateService) CreateTemplate(c *core.Context, template *m
}
// ModifyTemplate saves an existed transaction template model to database
func (s *TransactionTemplateService) ModifyTemplate(c *core.Context, template *models.TransactionTemplate) error {
func (s *TransactionTemplateService) ModifyTemplate(c core.Context, template *models.TransactionTemplate) error {
if template.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -138,7 +138,7 @@ func (s *TransactionTemplateService) ModifyTemplate(c *core.Context, template *m
}
// HideTemplate updates hidden field of given transaction templates
func (s *TransactionTemplateService) HideTemplate(c *core.Context, uid int64, ids []int64, hidden bool) error {
func (s *TransactionTemplateService) HideTemplate(c core.Context, uid int64, ids []int64, hidden bool) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -164,7 +164,7 @@ func (s *TransactionTemplateService) HideTemplate(c *core.Context, uid int64, id
}
// ModifyTemplateDisplayOrders updates display order of given transaction templates
func (s *TransactionTemplateService) ModifyTemplateDisplayOrders(c *core.Context, uid int64, templates []*models.TransactionTemplate) error {
func (s *TransactionTemplateService) ModifyTemplateDisplayOrders(c core.Context, uid int64, templates []*models.TransactionTemplate) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -190,7 +190,7 @@ func (s *TransactionTemplateService) ModifyTemplateDisplayOrders(c *core.Context
}
// DeleteTemplate deletes an existed transaction template from database
func (s *TransactionTemplateService) DeleteTemplate(c *core.Context, uid int64, templateId int64) error {
func (s *TransactionTemplateService) DeleteTemplate(c core.Context, uid int64, templateId int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -216,7 +216,7 @@ func (s *TransactionTemplateService) DeleteTemplate(c *core.Context, uid int64,
}
// DeleteAllTemplates deletes all existed transaction templates from database
func (s *TransactionTemplateService) DeleteAllTemplates(c *core.Context, uid int64) error {
func (s *TransactionTemplateService) DeleteAllTemplates(c core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
+15 -15
View File
@@ -37,7 +37,7 @@ var (
)
// GetTotalTransactionCountByUid returns total transaction count of user
func (s *TransactionService) GetTotalTransactionCountByUid(c *core.Context, uid int64) (int64, error) {
func (s *TransactionService) GetTotalTransactionCountByUid(c core.Context, uid int64) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -48,7 +48,7 @@ func (s *TransactionService) GetTotalTransactionCountByUid(c *core.Context, uid
}
// GetAllTransactions returns all transactions
func (s *TransactionService) GetAllTransactions(c *core.Context, uid int64, pageCount int32, noDuplicated bool) ([]*models.Transaction, error) {
func (s *TransactionService) GetAllTransactions(c core.Context, uid int64, pageCount int32, noDuplicated bool) ([]*models.Transaction, error) {
maxTransactionTime := utils.GetMaxTransactionTimeFromUnixTime(time.Now().Unix())
var allTransactions []*models.Transaction
@@ -73,12 +73,12 @@ func (s *TransactionService) GetAllTransactions(c *core.Context, uid int64, page
}
// GetAllTransactionsByMaxTime returns all transactions before given time
func (s *TransactionService) GetAllTransactionsByMaxTime(c *core.Context, uid int64, maxTransactionTime int64, count int32, noDuplicated bool) ([]*models.Transaction, error) {
func (s *TransactionService) GetAllTransactionsByMaxTime(c core.Context, uid int64, maxTransactionTime int64, count int32, noDuplicated bool) ([]*models.Transaction, error) {
return s.GetTransactionsByMaxTime(c, uid, maxTransactionTime, 0, 0, nil, nil, nil, false, "", "", 1, count, false, noDuplicated)
}
// GetTransactionsByMaxTime returns transactions before given time
func (s *TransactionService) GetTransactionsByMaxTime(c *core.Context, uid int64, maxTransactionTime int64, minTransactionTime int64, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, tagIds []int64, noTags bool, amountFilter string, keyword string, page int32, count int32, needOneMoreItem bool, noDuplicated bool) ([]*models.Transaction, error) {
func (s *TransactionService) GetTransactionsByMaxTime(c core.Context, uid int64, maxTransactionTime int64, minTransactionTime int64, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, tagIds []int64, noTags bool, amountFilter string, keyword string, page int32, count int32, needOneMoreItem bool, noDuplicated bool) ([]*models.Transaction, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -117,7 +117,7 @@ func (s *TransactionService) GetTransactionsByMaxTime(c *core.Context, uid int64
}
// GetTransactionsInMonthByPage returns all transactions in given year and month
func (s *TransactionService) GetTransactionsInMonthByPage(c *core.Context, uid int64, year int32, month int32, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, tagIds []int64, noTags bool, amountFilter string, keyword string) ([]*models.Transaction, error) {
func (s *TransactionService) GetTransactionsInMonthByPage(c core.Context, uid int64, year int32, month int32, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, tagIds []int64, noTags bool, amountFilter string, keyword string) ([]*models.Transaction, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -157,7 +157,7 @@ func (s *TransactionService) GetTransactionsInMonthByPage(c *core.Context, uid i
}
// GetTransactionByTransactionId returns a transaction model according to transaction id
func (s *TransactionService) GetTransactionByTransactionId(c *core.Context, uid int64, transactionId int64) (*models.Transaction, error) {
func (s *TransactionService) GetTransactionByTransactionId(c core.Context, uid int64, transactionId int64) (*models.Transaction, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -179,12 +179,12 @@ func (s *TransactionService) GetTransactionByTransactionId(c *core.Context, uid
}
// GetAllTransactionCount returns total count of transactions
func (s *TransactionService) GetAllTransactionCount(c *core.Context, uid int64) (int64, error) {
func (s *TransactionService) GetAllTransactionCount(c core.Context, uid int64) (int64, error) {
return s.GetTransactionCount(c, uid, 0, 0, 0, nil, nil, nil, false, "", "")
}
// GetTransactionCount returns count of transactions
func (s *TransactionService) GetTransactionCount(c *core.Context, uid int64, maxTransactionTime int64, minTransactionTime int64, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, tagIds []int64, noTags bool, amountFilter string, keyword string) (int64, error) {
func (s *TransactionService) GetTransactionCount(c core.Context, uid int64, maxTransactionTime int64, minTransactionTime int64, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, tagIds []int64, noTags bool, amountFilter string, keyword string) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -202,7 +202,7 @@ func (s *TransactionService) GetTransactionCount(c *core.Context, uid int64, max
}
// CreateTransaction saves a new transaction to database
func (s *TransactionService) CreateTransaction(c *core.Context, transaction *models.Transaction, tagIds []int64) error {
func (s *TransactionService) CreateTransaction(c core.Context, transaction *models.Transaction, tagIds []int64) error {
if transaction.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -430,7 +430,7 @@ func (s *TransactionService) CreateTransaction(c *core.Context, transaction *mod
}
// ModifyTransaction saves an existed transaction to database
func (s *TransactionService) ModifyTransaction(c *core.Context, transaction *models.Transaction, currentTagIdsCount int, addTagIds []int64, removeTagIds []int64) error {
func (s *TransactionService) ModifyTransaction(c core.Context, transaction *models.Transaction, currentTagIdsCount int, addTagIds []int64, removeTagIds []int64) error {
if transaction.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -826,7 +826,7 @@ func (s *TransactionService) ModifyTransaction(c *core.Context, transaction *mod
}
// DeleteTransaction deletes an existed transaction from database
func (s *TransactionService) DeleteTransaction(c *core.Context, uid int64, transactionId int64) error {
func (s *TransactionService) DeleteTransaction(c core.Context, uid int64, transactionId int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -950,7 +950,7 @@ func (s *TransactionService) DeleteTransaction(c *core.Context, uid int64, trans
}
// DeleteAllTransactions deletes all existed transactions from database
func (s *TransactionService) DeleteAllTransactions(c *core.Context, uid int64) error {
func (s *TransactionService) DeleteAllTransactions(c core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -1040,7 +1040,7 @@ func (s *TransactionService) GetRelatedTransferTransaction(originalTransaction *
}
// GetAccountsTotalIncomeAndExpense returns the every accounts total income and expense amount by specific date range
func (s *TransactionService) GetAccountsTotalIncomeAndExpense(c *core.Context, uid int64, startUnixTime int64, endUnixTime int64, utcOffset int16, useTransactionTimezone bool) (map[int64]int64, map[int64]int64, error) {
func (s *TransactionService) GetAccountsTotalIncomeAndExpense(c core.Context, uid int64, startUnixTime int64, endUnixTime int64, utcOffset int16, useTransactionTimezone bool) (map[int64]int64, map[int64]int64, error) {
if uid <= 0 {
return nil, nil, errs.ErrUserIdInvalid
}
@@ -1129,7 +1129,7 @@ func (s *TransactionService) GetAccountsTotalIncomeAndExpense(c *core.Context, u
}
// GetAccountsAndCategoriesTotalIncomeAndExpense returns the every accounts and categories total income and expense amount by specific date range
func (s *TransactionService) GetAccountsAndCategoriesTotalIncomeAndExpense(c *core.Context, uid int64, startUnixTime int64, endUnixTime int64, utcOffset int16, useTransactionTimezone bool) ([]*models.Transaction, error) {
func (s *TransactionService) GetAccountsAndCategoriesTotalIncomeAndExpense(c core.Context, uid int64, startUnixTime int64, endUnixTime int64, utcOffset int16, useTransactionTimezone bool) ([]*models.Transaction, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -1235,7 +1235,7 @@ func (s *TransactionService) GetAccountsAndCategoriesTotalIncomeAndExpense(c *co
}
// GetAccountsAndCategoriesMonthlyIncomeAndExpense returns the every accounts monthly income and expense amount by specific date range
func (s *TransactionService) GetAccountsAndCategoriesMonthlyIncomeAndExpense(c *core.Context, uid int64, startYear int32, startMonth int32, endYear int32, endMonth int32, utcOffset int16, useTransactionTimezone bool) (map[int32][]*models.Transaction, error) {
func (s *TransactionService) GetAccountsAndCategoriesMonthlyIncomeAndExpense(c core.Context, uid int64, startYear int32, startMonth int32, endYear int32, endMonth int32, utcOffset int16, useTransactionTimezone bool) (map[int32][]*models.Transaction, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
+8 -8
View File
@@ -46,7 +46,7 @@ var (
)
// GetUserTwoFactorSettingByUid returns the 2fa setting model according to user uid
func (s *TwoFactorAuthorizationService) GetUserTwoFactorSettingByUid(c *core.Context, uid int64) (*models.TwoFactor, error) {
func (s *TwoFactorAuthorizationService) GetUserTwoFactorSettingByUid(c core.Context, uid int64) (*models.TwoFactor, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -70,7 +70,7 @@ func (s *TwoFactorAuthorizationService) GetUserTwoFactorSettingByUid(c *core.Con
}
// GenerateTwoFactorSecret generates a new 2fa secret
func (s *TwoFactorAuthorizationService) GenerateTwoFactorSecret(c *core.Context, user *models.User) (*otp.Key, error) {
func (s *TwoFactorAuthorizationService) GenerateTwoFactorSecret(c core.Context, user *models.User) (*otp.Key, error) {
if user == nil {
return nil, errs.ErrUserNotFound
}
@@ -86,7 +86,7 @@ func (s *TwoFactorAuthorizationService) GenerateTwoFactorSecret(c *core.Context,
}
// CreateTwoFactorSetting saves a new 2fa setting to database
func (s *TwoFactorAuthorizationService) CreateTwoFactorSetting(c *core.Context, twoFactor *models.TwoFactor) error {
func (s *TwoFactorAuthorizationService) CreateTwoFactorSetting(c core.Context, twoFactor *models.TwoFactor) error {
if twoFactor.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -107,7 +107,7 @@ func (s *TwoFactorAuthorizationService) CreateTwoFactorSetting(c *core.Context,
}
// DeleteTwoFactorSetting deletes an existed 2fa setting from database
func (s *TwoFactorAuthorizationService) DeleteTwoFactorSetting(c *core.Context, uid int64) error {
func (s *TwoFactorAuthorizationService) DeleteTwoFactorSetting(c core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -126,7 +126,7 @@ func (s *TwoFactorAuthorizationService) DeleteTwoFactorSetting(c *core.Context,
}
// ExistsTwoFactorSetting returns whether the given user has existed 2fa setting
func (s *TwoFactorAuthorizationService) ExistsTwoFactorSetting(c *core.Context, uid int64) (bool, error) {
func (s *TwoFactorAuthorizationService) ExistsTwoFactorSetting(c core.Context, uid int64) (bool, error) {
if uid <= 0 {
return false, errs.ErrUserIdInvalid
}
@@ -135,7 +135,7 @@ func (s *TwoFactorAuthorizationService) ExistsTwoFactorSetting(c *core.Context,
}
// GetAndUseUserTwoFactorRecoveryCode checks whether the given 2fa recovery code exists and marks it used
func (s *TwoFactorAuthorizationService) GetAndUseUserTwoFactorRecoveryCode(c *core.Context, uid int64, recoveryCode string, salt string) error {
func (s *TwoFactorAuthorizationService) GetAndUseUserTwoFactorRecoveryCode(c core.Context, uid int64, recoveryCode string, salt string) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -173,7 +173,7 @@ func (s *TwoFactorAuthorizationService) GenerateTwoFactorRecoveryCodes() ([]stri
}
// CreateTwoFactorRecoveryCodes saves new 2fa recovery codes to database
func (s *TwoFactorAuthorizationService) CreateTwoFactorRecoveryCodes(c *core.Context, uid int64, recoveryCodes []string, salt string) error {
func (s *TwoFactorAuthorizationService) CreateTwoFactorRecoveryCodes(c core.Context, uid int64, recoveryCodes []string, salt string) error {
twoFactorRecoveryCodes := make([]*models.TwoFactorRecoveryCode, len(recoveryCodes))
for i := 0; i < len(recoveryCodes); i++ {
@@ -206,7 +206,7 @@ func (s *TwoFactorAuthorizationService) CreateTwoFactorRecoveryCodes(c *core.Con
}
// DeleteTwoFactorRecoveryCodes deletes existed 2fa recovery codes from database
func (s *TwoFactorAuthorizationService) DeleteTwoFactorRecoveryCodes(c *core.Context, uid int64) error {
func (s *TwoFactorAuthorizationService) DeleteTwoFactorRecoveryCodes(c core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
+18 -18
View File
@@ -58,7 +58,7 @@ var (
)
// GetUserByUsernameOrEmailAndPassword returns the user model according to login name and password
func (s *UserService) GetUserByUsernameOrEmailAndPassword(c *core.Context, loginname string, password string) (*models.User, error) {
func (s *UserService) GetUserByUsernameOrEmailAndPassword(c core.Context, loginname string, password string) (*models.User, error) {
var user *models.User
var err error
@@ -82,7 +82,7 @@ func (s *UserService) GetUserByUsernameOrEmailAndPassword(c *core.Context, login
}
// GetUserById returns the user model according to user uid
func (s *UserService) GetUserById(c *core.Context, uid int64) (*models.User, error) {
func (s *UserService) GetUserById(c core.Context, uid int64) (*models.User, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -100,7 +100,7 @@ func (s *UserService) GetUserById(c *core.Context, uid int64) (*models.User, err
}
// GetUserByUsername returns the user model according to user name
func (s *UserService) GetUserByUsername(c *core.Context, username string) (*models.User, error) {
func (s *UserService) GetUserByUsername(c core.Context, username string) (*models.User, error) {
if username == "" {
return nil, errs.ErrUsernameIsEmpty
}
@@ -118,7 +118,7 @@ func (s *UserService) GetUserByUsername(c *core.Context, username string) (*mode
}
// GetUserByEmail returns the user model according to user email
func (s *UserService) GetUserByEmail(c *core.Context, email string) (*models.User, error) {
func (s *UserService) GetUserByEmail(c core.Context, email string) (*models.User, error) {
if email == "" {
return nil, errs.ErrEmailIsEmpty
}
@@ -136,7 +136,7 @@ func (s *UserService) GetUserByEmail(c *core.Context, email string) (*models.Use
}
// GetUserAvatar returns the user avatar image data and image file extension according to user uid
func (s *UserService) GetUserAvatar(c *core.Context, uid int64, fileExtension string) ([]byte, error) {
func (s *UserService) GetUserAvatar(c core.Context, uid int64, fileExtension string) ([]byte, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -180,7 +180,7 @@ func (s *UserService) GetUserAvatar(c *core.Context, uid int64, fileExtension st
}
// CreateUser saves a new user model to database
func (s *UserService) CreateUser(c *core.Context, user *models.User) error {
func (s *UserService) CreateUser(c core.Context, user *models.User) error {
exists, err := s.ExistsUsername(c, user.Username)
if err != nil {
@@ -226,7 +226,7 @@ func (s *UserService) CreateUser(c *core.Context, user *models.User) error {
}
// UpdateUser saves an existed user model to database
func (s *UserService) UpdateUser(c *core.Context, user *models.User, modifyUserLanguage bool) (keyProfileUpdated bool, emailSetToUnverified bool, err error) {
func (s *UserService) UpdateUser(c core.Context, user *models.User, modifyUserLanguage bool) (keyProfileUpdated bool, emailSetToUnverified bool, err error) {
if user.Uid <= 0 {
return false, false, errs.ErrUserIdInvalid
}
@@ -348,7 +348,7 @@ func (s *UserService) UpdateUser(c *core.Context, user *models.User, modifyUserL
}
// UpdateUserAvatar updates the custom avatar type of specified user
func (s *UserService) UpdateUserAvatar(c *core.Context, uid int64, avatarFile multipart.File, fileExtension string, oldFileExtension string) error {
func (s *UserService) UpdateUserAvatar(c core.Context, uid int64, avatarFile multipart.File, fileExtension string, oldFileExtension string) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -381,7 +381,7 @@ func (s *UserService) UpdateUserAvatar(c *core.Context, uid int64, avatarFile mu
err = s.DeleteAvatar(uid, oldFileExtension)
if err != nil {
log.WarnfWithRequestId(c, "[users.UpdateUserAvatar] failed to delete old avatar with extension \"%s\" for user \"uid:%d\", because %s", oldFileExtension, uid, err.Error())
log.Warnf(c, "[users.UpdateUserAvatar] failed to delete old avatar with extension \"%s\" for user \"uid:%d\", because %s", oldFileExtension, uid, err.Error())
}
}
@@ -389,7 +389,7 @@ func (s *UserService) UpdateUserAvatar(c *core.Context, uid int64, avatarFile mu
}
// RemoveUserAvatar removes the custom avatar type of specified user
func (s *UserService) RemoveUserAvatar(c *core.Context, uid int64, fileExtension string) error {
func (s *UserService) RemoveUserAvatar(c core.Context, uid int64, fileExtension string) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -414,7 +414,7 @@ func (s *UserService) RemoveUserAvatar(c *core.Context, uid int64, fileExtension
}
// UpdateUserLastLoginTime updates the last login time field
func (s *UserService) UpdateUserLastLoginTime(c *core.Context, uid int64) error {
func (s *UserService) UpdateUserLastLoginTime(c core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -426,7 +426,7 @@ func (s *UserService) UpdateUserLastLoginTime(c *core.Context, uid int64) error
}
// EnableUser sets user enabled
func (s *UserService) EnableUser(c *core.Context, username string) error {
func (s *UserService) EnableUser(c core.Context, username string) error {
if username == "" {
return errs.ErrUsernameIsEmpty
}
@@ -449,7 +449,7 @@ func (s *UserService) EnableUser(c *core.Context, username string) error {
}
// DisableUser sets user disabled
func (s *UserService) DisableUser(c *core.Context, username string) error {
func (s *UserService) DisableUser(c core.Context, username string) error {
if username == "" {
return errs.ErrUsernameIsEmpty
}
@@ -472,7 +472,7 @@ func (s *UserService) DisableUser(c *core.Context, username string) error {
}
// SetUserEmailVerified sets user email address verified
func (s *UserService) SetUserEmailVerified(c *core.Context, username string) error {
func (s *UserService) SetUserEmailVerified(c core.Context, username string) error {
if username == "" {
return errs.ErrUsernameIsEmpty
}
@@ -495,7 +495,7 @@ func (s *UserService) SetUserEmailVerified(c *core.Context, username string) err
}
// SetUserEmailUnverified sets user email address unverified
func (s *UserService) SetUserEmailUnverified(c *core.Context, username string) error {
func (s *UserService) SetUserEmailUnverified(c core.Context, username string) error {
if username == "" {
return errs.ErrUsernameIsEmpty
}
@@ -518,7 +518,7 @@ func (s *UserService) SetUserEmailUnverified(c *core.Context, username string) e
}
// DeleteUser deletes an existed user from database
func (s *UserService) DeleteUser(c *core.Context, username string) error {
func (s *UserService) DeleteUser(c core.Context, username string) error {
if username == "" {
return errs.ErrUsernameIsEmpty
}
@@ -541,7 +541,7 @@ func (s *UserService) DeleteUser(c *core.Context, username string) error {
}
// ExistsUsername returns whether the given user name exists
func (s *UserService) ExistsUsername(c *core.Context, username string) (bool, error) {
func (s *UserService) ExistsUsername(c core.Context, username string) (bool, error) {
if username == "" {
return false, errs.ErrUsernameIsEmpty
}
@@ -550,7 +550,7 @@ func (s *UserService) ExistsUsername(c *core.Context, username string) (bool, er
}
// ExistsEmail returns whether the given user email exists
func (s *UserService) ExistsEmail(c *core.Context, email string) (bool, error) {
func (s *UserService) ExistsEmail(c core.Context, email string) (bool, error) {
if email == "" {
return false, errs.ErrEmailIsEmpty
}
+4 -4
View File
@@ -12,7 +12,7 @@ import (
)
// PrintJsonSuccessResult writes success response in json format to current http context
func PrintJsonSuccessResult(c *core.Context, result any) {
func PrintJsonSuccessResult(c *core.WebContext, result any) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"result": result,
@@ -20,7 +20,7 @@ func PrintJsonSuccessResult(c *core.Context, result any) {
}
// PrintDataSuccessResult writes success response in custom content type to current http context
func PrintDataSuccessResult(c *core.Context, contentType string, fileName string, result []byte) {
func PrintDataSuccessResult(c *core.WebContext, contentType string, fileName string, result []byte) {
if fileName != "" {
c.Header("Content-Disposition", "attachment;filename="+fileName)
}
@@ -29,7 +29,7 @@ func PrintDataSuccessResult(c *core.Context, contentType string, fileName string
}
// PrintJsonErrorResult writes error response in json format to current http context
func PrintJsonErrorResult(c *core.Context, err *errs.Error) {
func PrintJsonErrorResult(c *core.WebContext, err *errs.Error) {
c.SetResponseError(err)
errorMessage := err.Error()
@@ -60,7 +60,7 @@ func PrintJsonErrorResult(c *core.Context, err *errs.Error) {
}
// PrintDataErrorResult writes error response in custom content type to current http context
func PrintDataErrorResult(c *core.Context, contentType string, err *errs.Error) {
func PrintDataErrorResult(c *core.WebContext, contentType string, err *errs.Error) {
c.SetResponseError(err)
errorMessage := err.Error()