code refactor
This commit is contained in:
+14
@@ -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
@@ -5,6 +5,7 @@ import (
|
|||||||
|
|
||||||
"github.com/urfave/cli/v2"
|
"github.com/urfave/cli/v2"
|
||||||
|
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/cron"
|
"github.com/mayswind/ezbookkeeping/pkg/cron"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/log"
|
"github.com/mayswind/ezbookkeeping/pkg/log"
|
||||||
)
|
)
|
||||||
@@ -17,12 +18,12 @@ var CronJobs = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "list",
|
Name: "list",
|
||||||
Usage: "List all enabled cron jobs",
|
Usage: "List all enabled cron jobs",
|
||||||
Action: listAllCronJobs,
|
Action: bindAction(listAllCronJobs),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "run",
|
Name: "run",
|
||||||
Usage: "Run specified cron job",
|
Usage: "Run specified cron job",
|
||||||
Action: runCronJob,
|
Action: bindAction(runCronJob),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "name",
|
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)
|
config, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = cron.InitializeCronJobSchedulerContainer(config, false)
|
err = cron.InitializeCronJobSchedulerContainer(c, config, false)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
cronJobs := cron.Container.GetAllJobs()
|
cronJobs := cron.Container.GetAllJobs()
|
||||||
|
|
||||||
if len(cronJobs) < 1 {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,17 +72,17 @@ func listAllCronJobs(c *cli.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func runCronJob(c *cli.Context) error {
|
func runCronJob(c *core.CliContext) error {
|
||||||
config, err := initializeSystem(c)
|
config, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = cron.InitializeCronJobSchedulerContainer(config, false)
|
err = cron.InitializeCronJobSchedulerContainer(c, config, false)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +90,7 @@ func runCronJob(c *cli.Context) error {
|
|||||||
err = cron.Container.SyncRunJobNow(jobName)
|
err = cron.Container.SyncRunJobNow(jobName)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+18
-17
@@ -3,6 +3,7 @@ package cmd
|
|||||||
import (
|
import (
|
||||||
"github.com/urfave/cli/v2"
|
"github.com/urfave/cli/v2"
|
||||||
|
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/datastore"
|
"github.com/mayswind/ezbookkeeping/pkg/datastore"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/log"
|
"github.com/mayswind/ezbookkeeping/pkg/log"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/models"
|
"github.com/mayswind/ezbookkeeping/pkg/models"
|
||||||
@@ -16,32 +17,32 @@ var Database = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "update",
|
Name: "update",
|
||||||
Usage: "Update database structure",
|
Usage: "Update database structure",
|
||||||
Action: updateDatabaseStructure,
|
Action: bindAction(updateDatabaseStructure),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateDatabaseStructure(c *cli.Context) error {
|
func updateDatabaseStructure(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.BootInfof("[database.updateDatabaseStructure] starting maintaining")
|
log.BootInfof(c, "[database.updateDatabaseStructure] starting maintaining")
|
||||||
|
|
||||||
err = updateAllDatabaseTablesStructure()
|
err = updateAllDatabaseTablesStructure(c)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.BootInfof("[database.updateDatabaseStructure] all tables maintained successfully")
|
log.BootInfof(c, "[database.updateDatabaseStructure] all tables maintained successfully")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateAllDatabaseTablesStructure() error {
|
func updateAllDatabaseTablesStructure(c *core.CliContext) error {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
err = datastore.Container.UserStore.SyncStructs(new(models.User))
|
err = datastore.Container.UserStore.SyncStructs(new(models.User))
|
||||||
@@ -50,7 +51,7 @@ func updateAllDatabaseTablesStructure() error {
|
|||||||
return err
|
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))
|
err = datastore.Container.UserStore.SyncStructs(new(models.TwoFactor))
|
||||||
|
|
||||||
@@ -58,7 +59,7 @@ func updateAllDatabaseTablesStructure() error {
|
|||||||
return err
|
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))
|
err = datastore.Container.UserStore.SyncStructs(new(models.TwoFactorRecoveryCode))
|
||||||
|
|
||||||
@@ -66,7 +67,7 @@ func updateAllDatabaseTablesStructure() error {
|
|||||||
return err
|
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))
|
err = datastore.Container.TokenStore.SyncStructs(new(models.TokenRecord))
|
||||||
|
|
||||||
@@ -74,7 +75,7 @@ func updateAllDatabaseTablesStructure() error {
|
|||||||
return err
|
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))
|
err = datastore.Container.UserDataStore.SyncStructs(new(models.Account))
|
||||||
|
|
||||||
@@ -82,7 +83,7 @@ func updateAllDatabaseTablesStructure() error {
|
|||||||
return err
|
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))
|
err = datastore.Container.UserDataStore.SyncStructs(new(models.Transaction))
|
||||||
|
|
||||||
@@ -90,7 +91,7 @@ func updateAllDatabaseTablesStructure() error {
|
|||||||
return err
|
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))
|
err = datastore.Container.UserDataStore.SyncStructs(new(models.TransactionCategory))
|
||||||
|
|
||||||
@@ -98,7 +99,7 @@ func updateAllDatabaseTablesStructure() error {
|
|||||||
return err
|
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))
|
err = datastore.Container.UserDataStore.SyncStructs(new(models.TransactionTag))
|
||||||
|
|
||||||
@@ -106,7 +107,7 @@ func updateAllDatabaseTablesStructure() error {
|
|||||||
return err
|
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))
|
err = datastore.Container.UserDataStore.SyncStructs(new(models.TransactionTagIndex))
|
||||||
|
|
||||||
@@ -114,7 +115,7 @@ func updateAllDatabaseTablesStructure() error {
|
|||||||
return err
|
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))
|
err = datastore.Container.UserDataStore.SyncStructs(new(models.TransactionTemplate))
|
||||||
|
|
||||||
@@ -122,7 +123,7 @@ func updateAllDatabaseTablesStructure() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.BootInfof("[database.updateAllDatabaseTablesStructure] transaction template table maintained successfully")
|
log.BootInfof(c, "[database.updateAllDatabaseTablesStructure] transaction template table maintained successfully")
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-17
@@ -4,8 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/urfave/cli/v2"
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
|
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/datastore"
|
"github.com/mayswind/ezbookkeeping/pkg/datastore"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/duplicatechecker"
|
"github.com/mayswind/ezbookkeeping/pkg/duplicatechecker"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/exchangerates"
|
"github.com/mayswind/ezbookkeeping/pkg/exchangerates"
|
||||||
@@ -17,7 +16,7 @@ import (
|
|||||||
"github.com/mayswind/ezbookkeeping/pkg/uuid"
|
"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
|
var err error
|
||||||
configFilePath := c.String("conf-path")
|
configFilePath := c.String("conf-path")
|
||||||
isDisableBootLog := c.Bool("no-boot-log")
|
isDisableBootLog := c.Bool("no-boot-log")
|
||||||
@@ -25,26 +24,26 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
|
|||||||
if configFilePath != "" {
|
if configFilePath != "" {
|
||||||
if _, err = os.Stat(configFilePath); err != nil {
|
if _, err = os.Stat(configFilePath); err != nil {
|
||||||
if !isDisableBootLog {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if !isDisableBootLog {
|
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 {
|
} else {
|
||||||
configFilePath, err = settings.GetDefaultConfigFilePath()
|
configFilePath, err = settings.GetDefaultConfigFilePath()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !isDisableBootLog {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if !isDisableBootLog {
|
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 err != nil {
|
||||||
if !isDisableBootLog {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.SecretKeyNoSet {
|
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)
|
settings.SetCurrentConfig(config)
|
||||||
@@ -67,7 +66,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !isDisableBootLog {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -76,7 +75,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !isDisableBootLog {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -85,7 +84,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !isDisableBootLog {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -94,7 +93,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !isDisableBootLog {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -103,7 +102,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !isDisableBootLog {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -112,7 +111,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !isDisableBootLog {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -121,7 +120,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !isDisableBootLog {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -129,7 +128,7 @@ func initializeSystem(c *cli.Context) (*settings.Config, error) {
|
|||||||
cfgJson, _ := json.Marshal(getConfigWithoutSensitiveData(config))
|
cfgJson, _ := json.Marshal(getConfigWithoutSensitiveData(config))
|
||||||
|
|
||||||
if !isDisableBootLog {
|
if !isDisableBootLog {
|
||||||
log.BootInfof("[initializer.initializeSystem] has loaded configuration %s", cfgJson)
|
log.BootInfof(c, "[initializer.initializeSystem] has loaded configuration %s", cfgJson)
|
||||||
}
|
}
|
||||||
|
|
||||||
return config, nil
|
return config, nil
|
||||||
|
|||||||
+3
-2
@@ -5,6 +5,7 @@ import (
|
|||||||
|
|
||||||
"github.com/urfave/cli/v2"
|
"github.com/urfave/cli/v2"
|
||||||
|
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/utils"
|
"github.com/mayswind/ezbookkeeping/pkg/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -16,7 +17,7 @@ var SecurityUtils = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "gen-secret-key",
|
Name: "gen-secret-key",
|
||||||
Usage: "Generate a random secret key",
|
Usage: "Generate a random secret key",
|
||||||
Action: genSecretKey,
|
Action: bindAction(genSecretKey),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.IntFlag{
|
&cli.IntFlag{
|
||||||
Name: "length",
|
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")
|
length := c.Int("length")
|
||||||
|
|
||||||
if length <= 0 {
|
if length <= 0 {
|
||||||
|
|||||||
+69
-68
@@ -7,6 +7,7 @@ import (
|
|||||||
"github.com/urfave/cli/v2"
|
"github.com/urfave/cli/v2"
|
||||||
|
|
||||||
clis "github.com/mayswind/ezbookkeeping/pkg/cli"
|
clis "github.com/mayswind/ezbookkeeping/pkg/cli"
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/log"
|
"github.com/mayswind/ezbookkeeping/pkg/log"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/models"
|
"github.com/mayswind/ezbookkeeping/pkg/models"
|
||||||
@@ -21,7 +22,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-add",
|
Name: "user-add",
|
||||||
Usage: "Add new user",
|
Usage: "Add new user",
|
||||||
Action: addNewUser,
|
Action: bindAction(addNewUser),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -58,7 +59,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-get",
|
Name: "user-get",
|
||||||
Usage: "Get specified user info",
|
Usage: "Get specified user info",
|
||||||
Action: getUserInfo,
|
Action: bindAction(getUserInfo),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -71,7 +72,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-modify-password",
|
Name: "user-modify-password",
|
||||||
Usage: "Modify user password",
|
Usage: "Modify user password",
|
||||||
Action: modifyUserPassword,
|
Action: bindAction(modifyUserPassword),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -90,7 +91,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-enable",
|
Name: "user-enable",
|
||||||
Usage: "Enable specified user",
|
Usage: "Enable specified user",
|
||||||
Action: enableUser,
|
Action: bindAction(enableUser),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -103,7 +104,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-disable",
|
Name: "user-disable",
|
||||||
Usage: "Disable specified user",
|
Usage: "Disable specified user",
|
||||||
Action: disableUser,
|
Action: bindAction(disableUser),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -116,7 +117,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-resend-verify-email",
|
Name: "user-resend-verify-email",
|
||||||
Usage: "Resend user verify email",
|
Usage: "Resend user verify email",
|
||||||
Action: resendUserVerifyEmail,
|
Action: bindAction(resendUserVerifyEmail),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -129,7 +130,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-set-email-verified",
|
Name: "user-set-email-verified",
|
||||||
Usage: "Set user email address verified",
|
Usage: "Set user email address verified",
|
||||||
Action: setUserEmailVerified,
|
Action: bindAction(setUserEmailVerified),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -142,7 +143,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-set-email-unverified",
|
Name: "user-set-email-unverified",
|
||||||
Usage: "Set user email address unverified",
|
Usage: "Set user email address unverified",
|
||||||
Action: setUserEmailUnverified,
|
Action: bindAction(setUserEmailUnverified),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -155,7 +156,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-delete",
|
Name: "user-delete",
|
||||||
Usage: "Delete specified user",
|
Usage: "Delete specified user",
|
||||||
Action: deleteUser,
|
Action: bindAction(deleteUser),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -168,7 +169,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-2fa-disable",
|
Name: "user-2fa-disable",
|
||||||
Usage: "Disable user 2fa setting",
|
Usage: "Disable user 2fa setting",
|
||||||
Action: disableUser2FA,
|
Action: bindAction(disableUser2FA),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -181,7 +182,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-session-list",
|
Name: "user-session-list",
|
||||||
Usage: "List all user sessions",
|
Usage: "List all user sessions",
|
||||||
Action: listUserTokens,
|
Action: bindAction(listUserTokens),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -194,7 +195,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "user-session-clear",
|
Name: "user-session-clear",
|
||||||
Usage: "Clear user all sessions",
|
Usage: "Clear user all sessions",
|
||||||
Action: clearUserTokens,
|
Action: bindAction(clearUserTokens),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -207,7 +208,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "send-password-reset-mail",
|
Name: "send-password-reset-mail",
|
||||||
Usage: "Send password reset mail",
|
Usage: "Send password reset mail",
|
||||||
Action: sendPasswordResetMail,
|
Action: bindAction(sendPasswordResetMail),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -220,7 +221,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "transaction-check",
|
Name: "transaction-check",
|
||||||
Usage: "Check whether user all transactions and accounts are correct",
|
Usage: "Check whether user all transactions and accounts are correct",
|
||||||
Action: checkUserTransactionAndAccount,
|
Action: bindAction(checkUserTransactionAndAccount),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -233,7 +234,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "transaction-tag-index-fix-transaction-time",
|
Name: "transaction-tag-index-fix-transaction-time",
|
||||||
Usage: "Fix the transaction tag index data which does not have transaction time",
|
Usage: "Fix the transaction tag index data which does not have transaction time",
|
||||||
Action: fixTransactionTagIndexNotHaveTransactionTime,
|
Action: bindAction(fixTransactionTagIndexNotHaveTransactionTime),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
@@ -246,7 +247,7 @@ var UserData = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "transaction-export",
|
Name: "transaction-export",
|
||||||
Usage: "Export user all transactions to file",
|
Usage: "Export user all transactions to file",
|
||||||
Action: exportUserTransaction,
|
Action: bindAction(exportUserTransaction),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "username",
|
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)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -287,7 +288,7 @@ func addNewUser(c *cli.Context) error {
|
|||||||
user, err := clis.UserData.AddNewUser(c, username, email, nickname, password, defaultCurrency)
|
user, err := clis.UserData.AddNewUser(c, username, email, nickname, password, defaultCurrency)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -296,7 +297,7 @@ func addNewUser(c *cli.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getUserInfo(c *cli.Context) error {
|
func getUserInfo(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -307,7 +308,7 @@ func getUserInfo(c *cli.Context) error {
|
|||||||
user, err := clis.UserData.GetUserByUsername(c, username)
|
user, err := clis.UserData.GetUserByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,7 +317,7 @@ func getUserInfo(c *cli.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func modifyUserPassword(c *cli.Context) error {
|
func modifyUserPassword(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -328,16 +329,16 @@ func modifyUserPassword(c *cli.Context) error {
|
|||||||
err = clis.UserData.ModifyUserPassword(c, username, password)
|
err = clis.UserData.ModifyUserPassword(c, username, password)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func sendPasswordResetMail(c *cli.Context) error {
|
func sendPasswordResetMail(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -348,16 +349,16 @@ func sendPasswordResetMail(c *cli.Context) error {
|
|||||||
err = clis.UserData.SendPasswordResetMail(c, username)
|
err = clis.UserData.SendPasswordResetMail(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func enableUser(c *cli.Context) error {
|
func enableUser(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -368,16 +369,16 @@ func enableUser(c *cli.Context) error {
|
|||||||
err = clis.UserData.EnableUser(c, username)
|
err = clis.UserData.EnableUser(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func disableUser(c *cli.Context) error {
|
func disableUser(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -388,16 +389,16 @@ func disableUser(c *cli.Context) error {
|
|||||||
err = clis.UserData.DisableUser(c, username)
|
err = clis.UserData.DisableUser(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func resendUserVerifyEmail(c *cli.Context) error {
|
func resendUserVerifyEmail(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -408,16 +409,16 @@ func resendUserVerifyEmail(c *cli.Context) error {
|
|||||||
err = clis.UserData.ResendVerifyEmail(c, username)
|
err = clis.UserData.ResendVerifyEmail(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func setUserEmailVerified(c *cli.Context) error {
|
func setUserEmailVerified(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -428,16 +429,16 @@ func setUserEmailVerified(c *cli.Context) error {
|
|||||||
err = clis.UserData.SetUserEmailVerified(c, username)
|
err = clis.UserData.SetUserEmailVerified(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func setUserEmailUnverified(c *cli.Context) error {
|
func setUserEmailUnverified(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -448,16 +449,16 @@ func setUserEmailUnverified(c *cli.Context) error {
|
|||||||
err = clis.UserData.SetUserEmailUnverified(c, username)
|
err = clis.UserData.SetUserEmailUnverified(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func deleteUser(c *cli.Context) error {
|
func deleteUser(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -468,16 +469,16 @@ func deleteUser(c *cli.Context) error {
|
|||||||
err = clis.UserData.DeleteUser(c, username)
|
err = clis.UserData.DeleteUser(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func disableUser2FA(c *cli.Context) error {
|
func disableUser2FA(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -488,16 +489,16 @@ func disableUser2FA(c *cli.Context) error {
|
|||||||
err = clis.UserData.DisableUserTwoFactorAuthorization(c, username)
|
err = clis.UserData.DisableUserTwoFactorAuthorization(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func listUserTokens(c *cli.Context) error {
|
func listUserTokens(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -508,7 +509,7 @@ func listUserTokens(c *cli.Context) error {
|
|||||||
tokens, err := clis.UserData.ListUserTokens(c, username)
|
tokens, err := clis.UserData.ListUserTokens(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -523,7 +524,7 @@ func listUserTokens(c *cli.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func clearUserTokens(c *cli.Context) error {
|
func clearUserTokens(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -534,16 +535,16 @@ func clearUserTokens(c *cli.Context) error {
|
|||||||
err = clis.UserData.ClearUserTokens(c, username)
|
err = clis.UserData.ClearUserTokens(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkUserTransactionAndAccount(c *cli.Context) error {
|
func checkUserTransactionAndAccount(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -552,21 +553,21 @@ func checkUserTransactionAndAccount(c *cli.Context) error {
|
|||||||
|
|
||||||
username := c.String("username")
|
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)
|
_, err = clis.UserData.CheckTransactionAndAccount(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func fixTransactionTagIndexNotHaveTransactionTime(c *cli.Context) error {
|
func fixTransactionTagIndexNotHaveTransactionTime(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -575,21 +576,21 @@ func fixTransactionTagIndexNotHaveTransactionTime(c *cli.Context) error {
|
|||||||
|
|
||||||
username := c.String("username")
|
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)
|
_, err = clis.UserData.FixTransactionTagIndexWithTransactionTime(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func exportUserTransaction(c *cli.Context) error {
|
func exportUserTransaction(c *core.CliContext) error {
|
||||||
_, err := initializeSystem(c)
|
_, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -601,39 +602,39 @@ func exportUserTransaction(c *cli.Context) error {
|
|||||||
fileType := c.String("type")
|
fileType := c.String("type")
|
||||||
|
|
||||||
if fileType != "" && fileType != "csv" && fileType != "tsv" {
|
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
|
return errs.ErrNotSupported
|
||||||
}
|
}
|
||||||
|
|
||||||
if filePath == "" {
|
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
|
return os.ErrNotExist
|
||||||
}
|
}
|
||||||
|
|
||||||
fileExists, err := utils.IsExists(filePath)
|
fileExists, err := utils.IsExists(filePath)
|
||||||
|
|
||||||
if fileExists {
|
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
|
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)
|
content, err := clis.UserData.ExportTransaction(c, username, fileType)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = utils.WriteFile(filePath, content)
|
err = utils.WriteFile(filePath, content)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-6
@@ -7,6 +7,7 @@ import (
|
|||||||
|
|
||||||
"github.com/urfave/cli/v2"
|
"github.com/urfave/cli/v2"
|
||||||
|
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/mail"
|
"github.com/mayswind/ezbookkeeping/pkg/mail"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/requestid"
|
"github.com/mayswind/ezbookkeeping/pkg/requestid"
|
||||||
@@ -21,7 +22,7 @@ var Utilities = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "parse-default-request-id",
|
Name: "parse-default-request-id",
|
||||||
Usage: "Parse a request id which is generated by default request generator and show the details",
|
Usage: "Parse a request id which is generated by default request generator and show the details",
|
||||||
Action: parseRequestId,
|
Action: bindAction(parseRequestId),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "id",
|
Name: "id",
|
||||||
@@ -33,7 +34,7 @@ var Utilities = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "send-test-mail",
|
Name: "send-test-mail",
|
||||||
Usage: "Send an email to specified e-mail address",
|
Usage: "Send an email to specified e-mail address",
|
||||||
Action: sendTestMail,
|
Action: bindAction(sendTestMail),
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "to",
|
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)
|
config, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = requestid.InitializeRequestIdGenerator(config)
|
err = requestid.InitializeRequestIdGenerator(c, config)
|
||||||
defaultGenerator, err := requestid.NewDefaultRequestIdGenerator(config)
|
defaultGenerator, err := requestid.NewDefaultRequestIdGenerator(c, config)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -73,7 +74,7 @@ func parseRequestId(c *cli.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func sendTestMail(c *cli.Context) error {
|
func sendTestMail(c *core.CliContext) error {
|
||||||
config, err := initializeSystem(c)
|
config, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
+22
-22
@@ -33,40 +33,40 @@ var WebServer = &cli.Command{
|
|||||||
{
|
{
|
||||||
Name: "run",
|
Name: "run",
|
||||||
Usage: "Run ezBookkeeping web server",
|
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)
|
config, err := initializeSystem(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
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 {
|
if config.AutoUpdateDatabase {
|
||||||
err = updateAllDatabaseTablesStructure()
|
err = updateAllDatabaseTablesStructure(c)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err = requestid.InitializeRequestIdGenerator(config)
|
err = requestid.InitializeRequestIdGenerator(c, config)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = cron.InitializeCronJobSchedulerContainer(config, true)
|
err = cron.InitializeCronJobSchedulerContainer(c, config, true)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ func startWebServer(c *cli.Context) error {
|
|||||||
uuidServerInfo = fmt.Sprintf(", current uuid server id is %d", config.UuidServerId)
|
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 {
|
if config.Mode == settings.MODE_PRODUCTION {
|
||||||
gin.SetMode(gin.ReleaseMode)
|
gin.SetMode(gin.ReleaseMode)
|
||||||
@@ -345,20 +345,20 @@ func startWebServer(c *cli.Context) error {
|
|||||||
listenAddr := fmt.Sprintf("%s:%d", config.HttpAddr, config.HttpPort)
|
listenAddr := fmt.Sprintf("%s:%d", config.HttpAddr, config.HttpPort)
|
||||||
|
|
||||||
if config.Protocol == settings.SCHEME_SOCKET {
|
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)
|
err = router.RunUnix(config.UnixSocketPath)
|
||||||
} else if config.Protocol == settings.SCHEME_HTTP {
|
} 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)
|
err = router.Run(listenAddr)
|
||||||
} else if config.Protocol == settings.SCHEME_HTTPS {
|
} 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)
|
err = router.RunTLS(listenAddr, config.CertFile, config.CertKeyFile)
|
||||||
} else {
|
} else {
|
||||||
err = errs.ErrInvalidProtocol
|
err = errs.ErrInvalidProtocol
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.BootErrorf("[webserver.startWebServer] cannot start, because %s", err)
|
log.BootErrorf(c, "[webserver.startWebServer] cannot start, because %s", err)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -367,13 +367,13 @@ func startWebServer(c *cli.Context) error {
|
|||||||
|
|
||||||
func bindMiddleware(fn core.MiddlewareHandlerFunc) gin.HandlerFunc {
|
func bindMiddleware(fn core.MiddlewareHandlerFunc) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
fn(core.WrapContext(c))
|
fn(core.WrapWebContext(c))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindApi(fn core.ApiHandlerFunc) gin.HandlerFunc {
|
func bindApi(fn core.ApiHandlerFunc) gin.HandlerFunc {
|
||||||
return func(ginCtx *gin.Context) {
|
return func(ginCtx *gin.Context) {
|
||||||
c := core.WrapContext(ginCtx)
|
c := core.WrapWebContext(ginCtx)
|
||||||
result, err := fn(c)
|
result, err := fn(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -386,7 +386,7 @@ func bindApi(fn core.ApiHandlerFunc) gin.HandlerFunc {
|
|||||||
|
|
||||||
func bindApiWithTokenUpdate(fn core.ApiHandlerFunc, config *settings.Config) gin.HandlerFunc {
|
func bindApiWithTokenUpdate(fn core.ApiHandlerFunc, config *settings.Config) gin.HandlerFunc {
|
||||||
return func(ginCtx *gin.Context) {
|
return func(ginCtx *gin.Context) {
|
||||||
c := core.WrapContext(ginCtx)
|
c := core.WrapWebContext(ginCtx)
|
||||||
result, err := fn(c)
|
result, err := fn(c)
|
||||||
|
|
||||||
if err == nil && config.MapProvider == settings.AmapProvider && config.AmapSecurityVerificationMethod == settings.AmapSecurityVerificationInternalProxyMethod {
|
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 {
|
func bindCsv(fn core.DataHandlerFunc) gin.HandlerFunc {
|
||||||
return func(ginCtx *gin.Context) {
|
return func(ginCtx *gin.Context) {
|
||||||
c := core.WrapContext(ginCtx)
|
c := core.WrapWebContext(ginCtx)
|
||||||
result, fileName, err := fn(c)
|
result, fileName, err := fn(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -416,7 +416,7 @@ func bindCsv(fn core.DataHandlerFunc) gin.HandlerFunc {
|
|||||||
|
|
||||||
func bindTsv(fn core.DataHandlerFunc) gin.HandlerFunc {
|
func bindTsv(fn core.DataHandlerFunc) gin.HandlerFunc {
|
||||||
return func(ginCtx *gin.Context) {
|
return func(ginCtx *gin.Context) {
|
||||||
c := core.WrapContext(ginCtx)
|
c := core.WrapWebContext(ginCtx)
|
||||||
result, fileName, err := fn(c)
|
result, fileName, err := fn(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -429,7 +429,7 @@ func bindTsv(fn core.DataHandlerFunc) gin.HandlerFunc {
|
|||||||
|
|
||||||
func bindImage(fn core.ImageHandlerFunc) gin.HandlerFunc {
|
func bindImage(fn core.ImageHandlerFunc) gin.HandlerFunc {
|
||||||
return func(ginCtx *gin.Context) {
|
return func(ginCtx *gin.Context) {
|
||||||
c := core.WrapContext(ginCtx)
|
c := core.WrapWebContext(ginCtx)
|
||||||
result, contentType, err := fn(c)
|
result, contentType, err := fn(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -442,7 +442,7 @@ func bindImage(fn core.ImageHandlerFunc) gin.HandlerFunc {
|
|||||||
|
|
||||||
func bindCachedImage(fn core.ImageHandlerFunc, store persistence.CacheStore) gin.HandlerFunc {
|
func bindCachedImage(fn core.ImageHandlerFunc, store persistence.CacheStore) gin.HandlerFunc {
|
||||||
return cache.CachePage(store, time.Minute, func(ginCtx *gin.Context) {
|
return cache.CachePage(store, time.Minute, func(ginCtx *gin.Context) {
|
||||||
c := core.WrapContext(ginCtx)
|
c := core.WrapWebContext(ginCtx)
|
||||||
result, contentType, err := fn(c)
|
result, contentType, err := fn(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -455,7 +455,7 @@ func bindCachedImage(fn core.ImageHandlerFunc, store persistence.CacheStore) gin
|
|||||||
|
|
||||||
func bindProxy(fn core.ProxyHandlerFunc) gin.HandlerFunc {
|
func bindProxy(fn core.ProxyHandlerFunc) gin.HandlerFunc {
|
||||||
return func(ginCtx *gin.Context) {
|
return func(ginCtx *gin.Context) {
|
||||||
c := core.WrapContext(ginCtx)
|
c := core.WrapWebContext(ginCtx)
|
||||||
proxy, err := fn(c)
|
proxy, err := fn(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
+42
-42
@@ -35,12 +35,12 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// AccountListHandler returns accounts list of current user
|
// 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
|
var accountListReq models.AccountListRequest
|
||||||
err := c.ShouldBindQuery(&accountListReq)
|
err := c.ShouldBindQuery(&accountListReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
accounts, err := a.accounts.GetAllAccountsByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var accountGetReq models.AccountGetRequest
|
||||||
err := c.ShouldBindQuery(&accountGetReq)
|
err := c.ShouldBindQuery(&accountGetReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
accountAndSubAccounts, err := a.accounts.GetAccountAndSubAccountsByAccountId(c, uid, accountGetReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var accountCreateReq models.AccountCreateRequest
|
||||||
err := c.ShouldBindJSON(&accountCreateReq)
|
err := c.ShouldBindJSON(&accountCreateReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
utcOffset, err := c.GetClientTimezoneOffset()
|
utcOffset, err := c.GetClientTimezoneOffset()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrClientTimezoneOffsetInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
if accountCreateReq.Category < models.ACCOUNT_CATEGORY_CASH || accountCreateReq.Category > models.ACCOUNT_CATEGORY_INVESTMENT {
|
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
|
return nil, errs.ErrAccountCategoryInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
if accountCreateReq.Type == models.ACCOUNT_TYPE_SINGLE_ACCOUNT {
|
if accountCreateReq.Type == models.ACCOUNT_TYPE_SINGLE_ACCOUNT {
|
||||||
if len(accountCreateReq.SubAccounts) > 0 {
|
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
|
return nil, errs.ErrAccountCannotHaveSubAccounts
|
||||||
}
|
}
|
||||||
|
|
||||||
if accountCreateReq.Currency == validators.ParentAccountCurrencyPlaceholder {
|
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
|
return nil, errs.ErrAccountCurrencyInvalid
|
||||||
}
|
}
|
||||||
} else if accountCreateReq.Type == models.ACCOUNT_TYPE_MULTI_SUB_ACCOUNTS {
|
} else if accountCreateReq.Type == models.ACCOUNT_TYPE_MULTI_SUB_ACCOUNTS {
|
||||||
if len(accountCreateReq.SubAccounts) < 1 {
|
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
|
return nil, errs.ErrAccountHaveNoSubAccount
|
||||||
}
|
}
|
||||||
|
|
||||||
if accountCreateReq.Currency != validators.ParentAccountCurrencyPlaceholder {
|
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
|
return nil, errs.ErrParentAccountCannotSetCurrency
|
||||||
}
|
}
|
||||||
|
|
||||||
if accountCreateReq.Balance != 0 {
|
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
|
return nil, errs.ErrParentAccountCannotSetBalance
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,22 +189,22 @@ func (a *AccountsApi) AccountCreateHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
subAccount := accountCreateReq.SubAccounts[i]
|
subAccount := accountCreateReq.SubAccounts[i]
|
||||||
|
|
||||||
if subAccount.Category != accountCreateReq.Category {
|
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
|
return nil, errs.ErrSubAccountCategoryNotEqualsToParent
|
||||||
}
|
}
|
||||||
|
|
||||||
if subAccount.Type != models.ACCOUNT_TYPE_SINGLE_ACCOUNT {
|
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
|
return nil, errs.ErrSubAccountTypeInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
if subAccount.Currency == validators.ParentAccountCurrencyPlaceholder {
|
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
|
return nil, errs.ErrAccountCurrencyInvalid
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} 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
|
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)
|
maxOrderId, err := a.accounts.GetMaxDisplayOrder(c, uid, accountCreateReq.Category)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
found, remark := a.GetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_ACCOUNT, uid, accountCreateReq.ClientSessionId)
|
||||||
|
|
||||||
if found {
|
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)
|
accountId, err := utils.StringToInt64(remark)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
accountAndSubAccounts, err := a.accounts.GetAccountAndSubAccountsByAccountId(c, uid, accountId)
|
accountAndSubAccounts, err := a.accounts.GetAccountAndSubAccountsByAccountId(c, uid, accountId)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.accounts.CreateAccounts(c, mainAccount, childrenAccounts, utcOffset)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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))
|
a.SetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_ACCOUNT, uid, accountCreateReq.ClientSessionId, utils.Int64ToString(mainAccount.AccountId))
|
||||||
accountInfoResp := mainAccount.ToAccountInfoResponse()
|
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
|
// 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
|
var accountModifyReq models.AccountModifyRequest
|
||||||
err := c.ShouldBindJSON(&accountModifyReq)
|
err := c.ShouldBindJSON(&accountModifyReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if accountModifyReq.Category < models.ACCOUNT_CATEGORY_CASH || accountModifyReq.Category > models.ACCOUNT_CATEGORY_INVESTMENT {
|
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
|
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)
|
accountAndSubAccounts, err := a.accounts.GetAccountAndSubAccountsByAccountId(c, uid, accountModifyReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.accounts.ModifyAccounts(c, uid, toUpdateAccounts)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
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
|
// 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
|
var accountHideReq models.AccountHideRequest
|
||||||
err := c.ShouldBindJSON(&accountHideReq)
|
err := c.ShouldBindJSON(&accountHideReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.accounts.HideAccount(c, uid, []int64{accountHideReq.Id}, accountHideReq.Hidden)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// AccountMoveHandler moves display order of existed accounts by request parameters for current user
|
// 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
|
var accountMoveReq models.AccountMoveRequest
|
||||||
err := c.ShouldBindJSON(&accountMoveReq)
|
err := c.ShouldBindJSON(&accountMoveReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.accounts.ModifyAccountDisplayOrders(c, uid, accounts)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// AccountDeleteHandler deletes an existed account by request parameters for current user
|
// 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
|
var accountDeleteReq models.AccountDeleteRequest
|
||||||
err := c.ShouldBindJSON(&accountDeleteReq)
|
err := c.ShouldBindJSON(&accountDeleteReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.accounts.DeleteAccount(c, uid, accountDeleteReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// AmapApiProxyHandler returns amap api response
|
// 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
|
var targetUrl string
|
||||||
|
|
||||||
if strings.HasPrefix(c.Request.RequestURI, "/_AMapService/v4/map/styles") {
|
if strings.HasPrefix(c.Request.RequestURI, "/_AMapService/v4/map/styles") {
|
||||||
|
|||||||
+31
-31
@@ -32,24 +32,24 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// AuthorizeHandler verifies and authorizes current login request
|
// 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
|
var credential models.UserLoginRequest
|
||||||
err := c.ShouldBindJSON(&credential)
|
err := c.ShouldBindJSON(&credential)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrLoginNameOrPasswordInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := a.users.GetUserByUsernameOrEmailAndPassword(c, credential.LoginName, credential.Password)
|
user, err := a.users.GetUserByUsernameOrEmailAndPassword(c, credential.LoginName, credential.Password)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrLoginNameOrPasswordWrong
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Disabled {
|
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
|
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)
|
hasValidEmailVerifyToken, err := a.tokens.ExistsValidTokenByType(c, user.Uid, core.USER_TOKEN_TYPE_EMAIL_VERIFY)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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{
|
return nil, errs.NewErrorWithContext(errs.ErrEmailIsNotVerified, map[string]any{
|
||||||
"email": user.Email,
|
"email": user.Email,
|
||||||
@@ -72,7 +72,7 @@ func (a *AuthorizationsApi) AuthorizeHandler(c *core.Context) (any, *errs.Error)
|
|||||||
err = a.users.UpdateUserLastLoginTime(c, user.Uid)
|
err = a.users.UpdateUserLastLoginTime(c, user.Uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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)
|
twoFactorEnable, err = a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, user.Uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrSystemError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -96,7 +96,7 @@ func (a *AuthorizationsApi) AuthorizeHandler(c *core.Context) (any, *errs.Error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrTokenGenerating
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,19 +106,19 @@ func (a *AuthorizationsApi) AuthorizeHandler(c *core.Context) (any, *errs.Error)
|
|||||||
|
|
||||||
c.SetTokenClaims(claims)
|
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)
|
authResp := a.getAuthResponse(c, token, twoFactorEnable, user)
|
||||||
return authResp, nil
|
return authResp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TwoFactorAuthorizeHandler verifies and authorizes current 2fa login by passcode
|
// 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
|
var credential models.TwoFactorLoginRequest
|
||||||
err := c.ShouldBindJSON(&credential)
|
err := c.ShouldBindJSON(&credential)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrPasscodeInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,29 +126,29 @@ func (a *AuthorizationsApi) TwoFactorAuthorizeHandler(c *core.Context) (any, *er
|
|||||||
twoFactorSetting, err := a.twoFactorAuthorizations.GetUserTwoFactorSettingByUid(c, uid)
|
twoFactorSetting, err := a.twoFactorAuthorizations.GetUserTwoFactorSettingByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrSystemError)
|
||||||
}
|
}
|
||||||
|
|
||||||
if !totp.Validate(credential.Passcode, twoFactorSetting.Secret) {
|
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
|
return nil, errs.ErrPasscodeInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := a.users.GetUserById(c, uid)
|
user, err := a.users.GetUserById(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Disabled {
|
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
|
return nil, errs.ErrUserIsDisabled
|
||||||
}
|
}
|
||||||
|
|
||||||
if a.CurrentConfig().EnableUserForceVerifyEmail && !user.EmailVerified {
|
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
|
return nil, errs.ErrEmailIsNotVerified
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,32 +156,32 @@ func (a *AuthorizationsApi) TwoFactorAuthorizeHandler(c *core.Context) (any, *er
|
|||||||
err = a.tokens.DeleteTokenByClaims(c, oldTokenClaims)
|
err = a.tokens.DeleteTokenByClaims(c, oldTokenClaims)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
token, claims, err := a.tokens.CreateToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrTokenGenerating
|
||||||
}
|
}
|
||||||
|
|
||||||
c.SetTextualToken(token)
|
c.SetTextualToken(token)
|
||||||
c.SetTokenClaims(claims)
|
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)
|
authResp := a.getAuthResponse(c, token, false, user)
|
||||||
return authResp, nil
|
return authResp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TwoFactorAuthorizeByRecoveryCodeHandler verifies and authorizes current 2fa login by recovery code
|
// 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
|
var credential models.TwoFactorRecoveryCodeLoginRequest
|
||||||
err := c.ShouldBindJSON(&credential)
|
err := c.ShouldBindJSON(&credential)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrTwoFactorRecoveryCodeInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,7 +189,7 @@ func (a *AuthorizationsApi) TwoFactorAuthorizeByRecoveryCodeHandler(c *core.Cont
|
|||||||
enableTwoFactor, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
|
enableTwoFactor, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
user, err := a.users.GetUserById(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Disabled {
|
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
|
return nil, errs.ErrUserIsDisabled
|
||||||
}
|
}
|
||||||
|
|
||||||
if a.CurrentConfig().EnableUserForceVerifyEmail && !user.EmailVerified {
|
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
|
return nil, errs.ErrEmailIsNotVerified
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.twoFactorAuthorizations.GetAndUseUserTwoFactorRecoveryCode(c, uid, credential.RecoveryCode, user.Salt)
|
err = a.twoFactorAuthorizations.GetAndUseUserTwoFactorRecoveryCode(c, uid, credential.RecoveryCode, user.Salt)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrTwoFactorRecoveryCodeNotExist)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,26 +225,26 @@ func (a *AuthorizationsApi) TwoFactorAuthorizeByRecoveryCodeHandler(c *core.Cont
|
|||||||
err = a.tokens.DeleteTokenByClaims(c, oldTokenClaims)
|
err = a.tokens.DeleteTokenByClaims(c, oldTokenClaims)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
token, claims, err := a.tokens.CreateToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrTokenGenerating
|
||||||
}
|
}
|
||||||
|
|
||||||
c.SetTextualToken(token)
|
c.SetTextualToken(token)
|
||||||
c.SetTokenClaims(claims)
|
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)
|
authResp := a.getAuthResponse(c, token, false, user)
|
||||||
return authResp, nil
|
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{
|
return &models.AuthResponse{
|
||||||
Token: token,
|
Token: token,
|
||||||
Need2FA: need2FA,
|
Need2FA: need2FA,
|
||||||
|
|||||||
+25
-25
@@ -50,50 +50,50 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// ExportDataToEzbookkeepingCSVHandler returns exported data in csv format
|
// 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")
|
return a.getExportedFileContent(c, "csv")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportDataToEzbookkeepingTSVHandler returns exported data in csv format
|
// 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")
|
return a.getExportedFileContent(c, "tsv")
|
||||||
}
|
}
|
||||||
|
|
||||||
// DataStatisticsHandler returns user data statistics
|
// 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()
|
uid := c.GetCurrentUid()
|
||||||
totalAccountCount, err := a.accounts.GetTotalAccountCountByUid(c, uid)
|
totalAccountCount, err := a.accounts.GetTotalAccountCountByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
totalTransactionCategoryCount, err := a.categories.GetTotalCategoryCountByUid(c, uid)
|
totalTransactionCategoryCount, err := a.categories.GetTotalCategoryCountByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
totalTransactionTagCount, err := a.tags.GetTotalTagCountByUid(c, uid)
|
totalTransactionTagCount, err := a.tags.GetTotalTagCountByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
totalTransactionCount, err := a.transactions.GetTotalTransactionCountByUid(c, uid)
|
totalTransactionCount, err := a.transactions.GetTotalTransactionCountByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
totalTransactionTemplateCount, err := a.templates.GetTotalNormalTemplateCountByUid(c, uid)
|
totalTransactionTemplateCount, err := a.templates.GetTotalNormalTemplateCountByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,12 +109,12 @@ func (a *DataManagementsApi) DataStatisticsHandler(c *core.Context) (any, *errs.
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ClearDataHandler deletes all user data
|
// 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
|
var clearDataReq models.ClearDataRequest
|
||||||
err := c.ShouldBindJSON(&clearDataReq)
|
err := c.ShouldBindJSON(&clearDataReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,7 +123,7 @@ func (a *DataManagementsApi) ClearDataHandler(c *core.Context) (any, *errs.Error
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
@@ -136,36 +136,36 @@ func (a *DataManagementsApi) ClearDataHandler(c *core.Context) (any, *errs.Error
|
|||||||
err = a.transactions.DeleteAllTransactions(c, uid)
|
err = a.transactions.DeleteAllTransactions(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.categories.DeleteAllCategories(c, uid)
|
err = a.categories.DeleteAllCategories(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.tags.DeleteAllTags(c, uid)
|
err = a.tags.DeleteAllTags(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.templates.DeleteAllTemplates(c, uid)
|
err = a.templates.DeleteAllTemplates(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
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 {
|
if !a.CurrentConfig().EnableDataExport {
|
||||||
return nil, "", errs.ErrDataExportNotAllowed
|
return nil, "", errs.ErrDataExportNotAllowed
|
||||||
}
|
}
|
||||||
@@ -174,7 +174,7 @@ func (a *DataManagementsApi) getExportedFileContent(c *core.Context, fileType st
|
|||||||
utcOffset, err := c.GetClientTimezoneOffset()
|
utcOffset, err := c.GetClientTimezoneOffset()
|
||||||
|
|
||||||
if err != nil {
|
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 {
|
} else {
|
||||||
timezone = time.FixedZone("Client Timezone", int(utcOffset)*60)
|
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 err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, "", errs.ErrUserNotFound
|
||||||
@@ -193,28 +193,28 @@ func (a *DataManagementsApi) getExportedFileContent(c *core.Context, fileType st
|
|||||||
accounts, err := a.accounts.GetAllAccountsByUid(c, uid)
|
accounts, err := a.accounts.GetAllAccountsByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, "", errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
categories, err := a.categories.GetAllCategoriesByUid(c, uid, 0, -1)
|
categories, err := a.categories.GetAllCategoriesByUid(c, uid, 0, -1)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, "", errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
tags, err := a.tags.GetAllTagsByUid(c, uid)
|
tags, err := a.tags.GetAllTagsByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, "", errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
tagIndexes, err := a.tags.GetAllTagIdsMapOfAllTransactions(c, uid)
|
tagIndexes, err := a.tags.GetAllTagIdsMapOfAllTransactions(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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)
|
allTransactions, err := a.transactions.GetAllTransactions(c, uid, pageCountForDataExport, true)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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)
|
result, err := dataExporter.ToExportedContent(uid, allTransactions, accountMap, categoryMap, tagMap, tagIndexes)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, "", errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -14,11 +14,11 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// ApiNotFound returns api not found error
|
// 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
|
return nil, errs.ErrApiNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
// MethodNotAllowed returns method not allowed error
|
// 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
|
return nil, errs.ErrMethodNotAllowed
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// LatestExchangeRateHandler returns latest exchange rate data
|
// 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
|
dataSource := exchangerates.Container.Current
|
||||||
|
|
||||||
if dataSource == nil {
|
if dataSource == nil {
|
||||||
@@ -65,12 +65,12 @@ func (a *ExchangeRatesApi) LatestExchangeRateHandler(c *core.Context) (any, *err
|
|||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode != 200 {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,7 +79,7 @@ func (a *ExchangeRatesApi) LatestExchangeRateHandler(c *core.Context) (any, *err
|
|||||||
exchangeRateResp, err := dataSource.Parse(c, body)
|
exchangeRateResp, err := dataSource.Parse(c, body)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrFailedToRequestRemoteApi)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+17
-17
@@ -32,12 +32,12 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// UserForgetPasswordRequestHandler generates password reset link and send user an email with this link
|
// 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
|
var request models.ForgetPasswordRequest
|
||||||
err := c.ShouldBindJSON(&request)
|
err := c.ShouldBindJSON(&request)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrEmailIsEmptyOrInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,19 +45,19 @@ func (a *ForgetPasswordsApi) UserForgetPasswordRequestHandler(c *core.Context) (
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Disabled {
|
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
|
return nil, errs.ErrUserIsDisabled
|
||||||
}
|
}
|
||||||
|
|
||||||
if a.CurrentConfig().ForgetPasswordRequireVerifyEmail && !user.EmailVerified {
|
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
|
return nil, errs.ErrEmailIsNotVerified
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,7 +68,7 @@ func (a *ForgetPasswordsApi) UserForgetPasswordRequestHandler(c *core.Context) (
|
|||||||
token, _, err := a.tokens.CreatePasswordResetToken(c, user)
|
token, _, err := a.tokens.CreatePasswordResetToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrTokenGenerating
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ func (a *ForgetPasswordsApi) UserForgetPasswordRequestHandler(c *core.Context) (
|
|||||||
err = a.forgetPasswords.SendPasswordResetEmail(c, user, token, c.GetClientLocale())
|
err = a.forgetPasswords.SendPasswordResetEmail(c, user, token, c.GetClientLocale())
|
||||||
|
|
||||||
if err != nil {
|
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
|
// 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
|
var request models.PasswordResetRequest
|
||||||
err := c.ShouldBindJSON(&request)
|
err := c.ShouldBindJSON(&request)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,24 +98,24 @@ func (a *ForgetPasswordsApi) UserResetPasswordHandler(c *core.Context) (any, *er
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Disabled {
|
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
|
return nil, errs.ErrUserIsDisabled
|
||||||
}
|
}
|
||||||
|
|
||||||
if a.CurrentConfig().ForgetPasswordRequireVerifyEmail && !user.EmailVerified {
|
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
|
return nil, errs.ErrEmailIsNotVerified
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Email != request.Email {
|
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
|
return nil, errs.ErrEmptyIsInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,7 +124,7 @@ func (a *ForgetPasswordsApi) UserResetPasswordHandler(c *core.Context) (any, *er
|
|||||||
err = a.tokens.DeleteTokenByClaims(c, oldTokenClaims)
|
err = a.tokens.DeleteTokenByClaims(c, oldTokenClaims)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrNewPasswordEqualsOldInvalid
|
||||||
@@ -139,7 +139,7 @@ func (a *ForgetPasswordsApi) UserResetPasswordHandler(c *core.Context) (any, *er
|
|||||||
_, _, err = a.users.UpdateUser(c, userNew, false)
|
_, _, err = a.users.UpdateUser(c, userNew, false)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.tokens.DeleteTokensBeforeTime(c, uid, now)
|
||||||
|
|
||||||
if err == nil {
|
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 {
|
} 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
|
return true, nil
|
||||||
|
|||||||
+1
-1
@@ -15,7 +15,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// HealthStatusHandler returns the health status of current service
|
// 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 := make(map[string]string)
|
||||||
|
|
||||||
result["version"] = settings.Version
|
result["version"] = settings.Version
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// MapTileImageProxyHandler returns map tile image
|
// MapTileImageProxyHandler returns map tile image
|
||||||
func (p *MapImageProxy) MapTileImageProxyHandler(c *core.Context) (*httputil.ReverseProxy, *errs.Error) {
|
func (p *MapImageProxy) MapTileImageProxyHandler(c *core.WebContext) (*httputil.ReverseProxy, *errs.Error) {
|
||||||
return p.mapImageProxyHandler(c, func(c *core.Context, mapProvider string) (string, *errs.Error) {
|
return p.mapImageProxyHandler(c, func(c *core.WebContext, mapProvider string) (string, *errs.Error) {
|
||||||
if mapProvider == settings.OpenStreetMapProvider {
|
if mapProvider == settings.OpenStreetMapProvider {
|
||||||
return openStreetMapTileImageUrlFormat, nil
|
return openStreetMapTileImageUrlFormat, nil
|
||||||
} else if mapProvider == settings.OpenStreetMapHumanitarianStyleProvider {
|
} else if mapProvider == settings.OpenStreetMapHumanitarianStyleProvider {
|
||||||
@@ -71,8 +71,8 @@ func (p *MapImageProxy) MapTileImageProxyHandler(c *core.Context) (*httputil.Rev
|
|||||||
}
|
}
|
||||||
|
|
||||||
// MapAnnotationImageProxyHandler returns map annotation image
|
// MapAnnotationImageProxyHandler returns map annotation image
|
||||||
func (p *MapImageProxy) MapAnnotationImageProxyHandler(c *core.Context) (*httputil.ReverseProxy, *errs.Error) {
|
func (p *MapImageProxy) MapAnnotationImageProxyHandler(c *core.WebContext) (*httputil.ReverseProxy, *errs.Error) {
|
||||||
return p.mapImageProxyHandler(c, func(c *core.Context, mapProvider string) (string, *errs.Error) {
|
return p.mapImageProxyHandler(c, func(c *core.WebContext, mapProvider string) (string, *errs.Error) {
|
||||||
if mapProvider == settings.TianDiTuProvider {
|
if mapProvider == settings.TianDiTuProvider {
|
||||||
return tianDiTuMapAnnotationUrlFormat + "&tk=" + p.CurrentConfig().TianDiTuAPIKey, nil
|
return tianDiTuMapAnnotationUrlFormat + "&tk=" + p.CurrentConfig().TianDiTuAPIKey, nil
|
||||||
} else if mapProvider == settings.CustomProvider {
|
} 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)
|
mapProvider := strings.Replace(c.Query("provider"), "-", "_", -1)
|
||||||
targetUrl := ""
|
targetUrl := ""
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -32,7 +32,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// MobileUrlQrCodeHandler returns a mobile url qr code image
|
// 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"
|
fullUrl := a.CurrentConfig().RootUrl + "mobile"
|
||||||
data, err := a.generateUrlQrCode(c, fullUrl)
|
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
|
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, _ := qr.Encode(url, qr.M, qr.Auto)
|
||||||
qrCodeImg, _ = barcode.Scale(qrCodeImg, qrCodeDefaultWidth, qrCodeDefaultHeight)
|
qrCodeImg, _ = barcode.Scale(qrCodeImg, qrCodeDefaultWidth, qrCodeDefaultHeight)
|
||||||
imgData := &bytes.Buffer{}
|
imgData := &bytes.Buffer{}
|
||||||
|
|||||||
+23
-23
@@ -32,12 +32,12 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// TokenListHandler returns available token list of current user
|
// 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()
|
uid := c.GetCurrentUid()
|
||||||
tokens, err := a.tokens.GetAllUnexpiredNormalTokensByUid(c, uid)
|
tokens, err := a.tokens.GetAllUnexpiredNormalTokensByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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)
|
_, claims, err := a.tokens.ParseTokenByHeader(c)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -76,7 +76,7 @@ func (a *TokensApi) TokenRevokeCurrentHandler(c *core.Context) (any, *errs.Error
|
|||||||
userTokenId, err := utils.StringToInt64(claims.UserTokenId)
|
userTokenId, err := utils.StringToInt64(claims.UserTokenId)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.tokens.DeleteToken(c, tokenRecord)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TokenRevokeHandler revokes specific token of current user
|
// 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
|
var tokenRevokeReq models.TokenRevokeRequest
|
||||||
err := c.ShouldBindJSON(&tokenRevokeReq)
|
err := c.ShouldBindJSON(&tokenRevokeReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,7 +112,7 @@ func (a *TokensApi) TokenRevokeHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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)
|
return nil, errs.Or(err, errs.ErrInvalidTokenId)
|
||||||
@@ -121,28 +121,28 @@ func (a *TokensApi) TokenRevokeHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
uid := c.GetCurrentUid()
|
uid := c.GetCurrentUid()
|
||||||
|
|
||||||
if tokenRecord.Uid != uid {
|
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
|
return nil, errs.ErrInvalidTokenId
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.tokens.DeleteToken(c, tokenRecord)
|
err = a.tokens.DeleteToken(c, tokenRecord)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TokenRevokeAllHandler revokes all tokens of current user except current token
|
// 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()
|
uid := c.GetCurrentUid()
|
||||||
tokens, err := a.tokens.GetAllTokensByUid(c, uid)
|
tokens, err := a.tokens.GetAllTokensByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.tokens.DeleteTokens(c, uid, tokens)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TokenRefreshHandler refresh current token of current user
|
// 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()
|
uid := c.GetCurrentUid()
|
||||||
user, err := a.users.GetUserById(c, uid)
|
user, err := a.users.GetUserById(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,12 +185,12 @@ func (a *TokensApi) TokenRefreshHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
oldTokenClaims := c.GetTokenClaims()
|
oldTokenClaims := c.GetTokenClaims()
|
||||||
|
|
||||||
if now-oldTokenClaims.IssuedAt < int64(a.CurrentConfig().TokenMinRefreshInterval) {
|
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)
|
userTokenId, err := utils.StringToInt64(oldTokenClaims.UserTokenId)
|
||||||
|
|
||||||
if err != nil {
|
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 {
|
} else {
|
||||||
tokenRecord := &models.TokenRecord{
|
tokenRecord := &models.TokenRecord{
|
||||||
Uid: oldTokenClaims.Uid,
|
Uid: oldTokenClaims.Uid,
|
||||||
@@ -203,7 +203,7 @@ func (a *TokensApi) TokenRefreshHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
err = a.tokens.UpdateTokenLastSeen(c, tokenRecord)
|
err = a.tokens.UpdateTokenLastSeen(c, tokenRecord)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
token, claims, err := a.tokens.CreateToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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.SetTextualToken(token)
|
||||||
c.SetTokenClaims(claims)
|
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{
|
refreshResp := &models.TokenRefreshResponse{
|
||||||
NewToken: token,
|
NewToken: token,
|
||||||
|
|||||||
@@ -36,12 +36,12 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// CategoryListHandler returns transaction category list of current user
|
// 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
|
var categoryListReq models.TransactionCategoryListRequest
|
||||||
err := c.ShouldBindQuery(&categoryListReq)
|
err := c.ShouldBindQuery(&categoryListReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
categories, err := a.categories.GetAllCategoriesByUid(c, uid, categoryListReq.Type, categoryListReq.ParentId)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var categoryGetReq models.TransactionCategoryGetRequest
|
||||||
err := c.ShouldBindQuery(&categoryGetReq)
|
err := c.ShouldBindQuery(&categoryGetReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
category, err := a.categories.GetCategoryByCategoryId(c, uid, categoryGetReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var categoryCreateReq models.TransactionCategoryCreateRequest
|
||||||
err := c.ShouldBindJSON(&categoryCreateReq)
|
err := c.ShouldBindJSON(&categoryCreateReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if categoryCreateReq.Type < models.CATEGORY_TYPE_INCOME || categoryCreateReq.Type > models.CATEGORY_TYPE_TRANSFER {
|
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
|
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)
|
parentCategory, err := a.categories.GetCategoryByCategoryId(c, uid, categoryCreateReq.ParentId)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
if parentCategory == nil {
|
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
|
return nil, errs.ErrParentTransactionCategoryNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if parentCategory.ParentCategoryId > 0 {
|
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
|
return nil, errs.ErrCannotAddToSecondaryTransactionCategory
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,7 +124,7 @@ func (a *TransactionCategoriesApi) CategoryCreateHandler(c *core.Context) (any,
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
found, remark := a.GetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_CATEGORY, uid, categoryCreateReq.ClientSessionId)
|
||||||
|
|
||||||
if found {
|
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)
|
categoryId, err := utils.StringToInt64(remark)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
category, err = a.categories.GetCategoryByCategoryId(c, uid, categoryId)
|
category, err = a.categories.GetCategoryByCategoryId(c, uid, categoryId)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.categories.CreateCategory(c, category)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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))
|
a.SetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_CATEGORY, uid, categoryCreateReq.ClientSessionId, utils.Int64ToString(category.CategoryId))
|
||||||
categoryResp := category.ToTransactionCategoryInfoResponse()
|
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
|
// 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
|
var categoryCreateBatchReq models.TransactionCategoryCreateBatchRequest
|
||||||
err := c.ShouldBindBodyWith(&categoryCreateBatchReq, binding.JSON)
|
err := c.ShouldBindBodyWith(&categoryCreateBatchReq, binding.JSON)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var categoryModifyReq models.TransactionCategoryModifyRequest
|
||||||
err := c.ShouldBindJSON(&categoryModifyReq)
|
err := c.ShouldBindJSON(&categoryModifyReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
category, err := a.categories.GetCategoryByCategoryId(c, uid, categoryModifyReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
fromPrimaryCategory, err := a.categories.GetCategoryByCategoryId(c, uid, category.ParentCategoryId)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
toPrimaryCategory, err := a.categories.GetCategoryByCategoryId(c, uid, newCategory.ParentCategoryId)
|
toPrimaryCategory, err := a.categories.GetCategoryByCategoryId(c, uid, newCategory.ParentCategoryId)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.categories.ModifyCategory(c, newCategory)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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.Type = category.Type
|
||||||
newCategory.DisplayOrder = category.DisplayOrder
|
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
|
// 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
|
var categoryHideReq models.TransactionCategoryHideRequest
|
||||||
err := c.ShouldBindJSON(&categoryHideReq)
|
err := c.ShouldBindJSON(&categoryHideReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.categories.HideCategory(c, uid, []int64{categoryHideReq.Id}, categoryHideReq.Hidden)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CategoryMoveHandler moves display order of existed transaction categories by request parameters for current user
|
// 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
|
var categoryMoveReq models.TransactionCategoryMoveRequest
|
||||||
err := c.ShouldBindJSON(&categoryMoveReq)
|
err := c.ShouldBindJSON(&categoryMoveReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.categories.ModifyCategoryDisplayOrders(c, uid, categories)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CategoryDeleteHandler deletes an existed transaction category by request parameters for current user
|
// 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
|
var categoryDeleteReq models.TransactionCategoryDeleteRequest
|
||||||
err := c.ShouldBindJSON(&categoryDeleteReq)
|
err := c.ShouldBindJSON(&categoryDeleteReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.categories.DeleteCategory(c, uid, categoryDeleteReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
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
|
var err error
|
||||||
categoryTypeMaxOrderMap := make(map[models.TransactionCategoryType]int32)
|
categoryTypeMaxOrderMap := make(map[models.TransactionCategoryType]int32)
|
||||||
categoriesMap := make(map[*models.TransactionCategory][]*models.TransactionCategory)
|
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)
|
maxOrderId, err = a.categories.GetMaxDisplayOrder(c, uid, categoryCreateReq.Type)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
categories, err := a.categories.CreateCategories(c, uid, categoriesMap)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return categories, nil
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-27
@@ -23,12 +23,12 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// TagListHandler returns transaction tag list of current user
|
// 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()
|
uid := c.GetCurrentUid()
|
||||||
tags, err := a.tags.GetAllTagsByUid(c, uid)
|
tags, err := a.tags.GetAllTagsByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var tagGetReq models.TransactionTagGetRequest
|
||||||
err := c.ShouldBindQuery(&tagGetReq)
|
err := c.ShouldBindQuery(&tagGetReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
tag, err := a.tags.GetTagByTagId(c, uid, tagGetReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var tagCreateReq models.TransactionTagCreateRequest
|
||||||
err := c.ShouldBindJSON(&tagCreateReq)
|
err := c.ShouldBindJSON(&tagCreateReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
maxOrderId, err := a.tags.GetMaxDisplayOrder(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.tags.CreateTag(c, tag)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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()
|
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
|
// 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
|
var tagModifyReq models.TransactionTagModifyRequest
|
||||||
err := c.ShouldBindJSON(&tagModifyReq)
|
err := c.ShouldBindJSON(&tagModifyReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
tag, err := a.tags.GetTagByTagId(c, uid, tagModifyReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.tags.ModifyTag(c, newTag)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
tag.Name = newTag.Name
|
||||||
tagResp := tag.ToTransactionTagInfoResponse()
|
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
|
// 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
|
var tagHideReq models.TransactionTagHideRequest
|
||||||
err := c.ShouldBindJSON(&tagHideReq)
|
err := c.ShouldBindJSON(&tagHideReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.tags.HideTag(c, uid, []int64{tagHideReq.Id}, tagHideReq.Hidden)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TagMoveHandler moves display order of existed transaction tags by request parameters for current user
|
// 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
|
var tagMoveReq models.TransactionTagMoveRequest
|
||||||
err := c.ShouldBindJSON(&tagMoveReq)
|
err := c.ShouldBindJSON(&tagMoveReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.tags.ModifyTagDisplayOrders(c, uid, tags)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TagDeleteHandler deletes an existed transaction tag by request parameters for current user
|
// 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
|
var tagDeleteReq models.TransactionTagDeleteRequest
|
||||||
err := c.ShouldBindJSON(&tagDeleteReq)
|
err := c.ShouldBindJSON(&tagDeleteReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.tags.DeleteTag(c, uid, tagDeleteReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,17 +35,17 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// TemplateListHandler returns transaction template list of current user
|
// 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
|
var templateListReq models.TransactionTemplateListRequest
|
||||||
err := c.ShouldBindQuery(&templateListReq)
|
err := c.ShouldBindQuery(&templateListReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if templateListReq.TemplateType < models.TRANSACTION_TEMPLATE_TYPE_NORMAL || templateListReq.TemplateType > models.TRANSACTION_TEMPLATE_TYPE_NORMAL {
|
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
|
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)
|
templates, err := a.templates.GetAllTemplatesByUid(c, uid, templateListReq.TemplateType)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var templateGetReq models.TransactionTemplateGetRequest
|
||||||
err := c.ShouldBindQuery(&templateGetReq)
|
err := c.ShouldBindQuery(&templateGetReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
template, err := a.templates.GetTemplateByTemplateId(c, uid, templateGetReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var templateCreateReq models.TransactionTemplateCreateRequest
|
||||||
err := c.ShouldBindJSON(&templateCreateReq)
|
err := c.ShouldBindJSON(&templateCreateReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if templateCreateReq.TemplateType < models.TRANSACTION_TEMPLATE_TYPE_NORMAL || templateCreateReq.TemplateType > models.TRANSACTION_TEMPLATE_TYPE_NORMAL {
|
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
|
return nil, errs.ErrTransactionTemplateTypeInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
if templateCreateReq.Type <= models.TRANSACTION_TYPE_MODIFY_BALANCE || templateCreateReq.Type > models.TRANSACTION_TYPE_TRANSFER {
|
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
|
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)
|
maxOrderId, err := a.templates.GetMaxDisplayOrder(c, uid, templateCreateReq.TemplateType)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
found, remark := a.GetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_TEMPLATE, uid, templateCreateReq.ClientSessionId)
|
||||||
|
|
||||||
if found {
|
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)
|
templateId, err := utils.StringToInt64(remark)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
template, err = a.templates.GetTemplateByTemplateId(c, uid, templateId)
|
template, err = a.templates.GetTemplateByTemplateId(c, uid, templateId)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.templates.CreateTemplate(c, template)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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))
|
a.SetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_TEMPLATE, uid, templateCreateReq.ClientSessionId, utils.Int64ToString(template.TemplateId))
|
||||||
templateResp := template.ToTransactionTemplateInfoResponse(serverUtcOffset)
|
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
|
// 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
|
var templateModifyReq models.TransactionTemplateModifyRequest
|
||||||
err := c.ShouldBindJSON(&templateModifyReq)
|
err := c.ShouldBindJSON(&templateModifyReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if templateModifyReq.Type <= models.TRANSACTION_TYPE_MODIFY_BALANCE || templateModifyReq.Type > models.TRANSACTION_TYPE_TRANSFER {
|
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
|
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)
|
template, err := a.templates.GetTemplateByTemplateId(c, uid, templateModifyReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.templates.ModifyTemplate(c, newTemplate)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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()
|
serverUtcOffset := utils.GetServerTimezoneOffsetMinutes()
|
||||||
newTemplate.TemplateType = template.TemplateType
|
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
|
// 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
|
var templateHideReq models.TransactionTemplateHideRequest
|
||||||
err := c.ShouldBindJSON(&templateHideReq)
|
err := c.ShouldBindJSON(&templateHideReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.templates.HideTemplate(c, uid, []int64{templateHideReq.Id}, templateHideReq.Hidden)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TemplateMoveHandler moves display order of existed transaction templates by request parameters for current user
|
// 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
|
var templateMoveReq models.TransactionTemplateMoveRequest
|
||||||
err := c.ShouldBindJSON(&templateMoveReq)
|
err := c.ShouldBindJSON(&templateMoveReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.templates.ModifyTemplateDisplayOrders(c, uid, templates)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TemplateDeleteHandler deletes an existed transaction template by request parameters for current user
|
// 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
|
var templateDeleteReq models.TransactionTemplateDeleteRequest
|
||||||
err := c.ShouldBindJSON(&templateDeleteReq)
|
err := c.ShouldBindJSON(&templateDeleteReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.templates.DeleteTemplate(c, uid, templateDeleteReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+94
-94
@@ -45,12 +45,12 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// TransactionCountHandler returns transaction total count of current user
|
// 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
|
var transactionCountReq models.TransactionCountRequest
|
||||||
err := c.ShouldBindQuery(&transactionCountReq)
|
err := c.ShouldBindQuery(&transactionCountReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
allAccountIds, err := a.getAccountOrSubAccountIds(c, transactionCountReq.AccountIds, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
allCategoryIds, err := a.getCategoryOrSubCategoryIds(c, transactionCountReq.CategoryIds, uid)
|
allCategoryIds, err := a.getCategoryOrSubCategoryIds(c, transactionCountReq.CategoryIds, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
allTagIds, err = a.getTagIds(transactionCountReq.TagIds)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
totalCount, err := a.transactions.GetTransactionCount(c, uid, transactionCountReq.MaxTime, transactionCountReq.MinTime, transactionCountReq.Type, allCategoryIds, allAccountIds, allTagIds, noTags, transactionCountReq.AmountFilter, transactionCountReq.Keyword)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var transactionListReq models.TransactionListByMaxTimeRequest
|
||||||
err := c.ShouldBindQuery(&transactionListReq)
|
err := c.ShouldBindQuery(&transactionListReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
utcOffset, err := c.GetClientTimezoneOffset()
|
utcOffset, err := c.GetClientTimezoneOffset()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrClientTimezoneOffsetInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,7 +118,7 @@ func (a *TransactionsApi) TransactionListHandler(c *core.Context) (any, *errs.Er
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
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)
|
allAccountIds, err := a.getAccountOrSubAccountIds(c, transactionListReq.AccountIds, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
allCategoryIds, err := a.getCategoryOrSubCategoryIds(c, transactionListReq.CategoryIds, uid)
|
allCategoryIds, err := a.getCategoryOrSubCategoryIds(c, transactionListReq.CategoryIds, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
allTagIds, err = a.getTagIds(transactionListReq.TagIds)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
totalCount, err = a.transactions.GetTransactionCount(c, uid, transactionListReq.MaxTime, transactionListReq.MinTime, transactionListReq.Type, allCategoryIds, allAccountIds, allTagIds, noTags, transactionListReq.AmountFilter, transactionListReq.Keyword)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
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 {
|
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)
|
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)
|
transactionResult, err := a.getTransactionListResult(c, user, transactions, utcOffset, transactionListReq.TrimAccount, transactionListReq.TrimCategory, transactionListReq.TrimTag)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var transactionListReq models.TransactionListInMonthByPageRequest
|
||||||
err := c.ShouldBindQuery(&transactionListReq)
|
err := c.ShouldBindQuery(&transactionListReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
utcOffset, err := c.GetClientTimezoneOffset()
|
utcOffset, err := c.GetClientTimezoneOffset()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrClientTimezoneOffsetInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,7 +221,7 @@ func (a *TransactionsApi) TransactionMonthListHandler(c *core.Context) (any, *er
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
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)
|
allAccountIds, err := a.getAccountOrSubAccountIds(c, transactionListReq.AccountIds, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
allCategoryIds, err := a.getCategoryOrSubCategoryIds(c, transactionListReq.CategoryIds, uid)
|
allCategoryIds, err := a.getCategoryOrSubCategoryIds(c, transactionListReq.CategoryIds, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
allTagIds, err = a.getTagIds(transactionListReq.TagIds)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
transactions, err := a.transactions.GetTransactionsInMonthByPage(c, uid, transactionListReq.Year, transactionListReq.Month, transactionListReq.Type, allCategoryIds, allAccountIds, allTagIds, noTags, transactionListReq.AmountFilter, transactionListReq.Keyword)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
transactionResult, err := a.getTransactionListResult(c, user, transactions, utcOffset, transactionListReq.TrimAccount, transactionListReq.TrimCategory, transactionListReq.TrimTag)
|
transactionResult, err := a.getTransactionListResult(c, user, transactions, utcOffset, transactionListReq.TrimAccount, transactionListReq.TrimCategory, transactionListReq.TrimTag)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var statisticReq models.TransactionStatisticRequest
|
||||||
err := c.ShouldBindQuery(&statisticReq)
|
err := c.ShouldBindQuery(&statisticReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
utcOffset, err := c.GetClientTimezoneOffset()
|
utcOffset, err := c.GetClientTimezoneOffset()
|
||||||
|
|
||||||
if err != nil {
|
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
|
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)
|
totalAmounts, err := a.transactions.GetAccountsAndCategoriesTotalIncomeAndExpense(c, uid, statisticReq.StartTime, statisticReq.EndTime, utcOffset, statisticReq.UseTransactionTimezone)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var statisticTrendsReq models.TransactionStatisticTrendsRequest
|
||||||
err := c.ShouldBindQuery(&statisticTrendsReq)
|
err := c.ShouldBindQuery(&statisticTrendsReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
utcOffset, err := c.GetClientTimezoneOffset()
|
utcOffset, err := c.GetClientTimezoneOffset()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrClientTimezoneOffsetInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
startYear, startMonth, endYear, endMonth, err := statisticTrendsReq.GetNumericYearMonthRange()
|
startYear, startMonth, endYear, endMonth, err := statisticTrendsReq.GetNumericYearMonthRange()
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
allMonthlyTotalAmounts, err := a.transactions.GetAccountsAndCategoriesMonthlyIncomeAndExpense(c, uid, startYear, startMonth, endYear, endMonth, utcOffset, statisticTrendsReq.UseTransactionTimezone)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var transactionAmountsReq models.TransactionAmountsRequest
|
||||||
err := c.ShouldBindQuery(&transactionAmountsReq)
|
err := c.ShouldBindQuery(&transactionAmountsReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
requestItems, err := transactionAmountsReq.GetTransactionAmountsRequestItems()
|
requestItems, err := transactionAmountsReq.GetTransactionAmountsRequestItems()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrQueryItemsInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(requestItems) < 1 {
|
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
|
return nil, errs.ErrQueryItemsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(requestItems) > 20 {
|
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
|
return nil, errs.ErrQueryItemsTooMuch
|
||||||
}
|
}
|
||||||
|
|
||||||
utcOffset, err := c.GetClientTimezoneOffset()
|
utcOffset, err := c.GetClientTimezoneOffset()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrClientTimezoneOffsetInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -417,7 +417,7 @@ func (a *TransactionsApi) TransactionAmountsHandler(c *core.Context) (any, *errs
|
|||||||
accountMap := a.accounts.GetAccountMapByList(accounts)
|
accountMap := a.accounts.GetAccountMapByList(accounts)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
incomeAmounts, expenseAmounts, err := a.transactions.GetAccountsTotalIncomeAndExpense(c, uid, requestItem.StartTime, requestItem.EndTime, utcOffset, transactionAmountsReq.UseTransactionTimezone)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -439,7 +439,7 @@ func (a *TransactionsApi) TransactionAmountsHandler(c *core.Context) (any, *errs
|
|||||||
account, exists := accountMap[accountId]
|
account, exists := accountMap[accountId]
|
||||||
|
|
||||||
if !exists {
|
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
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -461,7 +461,7 @@ func (a *TransactionsApi) TransactionAmountsHandler(c *core.Context) (any, *errs
|
|||||||
account, exists := accountMap[accountId]
|
account, exists := accountMap[accountId]
|
||||||
|
|
||||||
if !exists {
|
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
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -498,19 +498,19 @@ func (a *TransactionsApi) TransactionAmountsHandler(c *core.Context) (any, *errs
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TransactionGetHandler returns one specific transaction of current user
|
// 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
|
var transactionGetReq models.TransactionGetRequest
|
||||||
err := c.ShouldBindQuery(&transactionGetReq)
|
err := c.ShouldBindQuery(&transactionGetReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
utcOffset, err := c.GetClientTimezoneOffset()
|
utcOffset, err := c.GetClientTimezoneOffset()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrClientTimezoneOffsetInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -519,7 +519,7 @@ func (a *TransactionsApi) TransactionGetHandler(c *core.Context) (any, *errs.Err
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
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)
|
transaction, err := a.transactions.GetTransactionByTransactionId(c, uid, transactionGetReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
accountMap, err := a.accounts.GetAccountsByAccountIds(c, uid, accountIds)
|
||||||
|
|
||||||
if _, exists := accountMap[transaction.AccountId]; !exists {
|
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
|
return nil, errs.ErrTransactionNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_OUT {
|
if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_OUT {
|
||||||
if _, exists := accountMap[transaction.RelatedAccountId]; !exists {
|
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
|
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})
|
allTransactionTagIds, err := a.transactionTags.GetAllTagIdsOfTransactions(c, uid, []int64{transaction.TransactionId})
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
category, err = a.transactionCategories.GetCategoryByCategoryId(c, uid, transaction.CategoryId)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)))
|
tagMap, err = a.transactionTags.GetTagsByTagIds(c, uid, utils.ToUniqueInt64Slice(a.getTransactionTagIds(allTransactionTagIds)))
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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
|
var transactionCreateReq models.TransactionCreateRequest
|
||||||
err := c.ShouldBindJSON(&transactionCreateReq)
|
err := c.ShouldBindJSON(&transactionCreateReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
tagIds, err := utils.StringArrayToInt64Array(transactionCreateReq.TagIds)
|
tagIds, err := utils.StringArrayToInt64Array(transactionCreateReq.TagIds)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrTransactionTagIdInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
if transactionCreateReq.Type < models.TRANSACTION_TYPE_MODIFY_BALANCE || transactionCreateReq.Type > models.TRANSACTION_TYPE_TRANSFER {
|
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
|
return nil, errs.ErrTransactionTypeInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
if transactionCreateReq.Type == models.TRANSACTION_TYPE_MODIFY_BALANCE && transactionCreateReq.CategoryId > 0 {
|
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
|
return nil, errs.ErrBalanceModificationTransactionCannotSetCategory
|
||||||
}
|
}
|
||||||
|
|
||||||
if transactionCreateReq.Type != models.TRANSACTION_TYPE_TRANSFER && transactionCreateReq.DestinationAccountId != 0 {
|
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
|
return nil, errs.ErrTransactionDestinationAccountCannotBeSet
|
||||||
} else if transactionCreateReq.Type == models.TRANSACTION_TYPE_TRANSFER && transactionCreateReq.SourceAccountId == transactionCreateReq.DestinationAccountId {
|
} 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
|
return nil, errs.ErrTransactionSourceAndDestinationIdCannotBeEqual
|
||||||
}
|
}
|
||||||
|
|
||||||
if transactionCreateReq.Type != models.TRANSACTION_TYPE_TRANSFER && transactionCreateReq.DestinationAmount != 0 {
|
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
|
return nil, errs.ErrTransactionDestinationAmountCannotBeSet
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -658,7 +658,7 @@ func (a *TransactionsApi) TransactionCreateHandler(c *core.Context) (any, *errs.
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
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)
|
found, remark := a.GetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_TRANSACTION, uid, transactionCreateReq.ClientSessionId)
|
||||||
|
|
||||||
if found {
|
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)
|
transactionId, err := utils.StringToInt64(remark)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
transaction, err = a.transactions.GetTransactionByTransactionId(c, uid, transactionId)
|
transaction, err = a.transactions.GetTransactionByTransactionId(c, uid, transactionId)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.transactions.CreateTransaction(c, transaction, tagIds)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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))
|
a.SetSubmissionRemark(duplicatechecker.DUPLICATE_CHECKER_TYPE_NEW_TRANSACTION, uid, transactionCreateReq.ClientSessionId, utils.Int64ToString(transaction.TransactionId))
|
||||||
transactionResp := transaction.ToTransactionInfoResponse(tagIds, transactionEditable)
|
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
|
// 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
|
var transactionModifyReq models.TransactionModifyRequest
|
||||||
err := c.ShouldBindJSON(&transactionModifyReq)
|
err := c.ShouldBindJSON(&transactionModifyReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
tagIds, err := utils.StringArrayToInt64Array(transactionModifyReq.TagIds)
|
tagIds, err := utils.StringArrayToInt64Array(transactionModifyReq.TagIds)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrTransactionTagIdInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -730,7 +730,7 @@ func (a *TransactionsApi) TransactionModifyHandler(c *core.Context) (any, *errs.
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
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)
|
transaction, err := a.transactions.GetTransactionByTransactionId(c, uid, transactionModifyReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_IN {
|
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
|
return nil, errs.ErrTransactionTypeInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
allTransactionTagIds, err := a.transactionTags.GetAllTagIdsOfTransactions(c, uid, []int64{transaction.TransactionId})
|
allTransactionTagIds, err := a.transactionTags.GetAllTagIdsOfTransactions(c, uid, []int64{transaction.TransactionId})
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.transactions.ModifyTransaction(c, newTransaction, len(transactionTagIds), addTransactionTagIds, removeTransactionTagIds)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
newTransaction.Type = transaction.Type
|
||||||
newTransactionResp := newTransaction.ToTransactionInfoResponse(tagIds, transactionEditable)
|
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
|
// 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
|
var transactionDeleteReq models.TransactionDeleteRequest
|
||||||
err := c.ShouldBindJSON(&transactionDeleteReq)
|
err := c.ShouldBindJSON(&transactionDeleteReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
utcOffset, err := c.GetClientTimezoneOffset()
|
utcOffset, err := c.GetClientTimezoneOffset()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrClientTimezoneOffsetInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -850,7 +850,7 @@ func (a *TransactionsApi) TransactionDeleteHandler(c *core.Context) (any, *errs.
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
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)
|
transaction, err := a.transactions.GetTransactionByTransactionId(c, uid, transactionDeleteReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_IN {
|
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
|
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)
|
err = a.transactions.DeleteTransaction(c, uid, transactionDeleteReq.Id)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
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))
|
finalTransactions := make([]*models.Transaction, 0, len(transactions))
|
||||||
|
|
||||||
for i := 0; i < len(transactions); i++ {
|
for i := 0; i < len(transactions); i++ {
|
||||||
transaction := transactions[i]
|
transaction := transactions[i]
|
||||||
|
|
||||||
if _, exists := accountMap[transaction.AccountId]; !exists {
|
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
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_IN || transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_OUT {
|
if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_IN || transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_OUT {
|
||||||
if _, exists := accountMap[transaction.RelatedAccountId]; !exists {
|
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
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -909,7 +909,7 @@ func (a *TransactionsApi) filterTransactions(c *core.Context, uid int64, transac
|
|||||||
return finalTransactions
|
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" {
|
if accountIds == "" || accountIds == "0" {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@@ -961,7 +961,7 @@ func (a *TransactionsApi) getAccountOrSubAccountIds(c *core.Context, accountIds
|
|||||||
return allAccountIds, nil
|
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" {
|
if categoryIds == "" || categoryIds == "0" {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@@ -1053,7 +1053,7 @@ func (a *TransactionsApi) getTransactionTagInfoResponses(tagIds []int64, allTran
|
|||||||
return allTags
|
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
|
uid := user.Uid
|
||||||
transactionIds := make([]int64, len(transactions))
|
transactionIds := make([]int64, len(transactions))
|
||||||
accountIds := make([]int64, 0, len(transactions)*2)
|
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))
|
allAccounts, err := a.accounts.GetAccountsByAccountIds(c, uid, utils.ToUniqueInt64Slice(accountIds))
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1088,7 +1088,7 @@ func (a *TransactionsApi) getTransactionListResult(c *core.Context, user *models
|
|||||||
allTransactionTagIds, err := a.transactionTags.GetAllTagIdsOfTransactions(c, uid, transactionIds)
|
allTransactionTagIds, err := a.transactionTags.GetAllTagIdsOfTransactions(c, uid, transactionIds)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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))
|
categoryMap, err = a.transactionCategories.GetCategoriesByCategoryIds(c, uid, utils.ToUniqueInt64Slice(categoryIds))
|
||||||
|
|
||||||
if err != nil {
|
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
|
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)))
|
tagMap, err = a.transactionTags.GetTagsByTagIds(c, uid, utils.ToUniqueInt64Slice(a.getTransactionTagIds(allTransactionTagIds)))
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// TwoFactorStatusHandler returns 2fa status of current user
|
// 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()
|
uid := c.GetCurrentUid()
|
||||||
twoFactorSetting, err := a.twoFactorAuthorizations.GetUserTwoFactorSettingByUid(c, uid)
|
twoFactorSetting, err := a.twoFactorAuthorizations.GetUserTwoFactorSettingByUid(c, uid)
|
||||||
|
|
||||||
@@ -45,7 +45,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorStatusHandler(c *core.Context) (an
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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()
|
uid := c.GetCurrentUid()
|
||||||
enabled, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
|
enabled, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,7 +75,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableRequestHandler(c *core.Conte
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
@@ -84,14 +84,14 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableRequestHandler(c *core.Conte
|
|||||||
key, err := a.twoFactorAuthorizations.GenerateTwoFactorSecret(c, user)
|
key, err := a.twoFactorAuthorizations.GenerateTwoFactorSecret(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
img, err := key.Image(240, 240)
|
img, err := key.Image(240, 240)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,12 +110,12 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableRequestHandler(c *core.Conte
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TwoFactorEnableConfirmHandler enables 2fa for current user
|
// 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
|
var confirmReq models.TwoFactorEnableConfirmRequest
|
||||||
err := c.ShouldBindJSON(&confirmReq)
|
err := c.ShouldBindJSON(&confirmReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,7 +123,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.Conte
|
|||||||
exists, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
|
exists, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,7 +135,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.Conte
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
@@ -147,46 +147,46 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.Conte
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !totp.Validate(confirmReq.Passcode, confirmReq.Secret) {
|
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
|
return nil, errs.ErrPasscodeInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
recoveryCodes, err := a.twoFactorAuthorizations.GenerateTwoFactorRecoveryCodes()
|
recoveryCodes, err := a.twoFactorAuthorizations.GenerateTwoFactorRecoveryCodes()
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.twoFactorAuthorizations.CreateTwoFactorRecoveryCodes(c, uid, recoveryCodes, user.Salt)
|
err = a.twoFactorAuthorizations.CreateTwoFactorRecoveryCodes(c, uid, recoveryCodes, user.Salt)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.twoFactorAuthorizations.CreateTwoFactorSetting(c, twoFactorSetting)
|
err = a.twoFactorAuthorizations.CreateTwoFactorSetting(c, twoFactorSetting)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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()
|
now := time.Now().Unix()
|
||||||
err = a.tokens.DeleteTokensBeforeTime(c, uid, now)
|
err = a.tokens.DeleteTokensBeforeTime(c, uid, now)
|
||||||
|
|
||||||
if err == nil {
|
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 {
|
} 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)
|
token, claims, err := a.tokens.CreateToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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{
|
confirmResp := &models.TwoFactorEnableConfirmResponse{
|
||||||
RecoveryCodes: recoveryCodes,
|
RecoveryCodes: recoveryCodes,
|
||||||
@@ -198,7 +198,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.Conte
|
|||||||
c.SetTextualToken(token)
|
c.SetTextualToken(token)
|
||||||
c.SetTokenClaims(claims)
|
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{
|
confirmResp := &models.TwoFactorEnableConfirmResponse{
|
||||||
Token: token,
|
Token: token,
|
||||||
@@ -209,12 +209,12 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorEnableConfirmHandler(c *core.Conte
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TwoFactorDisableHandler disables 2fa for current user
|
// 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
|
var disableReq models.TwoFactorDisableRequest
|
||||||
err := c.ShouldBindJSON(&disableReq)
|
err := c.ShouldBindJSON(&disableReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,7 +223,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorDisableHandler(c *core.Context) (a
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
@@ -236,7 +236,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorDisableHandler(c *core.Context) (a
|
|||||||
enableTwoFactor, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
|
enableTwoFactor, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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)
|
err = a.twoFactorAuthorizations.DeleteTwoFactorRecoveryCodes(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.twoFactorAuthorizations.DeleteTwoFactorSetting(c, uid)
|
err = a.twoFactorAuthorizations.DeleteTwoFactorSetting(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TwoFactorRecoveryCodeRegenerateHandler returns new 2fa recovery codes and revokes old recovery codes for current user
|
// 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
|
var regenerateReq models.TwoFactorRegenerateRecoveryCodeRequest
|
||||||
err := c.ShouldBindJSON(®enerateReq)
|
err := c.ShouldBindJSON(®enerateReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -278,7 +278,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorRecoveryCodeRegenerateHandler(c *c
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
@@ -291,7 +291,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorRecoveryCodeRegenerateHandler(c *c
|
|||||||
enableTwoFactor, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
|
enableTwoFactor, err := a.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,14 +302,14 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorRecoveryCodeRegenerateHandler(c *c
|
|||||||
recoveryCodes, err := a.twoFactorAuthorizations.GenerateTwoFactorRecoveryCodes()
|
recoveryCodes, err := a.twoFactorAuthorizations.GenerateTwoFactorRecoveryCodes()
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.twoFactorAuthorizations.CreateTwoFactorRecoveryCodes(c, uid, recoveryCodes, user.Salt)
|
err = a.twoFactorAuthorizations.CreateTwoFactorRecoveryCodes(c, uid, recoveryCodes, user.Salt)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -317,7 +317,7 @@ func (a *TwoFactorAuthorizationsApi) TwoFactorRecoveryCodeRegenerateHandler(c *c
|
|||||||
RecoveryCodes: recoveryCodes,
|
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
|
return recoveryCodesResp, nil
|
||||||
}
|
}
|
||||||
|
|||||||
+60
-60
@@ -38,7 +38,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// UserRegisterHandler saves a new user by request parameters
|
// 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 {
|
if !a.CurrentConfig().EnableUserRegister {
|
||||||
return nil, errs.ErrUserRegistrationNotAllowed
|
return nil, errs.ErrUserRegistrationNotAllowed
|
||||||
}
|
}
|
||||||
@@ -47,12 +47,12 @@ func (a *UsersApi) UserRegisterHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
err := c.ShouldBindBodyWith(&userRegisterReq, binding.JSON)
|
err := c.ShouldBindBodyWith(&userRegisterReq, binding.JSON)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if userRegisterReq.DefaultCurrency == validators.ParentAccountCurrencyPlaceholder {
|
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
|
return nil, errs.ErrUserDefaultCurrencyIsInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,11 +74,11 @@ func (a *UsersApi) UserRegisterHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
err = a.users.CreateUser(c, user)
|
err = a.users.CreateUser(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
presetCategoriesSaved := false
|
||||||
|
|
||||||
@@ -104,13 +104,13 @@ func (a *UsersApi) UserRegisterHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
|
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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 {
|
} else {
|
||||||
go func() {
|
go func() {
|
||||||
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
|
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
|
||||||
|
|
||||||
if err != nil {
|
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)
|
token, claims, err := a.tokens.CreateToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return authResp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,13 +131,13 @@ func (a *UsersApi) UserRegisterHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
c.SetTextualToken(token)
|
c.SetTextualToken(token)
|
||||||
c.SetTokenClaims(claims)
|
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
|
return authResp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserEmailVerifyHandler sets user email address verified
|
// 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
|
var userVerifyEmailReq models.UserVerifyEmailRequest
|
||||||
err := c.ShouldBindJSON(&userVerifyEmailReq)
|
err := c.ShouldBindJSON(&userVerifyEmailReq)
|
||||||
|
|
||||||
@@ -146,35 +146,35 @@ func (a *UsersApi) UserEmailVerifyHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Disabled {
|
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
|
return nil, errs.ErrUserIsDisabled
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.EmailVerified {
|
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
|
return nil, errs.ErrEmailIsVerified
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.users.SetUserEmailVerified(c, user.Username)
|
err = a.users.SetUserEmailVerified(c, user.Username)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.tokens.DeleteTokensByType(c, uid, core.USER_TOKEN_TYPE_EMAIL_VERIFY)
|
err = a.tokens.DeleteTokensByType(c, uid, core.USER_TOKEN_TYPE_EMAIL_VERIFY)
|
||||||
|
|
||||||
if err == nil {
|
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 {
|
} 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{}
|
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)
|
token, claims, err := a.tokens.CreateToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,20 +194,20 @@ func (a *UsersApi) UserEmailVerifyHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
c.SetTextualToken(token)
|
c.SetTextualToken(token)
|
||||||
c.SetTokenClaims(claims)
|
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
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserProfileHandler returns user profile of current user
|
// 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()
|
uid := c.GetCurrentUid()
|
||||||
user, err := a.users.GetUserById(c, uid)
|
user, err := a.users.GetUserById(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
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
|
// 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
|
var userUpdateReq models.UserProfileUpdateRequest
|
||||||
err := c.ShouldBindJSON(&userUpdateReq)
|
err := c.ShouldBindJSON(&userUpdateReq)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.NewIncompleteOrIncorrectSubmissionError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,7 +232,7 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
@@ -278,12 +278,12 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if _, exists := accountMap[userUpdateReq.DefaultAccountId]; !exists {
|
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
|
return nil, errs.ErrUserDefaultAccountIsInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
if accountMap[userUpdateReq.DefaultAccountId].Hidden {
|
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
|
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)
|
keyProfileUpdated, emailSetToUnverified, err := a.users.UpdateUser(c, userNew, modifyUserLanguage)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrOperationFailed)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -445,7 +445,7 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
|
|||||||
user.EmailVerified = false
|
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{
|
resp := &models.UserProfileUpdateResponse{
|
||||||
User: a.GetUserBasicInfo(user),
|
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)
|
err = a.tokens.DeleteTokensByType(c, uid, core.USER_TOKEN_TYPE_EMAIL_VERIFY)
|
||||||
|
|
||||||
if err != nil {
|
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 {
|
} else {
|
||||||
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
|
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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 {
|
} else {
|
||||||
go func() {
|
go func() {
|
||||||
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
|
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
|
||||||
|
|
||||||
if err != nil {
|
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)
|
err = a.tokens.DeleteTokensBeforeTime(c, uid, now)
|
||||||
|
|
||||||
if err == nil {
|
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 {
|
} 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)
|
token, claims, err := a.tokens.CreateToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -494,7 +494,7 @@ func (a *UsersApi) UserUpdateProfileHandler(c *core.Context) (any, *errs.Error)
|
|||||||
c.SetTextualToken(token)
|
c.SetTextualToken(token)
|
||||||
c.SetTokenClaims(claims)
|
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
|
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
|
// 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()
|
uid := c.GetCurrentUid()
|
||||||
user, err := a.users.GetUserById(c, uid)
|
user, err := a.users.GetUserById(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
@@ -518,40 +518,40 @@ func (a *UsersApi) UserUpdateAvatarHandler(c *core.Context) (any, *errs.Error) {
|
|||||||
form, err := c.MultipartForm()
|
form, err := c.MultipartForm()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrParameterInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
avatars := form.File["avatar"]
|
avatars := form.File["avatar"]
|
||||||
|
|
||||||
if len(avatars) < 1 {
|
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
|
return nil, errs.ErrNoUserAvatar
|
||||||
}
|
}
|
||||||
|
|
||||||
if avatars[0].Size < 1 {
|
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
|
return nil, errs.ErrUserAvatarIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
fileExtension := utils.GetFileNameExtension(avatars[0].Filename)
|
fileExtension := utils.GetFileNameExtension(avatars[0].Filename)
|
||||||
|
|
||||||
if utils.GetImageContentType(fileExtension) == "" {
|
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
|
return nil, errs.ErrImageTypeNotSupported
|
||||||
}
|
}
|
||||||
|
|
||||||
avatarFile, err := avatars[0].Open()
|
avatarFile, err := avatars[0].Open()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
err = a.users.UpdateUserAvatar(c, user.Uid, avatarFile, fileExtension, user.CustomAvatarType)
|
err = a.users.UpdateUserAvatar(c, user.Uid, avatarFile, fileExtension, user.CustomAvatarType)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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()
|
uid := c.GetCurrentUid()
|
||||||
user, err := a.users.GetUserById(c, uid)
|
user, err := a.users.GetUserById(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
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)
|
err = a.users.RemoveUserAvatar(c, user.Uid, user.CustomAvatarType)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
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
|
// 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 {
|
if !a.CurrentConfig().EnableUserVerifyEmail {
|
||||||
return nil, errs.ErrEmailValidationNotAllowed
|
return nil, errs.ErrEmailValidationNotAllowed
|
||||||
}
|
}
|
||||||
@@ -602,24 +602,24 @@ func (a *UsersApi) UserSendVerifyEmailByUnloginUserHandler(c *core.Context) (any
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if !a.users.IsPasswordEqualsUserPassword(userResendVerifyEmailReq.Password, user) {
|
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
|
return nil, errs.ErrUserPasswordWrong
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Disabled {
|
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
|
return nil, errs.ErrUserIsDisabled
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.EmailVerified {
|
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
|
return nil, errs.ErrEmailIsVerified
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -630,7 +630,7 @@ func (a *UsersApi) UserSendVerifyEmailByUnloginUserHandler(c *core.Context) (any
|
|||||||
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
|
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrTokenGenerating
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -638,7 +638,7 @@ func (a *UsersApi) UserSendVerifyEmailByUnloginUserHandler(c *core.Context) (any
|
|||||||
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
|
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
|
||||||
|
|
||||||
if err != nil {
|
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
|
// 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 {
|
if !a.CurrentConfig().EnableUserVerifyEmail {
|
||||||
return nil, errs.ErrEmailValidationNotAllowed
|
return nil, errs.ErrEmailValidationNotAllowed
|
||||||
}
|
}
|
||||||
@@ -656,14 +656,14 @@ func (a *UsersApi) UserSendVerifyEmailByLoginedUserHandler(c *core.Context) (any
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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
|
return nil, errs.ErrUserNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.EmailVerified {
|
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
|
return nil, errs.ErrEmailIsVerified
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -674,7 +674,7 @@ func (a *UsersApi) UserSendVerifyEmailByLoginedUserHandler(c *core.Context) (any
|
|||||||
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
|
token, _, err := a.tokens.CreateEmailVerifyToken(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrTokenGenerating
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -682,7 +682,7 @@ func (a *UsersApi) UserSendVerifyEmailByLoginedUserHandler(c *core.Context) (any
|
|||||||
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
|
err = a.users.SendVerifyEmail(user, token, c.GetClientLocale())
|
||||||
|
|
||||||
if err != nil {
|
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
|
// 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")
|
fileName := c.Param("fileName")
|
||||||
fileExtension := utils.GetFileNameExtension(fileName)
|
fileExtension := utils.GetFileNameExtension(fileName)
|
||||||
contentType := utils.GetImageContentType(fileExtension)
|
contentType := utils.GetImageContentType(fileExtension)
|
||||||
@@ -703,7 +703,7 @@ func (a *UsersApi) UserGetAvatarHandler(c *core.Context) ([]byte, string, *errs.
|
|||||||
fileBaseName := utils.GetFileNameWithoutExtension(fileName)
|
fileBaseName := utils.GetFileNameWithoutExtension(fileName)
|
||||||
|
|
||||||
if utils.Int64ToString(uid) != fileBaseName {
|
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
|
return nil, "", errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -711,7 +711,7 @@ func (a *UsersApi) UserGetAvatarHandler(c *core.Context) ([]byte, string, *errs.
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errs.IsCustomError(err) {
|
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)
|
return nil, "", errs.Or(err, errs.ErrOperationFailed)
|
||||||
|
|||||||
+140
-141
@@ -3,9 +3,8 @@ package cli
|
|||||||
import (
|
import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/urfave/cli/v2"
|
|
||||||
|
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/converters"
|
"github.com/mayswind/ezbookkeeping/pkg/converters"
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/log"
|
"github.com/mayswind/ezbookkeeping/pkg/log"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/models"
|
"github.com/mayswind/ezbookkeeping/pkg/models"
|
||||||
@@ -52,34 +51,34 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// AddNewUser adds a new user according to specified info
|
// 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 == "" {
|
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
|
return nil, errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
if email == "" {
|
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
|
return nil, errs.ErrEmailIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
if nickname == "" {
|
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
|
return nil, errs.ErrNicknameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
if password == "" {
|
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
|
return nil, errs.ErrPasswordIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
if defaultCurrency == "" {
|
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
|
return nil, errs.ErrUserDefaultCurrencyIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := validators.AllCurrencyNames[defaultCurrency]; !ok {
|
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
|
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,
|
TransactionEditScope: models.TRANSACTION_EDIT_SCOPE_ALL,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := l.users.CreateUser(nil, user)
|
err := l.users.CreateUser(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
return user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetUserByUsername returns user by user name
|
// 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 == "" {
|
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
|
return nil, errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := l.users.GetUserByUsername(nil, username)
|
user, err := l.users.GetUserByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,21 +122,21 @@ func (l *UserDataCli) GetUserByUsername(c *cli.Context, username string) (*model
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ModifyUserPassword modifies user password
|
// 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 == "" {
|
if username == "" {
|
||||||
log.BootErrorf("[user_data.ModifyUserPassword] user name is empty")
|
log.BootErrorf(c, "[user_data.ModifyUserPassword] user name is empty")
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
if password == "" {
|
if password == "" {
|
||||||
log.BootErrorf("[user_data.ModifyUserPassword] user password is empty")
|
log.BootErrorf(c, "[user_data.ModifyUserPassword] user password is empty")
|
||||||
return errs.ErrPasswordIsEmpty
|
return errs.ErrPasswordIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := l.users.GetUserByUsername(nil, username)
|
user, err := l.users.GetUserByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,55 +150,55 @@ func (l *UserDataCli) ModifyUserPassword(c *cli.Context, username string, passwo
|
|||||||
Password: password,
|
Password: password,
|
||||||
}
|
}
|
||||||
|
|
||||||
_, _, err = l.users.UpdateUser(nil, userNew, false)
|
_, _, err = l.users.UpdateUser(c, userNew, false)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
err = l.tokens.DeleteTokensBeforeTime(nil, user.Uid, now)
|
err = l.tokens.DeleteTokensBeforeTime(c, user.Uid, now)
|
||||||
|
|
||||||
if err == nil {
|
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 {
|
} 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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendPasswordResetMail sends an email with password reset link
|
// 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 == "" {
|
if username == "" {
|
||||||
log.BootErrorf("[user_data.SendPasswordResetMail] user name is empty")
|
log.BootErrorf(c, "[user_data.SendPasswordResetMail] user name is empty")
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := l.users.GetUserByUsername(nil, username)
|
user, err := l.users.GetUserByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if l.CurrentConfig().ForgetPasswordRequireVerifyEmail && !user.EmailVerified {
|
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
|
return errs.ErrEmailIsNotVerified
|
||||||
}
|
}
|
||||||
|
|
||||||
token, _, err := l.tokens.CreatePasswordResetToken(nil, user)
|
token, _, err := l.tokens.CreatePasswordResetTokenWithoutUserAgent(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = l.forgetPasswords.SendPasswordResetEmail(nil, user, token, "")
|
err = l.forgetPasswords.SendPasswordResetEmail(c, user, token, "")
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
// 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 == "" {
|
if username == "" {
|
||||||
log.BootErrorf("[user_data.EnableUser] user name is empty")
|
log.BootErrorf(c, "[user_data.EnableUser] user name is empty")
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
err := l.users.EnableUser(nil, username)
|
err := l.users.EnableUser(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
// 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 == "" {
|
if username == "" {
|
||||||
log.BootErrorf("[user_data.DisableUser] user name is empty")
|
log.BootErrorf(c, "[user_data.DisableUser] user name is empty")
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
err := l.users.DisableUser(nil, username)
|
err := l.users.DisableUser(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,39 +240,39 @@ func (l *UserDataCli) DisableUser(c *cli.Context, username string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ResendVerifyEmail resends an email with account activation link
|
// 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 {
|
if !l.CurrentConfig().EnableUserVerifyEmail {
|
||||||
return errs.ErrEmailValidationNotAllowed
|
return errs.ErrEmailValidationNotAllowed
|
||||||
}
|
}
|
||||||
|
|
||||||
if username == "" {
|
if username == "" {
|
||||||
log.BootErrorf("[user_data.ResendVerifyEmail] user name is empty")
|
log.BootErrorf(c, "[user_data.ResendVerifyEmail] user name is empty")
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := l.users.GetUserByUsername(nil, username)
|
user, err := l.users.GetUserByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.EmailVerified {
|
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
|
return errs.ErrEmailIsVerified
|
||||||
}
|
}
|
||||||
|
|
||||||
token, _, err := l.tokens.CreateEmailVerifyToken(nil, user)
|
token, _, err := l.tokens.CreateEmailVerifyTokenWithoutUserAgent(c, user)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return errs.ErrTokenGenerating
|
||||||
}
|
}
|
||||||
|
|
||||||
err = l.users.SendVerifyEmail(user, token, "")
|
err = l.users.SendVerifyEmail(user, token, "")
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,16 +280,16 @@ func (l *UserDataCli) ResendVerifyEmail(c *cli.Context, username string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetUserEmailVerified sets user email address verified
|
// 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 == "" {
|
if username == "" {
|
||||||
log.BootErrorf("[user_data.SetUserEmailVerified] user name is empty")
|
log.BootErrorf(c, "[user_data.SetUserEmailVerified] user name is empty")
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
err := l.users.SetUserEmailVerified(nil, username)
|
err := l.users.SetUserEmailVerified(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -298,16 +297,16 @@ func (l *UserDataCli) SetUserEmailVerified(c *cli.Context, username string) erro
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetUserEmailUnverified sets user email address unverified
|
// 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 == "" {
|
if username == "" {
|
||||||
log.BootErrorf("[user_data.SetUserEmailUnverified] user name is empty")
|
log.BootErrorf(c, "[user_data.SetUserEmailUnverified] user name is empty")
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
err := l.users.SetUserEmailUnverified(nil, username)
|
err := l.users.SetUserEmailUnverified(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
// 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 == "" {
|
if username == "" {
|
||||||
log.BootErrorf("[user_data.DeleteUser] user name is empty")
|
log.BootErrorf(c, "[user_data.DeleteUser] user name is empty")
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
err := l.users.DeleteUser(nil, username)
|
err := l.users.DeleteUser(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -332,23 +331,23 @@ func (l *UserDataCli) DeleteUser(c *cli.Context, username string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ListUserTokens returns all tokens of the specified user
|
// 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 == "" {
|
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
|
return nil, errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
uid, err := l.getUserIdByUsername(c, username)
|
uid, err := l.getUserIdByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
tokens, err := l.tokens.GetAllUnexpiredNormalTokensByUid(nil, uid)
|
tokens, err := l.tokens.GetAllUnexpiredNormalTokensByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
// 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 == "" {
|
if username == "" {
|
||||||
log.BootErrorf("[user_data.ClearUserTokens] user name is empty")
|
log.BootErrorf(c, "[user_data.ClearUserTokens] user name is empty")
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
uid, err := l.getUserIdByUsername(c, username)
|
uid, err := l.getUserIdByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
err = l.tokens.DeleteTokensBeforeTime(nil, uid, now)
|
err = l.tokens.DeleteTokensBeforeTime(c, uid, now)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -381,23 +380,23 @@ func (l *UserDataCli) ClearUserTokens(c *cli.Context, username string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DisableUserTwoFactorAuthorization disables 2fa for the specified user
|
// 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 == "" {
|
if username == "" {
|
||||||
log.BootErrorf("[user_data.DisableUserTwoFactorAuthorization] user name is empty")
|
log.BootErrorf(c, "[user_data.DisableUserTwoFactorAuthorization] user name is empty")
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
uid, err := l.getUserIdByUsername(c, username)
|
uid, err := l.getUserIdByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
enableTwoFactor, err := l.twoFactorAuthorizations.ExistsTwoFactorSetting(nil, uid)
|
enableTwoFactor, err := l.twoFactorAuthorizations.ExistsTwoFactorSetting(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -405,17 +404,17 @@ func (l *UserDataCli) DisableUserTwoFactorAuthorization(c *cli.Context, username
|
|||||||
return errs.ErrTwoFactorIsNotEnabled
|
return errs.ErrTwoFactorIsNotEnabled
|
||||||
}
|
}
|
||||||
|
|
||||||
err = l.twoFactorAuthorizations.DeleteTwoFactorRecoveryCodes(nil, uid)
|
err = l.twoFactorAuthorizations.DeleteTwoFactorRecoveryCodes(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = l.twoFactorAuthorizations.DeleteTwoFactorSetting(nil, uid)
|
err = l.twoFactorAuthorizations.DeleteTwoFactorSetting(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
// 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 == "" {
|
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
|
return false, errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
uid, err := l.getUserIdByUsername(c, username)
|
uid, err := l.getUserIdByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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 {
|
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
|
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 {
|
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
|
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 {
|
} else if transaction.Type == models.TRANSACTION_DB_TYPE_TRANSFER_IN {
|
||||||
balance = balance + transaction.Amount
|
balance = balance + transaction.Amount
|
||||||
} else {
|
} 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
|
return false, errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -520,12 +519,12 @@ func (l *UserDataCli) CheckTransactionAndAccount(c *cli.Context, username string
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !exists && account.Balance != 0 {
|
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
|
return false, errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
if account.Balance != actualBalance {
|
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
|
return false, errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -534,7 +533,7 @@ func (l *UserDataCli) CheckTransactionAndAccount(c *cli.Context, username string
|
|||||||
_, exists := accountMap[accountId]
|
_, exists := accountMap[accountId]
|
||||||
|
|
||||||
if !exists {
|
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
|
return false, errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -543,7 +542,7 @@ func (l *UserDataCli) CheckTransactionAndAccount(c *cli.Context, username string
|
|||||||
tagIndex := tagIndexes[i]
|
tagIndex := tagIndexes[i]
|
||||||
|
|
||||||
if tagIndex.TransactionTime < 1 {
|
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
|
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
|
// 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 == "" {
|
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
|
return false, errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
uid, err := l.getUserIdByUsername(c, username)
|
uid, err := l.getUserIdByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
tagIndexes, err := l.tags.GetAllTagIdsOfAllTransactions(nil, uid)
|
tagIndexes, err := l.tags.GetAllTagIdsOfAllTransactions(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -583,14 +582,14 @@ func (l *UserDataCli) FixTransactionTagIndexWithTransactionTime(c *cli.Context,
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(invalidTagIndexes) < 1 {
|
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
|
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 {
|
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
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -607,10 +606,10 @@ func (l *UserDataCli) FixTransactionTagIndexWithTransactionTime(c *cli.Context,
|
|||||||
tagIndex.TransactionTime = transaction.TransactionTime
|
tagIndex.TransactionTime = transaction.TransactionTime
|
||||||
}
|
}
|
||||||
|
|
||||||
err = l.tags.ModifyTagIndexTransactionTime(nil, uid, invalidTagIndexes)
|
err = l.tags.ModifyTagIndexTransactionTime(c, uid, invalidTagIndexes)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -618,30 +617,30 @@ func (l *UserDataCli) FixTransactionTagIndexWithTransactionTime(c *cli.Context,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ExportTransaction returns csv file content according user all transactions
|
// 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 == "" {
|
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
|
return nil, errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
uid, err := l.getUserIdByUsername(c, username)
|
uid, err := l.getUserIdByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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 {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
allTransactions, err := l.transactions.GetAllTransactions(nil, uid, pageCountForDataExport, true)
|
allTransactions, err := l.transactions.GetAllTransactions(c, uid, pageCountForDataExport, true)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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)
|
result, err := dataExporter.ToExportedContent(uid, allTransactions, accountMap, categoryMap, tagMap, tagIndexesMap)
|
||||||
|
|
||||||
if err != nil {
|
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 nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
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)
|
user, err := l.GetUserByUsername(c, username)
|
||||||
|
|
||||||
if err != nil {
|
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 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return user.Uid, nil
|
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 {
|
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
|
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 {
|
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
|
return nil, nil, nil, nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
accountMap = l.accounts.GetAccountMapByList(accounts)
|
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 {
|
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
|
return nil, nil, nil, nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
categoryMap = l.categories.GetCategoryMapByList(categories)
|
categoryMap = l.categories.GetCategoryMapByList(categories)
|
||||||
|
|
||||||
tags, err := l.tags.GetAllTagsByUid(nil, uid)
|
tags, err := l.tags.GetAllTagsByUid(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, nil, nil, nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
tagMap = l.tags.GetTagMapByList(tags)
|
tagMap = l.tags.GetTagMapByList(tags)
|
||||||
|
|
||||||
tagIndexes, err = l.tags.GetAllTagIdsOfAllTransactions(nil, uid)
|
tagIndexes, err = l.tags.GetAllTagIdsOfAllTransactions(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
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]
|
account, exists := accountMap[transaction.AccountId]
|
||||||
|
|
||||||
if !exists {
|
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
|
return errs.ErrAccountNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if account.ParentAccountId == models.LevelOneAccountParentId && accountHasChild[account.AccountId] {
|
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
|
return errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -736,12 +735,12 @@ func (l *UserDataCli) checkTransactionAccount(c *cli.Context, transaction *model
|
|||||||
relatedAccount, exists := accountMap[transaction.RelatedAccountId]
|
relatedAccount, exists := accountMap[transaction.RelatedAccountId]
|
||||||
|
|
||||||
if !exists {
|
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
|
return errs.ErrAccountNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if relatedAccount.ParentAccountId == models.LevelOneAccountParentId && accountHasChild[relatedAccount.AccountId] {
|
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
|
return errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -749,10 +748,10 @@ func (l *UserDataCli) checkTransactionAccount(c *cli.Context, transaction *model
|
|||||||
return nil
|
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.Type == models.TRANSACTION_DB_TYPE_MODIFY_BALANCE {
|
||||||
if transaction.CategoryId > 0 {
|
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
|
return errs.ErrBalanceModificationTransactionCannotSetCategory
|
||||||
} else {
|
} else {
|
||||||
return nil
|
return nil
|
||||||
@@ -762,19 +761,19 @@ func (l *UserDataCli) checkTransactionCategory(c *cli.Context, transaction *mode
|
|||||||
category, exists := categoryMap[transaction.CategoryId]
|
category, exists := categoryMap[transaction.CategoryId]
|
||||||
|
|
||||||
if !exists {
|
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
|
return errs.ErrTransactionCategoryNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if category.ParentCategoryId == models.LevelOneTransactionParentId {
|
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 errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
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]
|
tagIndexes, exists := allTagIndexesMap[transactionId]
|
||||||
|
|
||||||
if !exists {
|
if !exists {
|
||||||
@@ -786,7 +785,7 @@ func (l *UserDataCli) checkTransactionTag(c *cli.Context, transactionId int64, a
|
|||||||
tag, exists := tagMap[tagIndex]
|
tag, exists := tagMap[tagIndex]
|
||||||
|
|
||||||
if !exists {
|
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
|
return errs.ErrTransactionTagNotFound
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -794,7 +793,7 @@ func (l *UserDataCli) checkTransactionTag(c *cli.Context, transactionId int64, a
|
|||||||
return nil
|
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 {
|
if transaction.Type != models.TRANSACTION_DB_TYPE_TRANSFER_OUT && transaction.Type != models.TRANSACTION_DB_TYPE_TRANSFER_IN {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -802,22 +801,22 @@ func (l *UserDataCli) checkTransactionRelatedTransaction(c *cli.Context, transac
|
|||||||
relatedTransaction, exists := transactionMap[transaction.RelatedId]
|
relatedTransaction, exists := transactionMap[transaction.RelatedId]
|
||||||
|
|
||||||
if !exists {
|
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
|
return errs.ErrTransactionNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if transaction.RelatedId != relatedTransaction.TransactionId || transaction.TransactionId != relatedTransaction.RelatedId {
|
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
|
return errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
if transaction.RelatedAccountId != relatedTransaction.AccountId || transaction.AccountId != relatedTransaction.RelatedAccountId {
|
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
|
return errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
if transaction.RelatedAccountAmount != relatedTransaction.Amount || transaction.Amount != relatedTransaction.RelatedAccountAmount {
|
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
|
return errs.ErrOperationFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -825,7 +824,7 @@ func (l *UserDataCli) checkTransactionRelatedTransaction(c *cli.Context, transac
|
|||||||
relatedAccount := accountMap[transaction.RelatedAccountId]
|
relatedAccount := accountMap[transaction.RelatedAccountId]
|
||||||
|
|
||||||
if account.Currency == relatedAccount.Currency && transaction.Amount != transaction.RelatedAccountAmount {
|
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
|
return nil
|
||||||
|
|||||||
+3
-158
@@ -1,161 +1,6 @@
|
|||||||
package core
|
package core
|
||||||
|
|
||||||
import (
|
// Context is the base context of ezBookkeeping
|
||||||
"net"
|
type Context interface {
|
||||||
"strconv"
|
GetContextId() string
|
||||||
|
|
||||||
"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,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
}
|
||||||
@@ -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(),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
@@ -6,17 +6,20 @@ import (
|
|||||||
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// CliHandlerFunc represents the cli handler function
|
||||||
|
type CliHandlerFunc func(*CliContext) error
|
||||||
|
|
||||||
// MiddlewareHandlerFunc represents the middleware handler function
|
// MiddlewareHandlerFunc represents the middleware handler function
|
||||||
type MiddlewareHandlerFunc func(*Context)
|
type MiddlewareHandlerFunc func(*WebContext)
|
||||||
|
|
||||||
// ApiHandlerFunc represents the api handler function
|
// 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
|
// 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
|
// 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
|
// ProxyHandlerFunc represents the reverse proxy handler function
|
||||||
type ProxyHandlerFunc func(*Context) (*httputil.ReverseProxy, *errs.Error)
|
type ProxyHandlerFunc func(*WebContext) (*httputil.ReverseProxy, *errs.Error)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
|
|
||||||
"github.com/go-co-op/gocron/v2"
|
"github.com/go-co-op/gocron/v2"
|
||||||
|
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/log"
|
"github.com/mayswind/ezbookkeeping/pkg/log"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/settings"
|
"github.com/mayswind/ezbookkeeping/pkg/settings"
|
||||||
@@ -27,7 +28,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// InitializeCronJobSchedulerContainer initializes the cron job scheduler according to the config
|
// 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
|
var err error
|
||||||
|
|
||||||
Container.scheduler, err = gocron.NewScheduler(
|
Container.scheduler, err = gocron.NewScheduler(
|
||||||
@@ -39,7 +40,7 @@ func InitializeCronJobSchedulerContainer(config *settings.Config, startScheduler
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
Container.registerAllJobs(config)
|
Container.registerAllJobs(ctx, config)
|
||||||
|
|
||||||
if startScheduler {
|
if startScheduler {
|
||||||
Container.scheduler.Start()
|
Container.scheduler.Start()
|
||||||
@@ -75,13 +76,13 @@ func (c *CronJobSchedulerContainer) SyncRunJobNow(jobName string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CronJobSchedulerContainer) registerAllJobs(config *settings.Config) {
|
func (c *CronJobSchedulerContainer) registerAllJobs(ctx core.Context, config *settings.Config) {
|
||||||
if config.EnableRemoveExpiredTokens {
|
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(
|
gocronJob, err := c.scheduler.NewJob(
|
||||||
job.Period.ToJobDefinition(),
|
job.Period.ToJobDefinition(),
|
||||||
gocron.NewTask(job.doRun),
|
gocron.NewTask(job.doRun),
|
||||||
@@ -93,9 +94,9 @@ func (c *CronJobSchedulerContainer) registerIntervalJob(job *CronJob) {
|
|||||||
c.allJobs = append(c.allJobs, job)
|
c.allJobs = append(c.allJobs, job)
|
||||||
c.allJobsMap[job.Name] = job
|
c.allJobsMap[job.Name] = job
|
||||||
c.allGocronJobsMap[job.Name] = gocronJob
|
c.allGocronJobsMap[job.Name] = gocronJob
|
||||||
log.Infof("[cron_container.registerJob] job \"%s\" has been registered", job.Name)
|
log.Infof(ctx, "[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.Debugf(ctx, "[cron_container.registerJob] job \"%s\" gocron id is %s", job.Name, gocronJob.ID())
|
||||||
} else {
|
} 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())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"github.com/go-co-op/gocron/v2"
|
"github.com/go-co-op/gocron/v2"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/duplicatechecker"
|
"github.com/mayswind/ezbookkeeping/pkg/duplicatechecker"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/settings"
|
"github.com/mayswind/ezbookkeeping/pkg/settings"
|
||||||
)
|
)
|
||||||
@@ -33,13 +34,13 @@ func TestCronJobSchedulerContainerRegisterIntervalJob(t *testing.T) {
|
|||||||
Period: CronJobIntervalPeriod{
|
Period: CronJobIntervalPeriod{
|
||||||
Interval: 1 * time.Second,
|
Interval: 1 * time.Second,
|
||||||
},
|
},
|
||||||
Run: func() error {
|
Run: func(c *core.CronContext) error {
|
||||||
actualValue = true
|
actualValue = true
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
container.registerIntervalJob(job)
|
container.registerIntervalJob(core.NewNullContext(), job)
|
||||||
container.scheduler.Start()
|
container.scheduler.Start()
|
||||||
|
|
||||||
assert.Equal(t, 1, len(container.GetAllJobs()))
|
assert.Equal(t, 1, len(container.GetAllJobs()))
|
||||||
@@ -73,13 +74,13 @@ func TestCronJobSchedulerContainerSyncRunJobNow(t *testing.T) {
|
|||||||
Period: CronJobIntervalPeriod{
|
Period: CronJobIntervalPeriod{
|
||||||
Interval: 24 * time.Hour,
|
Interval: 24 * time.Hour,
|
||||||
},
|
},
|
||||||
Run: func() error {
|
Run: func(c *core.CronContext) error {
|
||||||
actualValue = true
|
actualValue = true
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
container.registerIntervalJob(job)
|
container.registerIntervalJob(core.NewNullContext(), job)
|
||||||
|
|
||||||
err = container.SyncRunJobNow("TestSyncRunJob")
|
err = container.SyncRunJobNow("TestSyncRunJob")
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
@@ -115,17 +116,17 @@ func TestCronJobSchedulerContainerRepeatRun(t *testing.T) {
|
|||||||
Period: CronJobFixedTimePeriod{
|
Period: CronJobFixedTimePeriod{
|
||||||
Time: runTime,
|
Time: runTime,
|
||||||
},
|
},
|
||||||
Run: func() error {
|
Run: func(c *core.CronContext) error {
|
||||||
runCount.Add(1)
|
runCount.Add(1)
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
container.registerIntervalJob(job)
|
container.registerIntervalJob(core.NewNullContext(), job)
|
||||||
container.registerIntervalJob(job)
|
container.registerIntervalJob(core.NewNullContext(), job)
|
||||||
container.registerIntervalJob(job)
|
container.registerIntervalJob(core.NewNullContext(), job)
|
||||||
container.registerIntervalJob(job)
|
container.registerIntervalJob(core.NewNullContext(), job)
|
||||||
container.registerIntervalJob(job)
|
container.registerIntervalJob(core.NewNullContext(), job)
|
||||||
container.scheduler.Start()
|
container.scheduler.Start()
|
||||||
|
|
||||||
time.Sleep(10 * time.Second)
|
time.Sleep(10 * time.Second)
|
||||||
|
|||||||
+10
-8
@@ -4,6 +4,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/duplicatechecker"
|
"github.com/mayswind/ezbookkeeping/pkg/duplicatechecker"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/log"
|
"github.com/mayswind/ezbookkeeping/pkg/log"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/utils"
|
"github.com/mayswind/ezbookkeeping/pkg/utils"
|
||||||
@@ -14,38 +15,39 @@ type CronJob struct {
|
|||||||
Name string
|
Name string
|
||||||
Description string
|
Description string
|
||||||
Period CronJobPeriod
|
Period CronJobPeriod
|
||||||
Run func() error
|
Run func(*core.CronContext) error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CronJob) doRun() {
|
func (j *CronJob) doRun() {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
c := core.NewCronJobContext(j.Name)
|
||||||
|
|
||||||
if duplicatechecker.Container.Current != nil {
|
if duplicatechecker.Container.Current != nil {
|
||||||
localAddr, err := utils.GetLocalIPAddressesString()
|
localAddr, err := utils.GetLocalIPAddressesString()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
currentInfo := fmt.Sprintf("ip: %s, startTime: %d", localAddr, time.Now().Unix())
|
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 {
|
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
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err := c.Run()
|
err := j.Run(c)
|
||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
cost := now.Sub(start).Nanoseconds() / 1e6
|
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/go-co-op/gocron/v2"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCronJobNextRunTimeWithIntervalPeriod(t *testing.T) {
|
func TestCronJobNextRunTimeWithIntervalPeriod(t *testing.T) {
|
||||||
@@ -20,7 +22,7 @@ func TestCronJobNextRunTimeWithIntervalPeriod(t *testing.T) {
|
|||||||
Period: CronJobIntervalPeriod{
|
Period: CronJobIntervalPeriod{
|
||||||
Interval: 2*time.Hour + 34*time.Minute + 56*time.Second,
|
Interval: 2*time.Hour + 34*time.Minute + 56*time.Second,
|
||||||
},
|
},
|
||||||
Run: func() error {
|
Run: func(c *core.CronContext) error {
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -64,7 +66,7 @@ func TestCronJobNextRunTimeWithFixedHourPeriod(t *testing.T) {
|
|||||||
Period: CronJobFixedHourPeriod{
|
Period: CronJobFixedHourPeriod{
|
||||||
Hour: 0,
|
Hour: 0,
|
||||||
},
|
},
|
||||||
Run: func() error {
|
Run: func(c *core.CronContext) error {
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -109,7 +111,7 @@ func TestCronJobNextRunTimeWithFixedTimePeriod(t *testing.T) {
|
|||||||
Period: CronJobFixedTimePeriod{
|
Period: CronJobFixedTimePeriod{
|
||||||
Time: expectedTime,
|
Time: expectedTime,
|
||||||
},
|
},
|
||||||
Run: func() error {
|
Run: func(c *core.CronContext) error {
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package cron
|
package cron
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/services"
|
"github.com/mayswind/ezbookkeeping/pkg/services"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -11,7 +12,7 @@ var RemoveExpiredTokensJob = &CronJob{
|
|||||||
Period: CronJobFixedHourPeriod{
|
Period: CronJobFixedHourPeriod{
|
||||||
Hour: 0,
|
Hour: 0,
|
||||||
},
|
},
|
||||||
Run: func() error {
|
Run: func(c *core.CronContext) error {
|
||||||
return services.Tokens.DeleteAllExpiredTokens(nil)
|
return services.Tokens.DeleteAllExpiredTokens(c)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package cron
|
|||||||
import (
|
import (
|
||||||
"github.com/go-co-op/gocron/v2"
|
"github.com/go-co-op/gocron/v2"
|
||||||
|
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/log"
|
"github.com/mayswind/ezbookkeeping/pkg/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -12,22 +13,22 @@ type GocronLoggerAdapter struct {
|
|||||||
|
|
||||||
// Debug logs debug log
|
// Debug logs debug log
|
||||||
func (logger GocronLoggerAdapter) Debug(msg string, args ...any) {
|
func (logger GocronLoggerAdapter) Debug(msg string, args ...any) {
|
||||||
log.Debugf(msg, args...)
|
log.Debugf(core.NewNullContext(), msg, args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Info logs info log
|
// Info logs info log
|
||||||
func (logger GocronLoggerAdapter) Info(msg string, args ...any) {
|
func (logger GocronLoggerAdapter) Info(msg string, args ...any) {
|
||||||
log.Infof(msg, args...)
|
log.Infof(core.NewNullContext(), msg, args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Warn logs warn log
|
// Warn logs warn log
|
||||||
func (logger GocronLoggerAdapter) Warn(msg string, args ...any) {
|
func (logger GocronLoggerAdapter) Warn(msg string, args ...any) {
|
||||||
log.Warnf(msg, args...)
|
log.Warnf(core.NewNullContext(), msg, args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error logs error log
|
// Error logs error log
|
||||||
func (logger GocronLoggerAdapter) Error(msg string, args ...any) {
|
func (logger GocronLoggerAdapter) Error(msg string, args ...any) {
|
||||||
log.Errorf(msg, args...)
|
log.Errorf(core.NewNullContext(), msg, args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewGocronLoggerAdapter returns a new GocronLoggerAdapter instance
|
// NewGocronLoggerAdapter returns a new GocronLoggerAdapter instance
|
||||||
|
|||||||
@@ -12,12 +12,12 @@ type Database struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewSession starts a new session with the specified context
|
// 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))
|
return db.engineGroup.Context(NewXOrmContextAdapter(c))
|
||||||
}
|
}
|
||||||
|
|
||||||
// DoTransaction runs a new database transaction
|
// 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()
|
sess := db.engineGroup.NewSession()
|
||||||
|
|
||||||
if c != nil {
|
if c != nil {
|
||||||
|
|||||||
@@ -28,12 +28,12 @@ func (s *DataStore) Choose(key int64) *Database {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Query returns a new database session in a specific database by sharding key
|
// 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)
|
return s.Choose(key).NewSession(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
// DoTransaction runs a new database transaction in a specific database by sharding key
|
// 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)
|
return s.Choose(key).DoTransaction(c, fn)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,10 +39,10 @@ func (c *XOrmContextAdapter) Value(key any) any {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewXOrmContextAdapter(c *core.Context) *XOrmContextAdapter {
|
func NewXOrmContextAdapter(c core.Context) *XOrmContextAdapter {
|
||||||
if c != nil {
|
if c != nil {
|
||||||
return &XOrmContextAdapter{
|
return &XOrmContextAdapter{
|
||||||
requestId: c.GetRequestId(),
|
requestId: c.GetContextId(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -36,9 +36,9 @@ type BankOfCanadaExchangeRateData struct {
|
|||||||
type BankOfCanadaObservationData map[string]any
|
type BankOfCanadaObservationData map[string]any
|
||||||
|
|
||||||
// ToLatestExchangeRateResponse returns a view-object according to original data from bank of Canada
|
// 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 {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,12 +82,12 @@ func (e *BankOfCanadaExchangeRateData) ToLatestExchangeRateResponse(c *core.Cont
|
|||||||
rate, err := utils.StringToFloat64(exchangeRate)
|
rate, err := utils.StringToFloat64(exchangeRate)
|
||||||
|
|
||||||
if err != nil {
|
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
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if rate <= 0 {
|
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
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,7 +106,7 @@ func (e *BankOfCanadaExchangeRateData) ToLatestExchangeRateResponse(c *core.Cont
|
|||||||
timezone, err := time.LoadLocation(bankOfCanadaDataUpdateDateTimezone)
|
timezone, err := time.LoadLocation(bankOfCanadaDataUpdateDateTimezone)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,7 +114,7 @@ func (e *BankOfCanadaExchangeRateData) ToLatestExchangeRateResponse(c *core.Cont
|
|||||||
updateTime, err := time.ParseInLocation(bankOfCanadaDataUpdateDateFormat, updateDateTime, timezone)
|
updateTime, err := time.ParseInLocation(bankOfCanadaDataUpdateDateFormat, updateDateTime, timezone)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
// 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{}
|
bankOfCanadaData := &BankOfCanadaExchangeRateData{}
|
||||||
err := json.Unmarshal(content, bankOfCanadaData)
|
err := json.Unmarshal(content, bankOfCanadaData)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
latestExchangeRateResponse := bankOfCanadaData.ToLatestExchangeRateResponse(c)
|
latestExchangeRateResponse := bankOfCanadaData.ToLatestExchangeRateResponse(c)
|
||||||
|
|
||||||
if latestExchangeRateResponse == nil {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package exchangerates
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/core"
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
@@ -32,9 +31,7 @@ const bankOfCanadaMinimumRequiredContent = "{\n" +
|
|||||||
|
|
||||||
func TestBankOfCanadaDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
|
func TestBankOfCanadaDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
|
||||||
dataSource := &BankOfCanadaDataSource{}
|
dataSource := &BankOfCanadaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(bankOfCanadaMinimumRequiredContent))
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(bankOfCanadaMinimumRequiredContent))
|
||||||
assert.Equal(t, nil, err)
|
assert.Equal(t, nil, err)
|
||||||
@@ -43,9 +40,7 @@ func TestBankOfCanadaDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
|
|||||||
|
|
||||||
func TestBankOfCanadaDataSource_StandardDataExtractExchangeRates(t *testing.T) {
|
func TestBankOfCanadaDataSource_StandardDataExtractExchangeRates(t *testing.T) {
|
||||||
dataSource := &BankOfCanadaDataSource{}
|
dataSource := &BankOfCanadaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(bankOfCanadaMinimumRequiredContent))
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(bankOfCanadaMinimumRequiredContent))
|
||||||
assert.Equal(t, nil, err)
|
assert.Equal(t, nil, err)
|
||||||
@@ -65,9 +60,7 @@ func TestBankOfCanadaDataSource_StandardDataExtractExchangeRates(t *testing.T) {
|
|||||||
|
|
||||||
func TestBankOfCanadaDataSource_BlankContent(t *testing.T) {
|
func TestBankOfCanadaDataSource_BlankContent(t *testing.T) {
|
||||||
dataSource := &BankOfCanadaDataSource{}
|
dataSource := &BankOfCanadaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte(""))
|
_, err := dataSource.Parse(context, []byte(""))
|
||||||
assert.NotEqual(t, nil, err)
|
assert.NotEqual(t, nil, err)
|
||||||
@@ -75,9 +68,7 @@ func TestBankOfCanadaDataSource_BlankContent(t *testing.T) {
|
|||||||
|
|
||||||
func TestBankOfCanadaDataSource_EmptyJsonObject(t *testing.T) {
|
func TestBankOfCanadaDataSource_EmptyJsonObject(t *testing.T) {
|
||||||
dataSource := &BankOfCanadaDataSource{}
|
dataSource := &BankOfCanadaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("{}"))
|
_, err := dataSource.Parse(context, []byte("{}"))
|
||||||
assert.NotEqual(t, nil, err)
|
assert.NotEqual(t, nil, err)
|
||||||
@@ -85,9 +76,7 @@ func TestBankOfCanadaDataSource_EmptyJsonObject(t *testing.T) {
|
|||||||
|
|
||||||
func TestBankOfCanadaDataSource_EmptyObservationsContent(t *testing.T) {
|
func TestBankOfCanadaDataSource_EmptyObservationsContent(t *testing.T) {
|
||||||
dataSource := &BankOfCanadaDataSource{}
|
dataSource := &BankOfCanadaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("{"+
|
_, err := dataSource.Parse(context, []byte("{"+
|
||||||
" \"observations\": []"+
|
" \"observations\": []"+
|
||||||
@@ -97,9 +86,7 @@ func TestBankOfCanadaDataSource_EmptyObservationsContent(t *testing.T) {
|
|||||||
|
|
||||||
func TestBankOfCanadaDataSource_InvalidObservationFormat(t *testing.T) {
|
func TestBankOfCanadaDataSource_InvalidObservationFormat(t *testing.T) {
|
||||||
dataSource := &BankOfCanadaDataSource{}
|
dataSource := &BankOfCanadaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
|
||||||
" \"observations\": [\n"+
|
" \"observations\": [\n"+
|
||||||
@@ -117,9 +104,7 @@ func TestBankOfCanadaDataSource_InvalidObservationFormat(t *testing.T) {
|
|||||||
|
|
||||||
func TestBankOfCanadaDataSource_InvalidObservationFormat2(t *testing.T) {
|
func TestBankOfCanadaDataSource_InvalidObservationFormat2(t *testing.T) {
|
||||||
dataSource := &BankOfCanadaDataSource{}
|
dataSource := &BankOfCanadaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
|
||||||
" \"observations\": [\n"+
|
" \"observations\": [\n"+
|
||||||
@@ -137,9 +122,7 @@ func TestBankOfCanadaDataSource_InvalidObservationFormat2(t *testing.T) {
|
|||||||
|
|
||||||
func TestBankOfCanadaDataSource_InvalidCurrency(t *testing.T) {
|
func TestBankOfCanadaDataSource_InvalidCurrency(t *testing.T) {
|
||||||
dataSource := &BankOfCanadaDataSource{}
|
dataSource := &BankOfCanadaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
|
||||||
" \"observations\": [\n"+
|
" \"observations\": [\n"+
|
||||||
@@ -157,9 +140,7 @@ func TestBankOfCanadaDataSource_InvalidCurrency(t *testing.T) {
|
|||||||
|
|
||||||
func TestBankOfCanadaDataSource_EmptyRate(t *testing.T) {
|
func TestBankOfCanadaDataSource_EmptyRate(t *testing.T) {
|
||||||
dataSource := &BankOfCanadaDataSource{}
|
dataSource := &BankOfCanadaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
|
||||||
" \"observations\": [\n"+
|
" \"observations\": [\n"+
|
||||||
@@ -177,9 +158,7 @@ func TestBankOfCanadaDataSource_EmptyRate(t *testing.T) {
|
|||||||
|
|
||||||
func TestBankOfCanadaDataSource_InvalidRate(t *testing.T) {
|
func TestBankOfCanadaDataSource_InvalidRate(t *testing.T) {
|
||||||
dataSource := &BankOfCanadaDataSource{}
|
dataSource := &BankOfCanadaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("{"+
|
||||||
" \"observations\": [\n"+
|
" \"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
|
// 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")
|
lines := strings.Split(string(content), "\n")
|
||||||
|
|
||||||
if len(lines) < 3 {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
headerLineItems := strings.Split(lines[0], "#")
|
headerLineItems := strings.Split(lines[0], "#")
|
||||||
|
|
||||||
if len(headerLineItems) != 2 {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,21 +60,21 @@ func (e *CzechNationalBankDataSource) Parse(c *core.Context, content []byte) (*m
|
|||||||
currencyCodeColumnIndex, exists := titleItemMap["Code"]
|
currencyCodeColumnIndex, exists := titleItemMap["Code"]
|
||||||
|
|
||||||
if !exists {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
amountColumnIndex, exists := titleItemMap["Amount"]
|
amountColumnIndex, exists := titleItemMap["Amount"]
|
||||||
|
|
||||||
if !exists {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
rateColumnIndex, exists := titleItemMap["Rate"]
|
rateColumnIndex, exists := titleItemMap["Rate"]
|
||||||
|
|
||||||
if !exists {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,7 +92,7 @@ func (e *CzechNationalBankDataSource) Parse(c *core.Context, content []byte) (*m
|
|||||||
timezone, err := time.LoadLocation(czechNationalBankDataUpdateDateTimezone)
|
timezone, err := time.LoadLocation(czechNationalBankDataUpdateDateTimezone)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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)
|
updateTime, err := time.ParseInLocation(czechNationalBankDataUpdateDateFormat, updateDateTime, timezone)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,7 +115,7 @@ func (e *CzechNationalBankDataSource) Parse(c *core.Context, content []byte) (*m
|
|||||||
return latestExchangeRateResp, nil
|
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 {
|
if len(line) < 1 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -123,7 +123,7 @@ func (e *CzechNationalBankDataSource) parseExchangeRate(c *core.Context, line st
|
|||||||
items := strings.Split(line, "|")
|
items := strings.Split(line, "|")
|
||||||
|
|
||||||
if currencyCodeColumnIndex >= len(items) || amountColumnIndex >= len(items) || rateColumnIndex >= len(items) {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,19 +136,19 @@ func (e *CzechNationalBankDataSource) parseExchangeRate(c *core.Context, line st
|
|||||||
amount, err := utils.StringToInt64(items[amountColumnIndex])
|
amount, err := utils.StringToInt64(items[amountColumnIndex])
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
rate, err := utils.StringToFloat64(items[rateColumnIndex])
|
rate, err := utils.StringToFloat64(items[rateColumnIndex])
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if rate <= 0 {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package exchangerates
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/core"
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
@@ -17,9 +16,7 @@ const czechNationalBankMinimumRequiredContent = "01 Apr 2021 #64\n" +
|
|||||||
|
|
||||||
func TestCzechNationalBankDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
|
func TestCzechNationalBankDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
|
||||||
dataSource := &CzechNationalBankDataSource{}
|
dataSource := &CzechNationalBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(czechNationalBankMinimumRequiredContent))
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(czechNationalBankMinimumRequiredContent))
|
||||||
assert.Equal(t, nil, err)
|
assert.Equal(t, nil, err)
|
||||||
@@ -28,9 +25,7 @@ func TestCzechNationalBankDataSource_StandardDataExtractBaseCurrency(t *testing.
|
|||||||
|
|
||||||
func TestCzechNationalBankDataSource_StandardDataExtractExchangeRates(t *testing.T) {
|
func TestCzechNationalBankDataSource_StandardDataExtractExchangeRates(t *testing.T) {
|
||||||
dataSource := &CzechNationalBankDataSource{}
|
dataSource := &CzechNationalBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(czechNationalBankMinimumRequiredContent))
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(czechNationalBankMinimumRequiredContent))
|
||||||
assert.Equal(t, nil, err)
|
assert.Equal(t, nil, err)
|
||||||
@@ -46,9 +41,7 @@ func TestCzechNationalBankDataSource_StandardDataExtractExchangeRates(t *testing
|
|||||||
|
|
||||||
func TestCzechNationalBankDataSource_BlankContent(t *testing.T) {
|
func TestCzechNationalBankDataSource_BlankContent(t *testing.T) {
|
||||||
dataSource := &CzechNationalBankDataSource{}
|
dataSource := &CzechNationalBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte(""))
|
_, err := dataSource.Parse(context, []byte(""))
|
||||||
assert.NotEqual(t, nil, err)
|
assert.NotEqual(t, nil, err)
|
||||||
@@ -56,9 +49,7 @@ func TestCzechNationalBankDataSource_BlankContent(t *testing.T) {
|
|||||||
|
|
||||||
func TestCzechNationalBankDataSource_OnlyHeader(t *testing.T) {
|
func TestCzechNationalBankDataSource_OnlyHeader(t *testing.T) {
|
||||||
dataSource := &CzechNationalBankDataSource{}
|
dataSource := &CzechNationalBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64"))
|
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64"))
|
||||||
assert.NotEqual(t, nil, err)
|
assert.NotEqual(t, nil, err)
|
||||||
@@ -66,9 +57,7 @@ func TestCzechNationalBankDataSource_OnlyHeader(t *testing.T) {
|
|||||||
|
|
||||||
func TestCzechNationalBankDataSource_OnlyHeaderAndTitle(t *testing.T) {
|
func TestCzechNationalBankDataSource_OnlyHeaderAndTitle(t *testing.T) {
|
||||||
dataSource := &CzechNationalBankDataSource{}
|
dataSource := &CzechNationalBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
||||||
"Country|Currency|Amount|Code|Rate"))
|
"Country|Currency|Amount|Code|Rate"))
|
||||||
@@ -77,9 +66,7 @@ func TestCzechNationalBankDataSource_OnlyHeaderAndTitle(t *testing.T) {
|
|||||||
|
|
||||||
func TestCzechNationalBankDataSource_TitleMissingCode(t *testing.T) {
|
func TestCzechNationalBankDataSource_TitleMissingCode(t *testing.T) {
|
||||||
dataSource := &CzechNationalBankDataSource{}
|
dataSource := &CzechNationalBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
||||||
"Country|Currency|Amount|Rate\n"+
|
"Country|Currency|Amount|Rate\n"+
|
||||||
@@ -90,9 +77,7 @@ func TestCzechNationalBankDataSource_TitleMissingCode(t *testing.T) {
|
|||||||
|
|
||||||
func TestCzechNationalBankDataSource_TitleMissingRate(t *testing.T) {
|
func TestCzechNationalBankDataSource_TitleMissingRate(t *testing.T) {
|
||||||
dataSource := &CzechNationalBankDataSource{}
|
dataSource := &CzechNationalBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
_, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
||||||
"Country|Currency|Amount|Code\n"+
|
"Country|Currency|Amount|Code\n"+
|
||||||
@@ -103,9 +88,7 @@ func TestCzechNationalBankDataSource_TitleMissingRate(t *testing.T) {
|
|||||||
|
|
||||||
func TestCzechNationalBankDataSource_InvalidCurrency(t *testing.T) {
|
func TestCzechNationalBankDataSource_InvalidCurrency(t *testing.T) {
|
||||||
dataSource := &CzechNationalBankDataSource{}
|
dataSource := &CzechNationalBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
||||||
"Country|Currency|Amount|Code|Rate\n"+
|
"Country|Currency|Amount|Code|Rate\n"+
|
||||||
@@ -116,9 +99,7 @@ func TestCzechNationalBankDataSource_InvalidCurrency(t *testing.T) {
|
|||||||
|
|
||||||
func TestCzechNationalBankDataSource_EmptyRate(t *testing.T) {
|
func TestCzechNationalBankDataSource_EmptyRate(t *testing.T) {
|
||||||
dataSource := &CzechNationalBankDataSource{}
|
dataSource := &CzechNationalBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
||||||
"Country|Currency|Amount|Code|Rate\n"+
|
"Country|Currency|Amount|Code|Rate\n"+
|
||||||
@@ -129,9 +110,7 @@ func TestCzechNationalBankDataSource_EmptyRate(t *testing.T) {
|
|||||||
|
|
||||||
func TestCzechNationalBankDataSource_InvalidRate(t *testing.T) {
|
func TestCzechNationalBankDataSource_InvalidRate(t *testing.T) {
|
||||||
dataSource := &CzechNationalBankDataSource{}
|
dataSource := &CzechNationalBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("01 Apr 2021 #64\n"+
|
||||||
"Country|Currency|Amount|Code|Rate\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
|
// 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 {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
latestEuroCentralBankExchangeRate := e.AllExchangeRates[0]
|
latestEuroCentralBankExchangeRate := e.AllExchangeRates[0]
|
||||||
|
|
||||||
if len(latestEuroCentralBankExchangeRate.ExchangeRates) < 1 {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ func (e *EuroCentralBankExchangeRateData) ToLatestExchangeRateResponse(c *core.C
|
|||||||
timezone, err := time.LoadLocation(euroCentralBankDataUpdateDateTimezone)
|
timezone, err := time.LoadLocation(euroCentralBankDataUpdateDateTimezone)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,7 +84,7 @@ func (e *EuroCentralBankExchangeRateData) ToLatestExchangeRateResponse(c *core.C
|
|||||||
updateTime, err := time.ParseInLocation(euroCentralBankDataUpdateDateFormat, updateDateTime, timezone)
|
updateTime, err := time.ParseInLocation(euroCentralBankDataUpdateDateFormat, updateDateTime, timezone)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
// 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{}
|
euroCentralBankData := &EuroCentralBankExchangeRateData{}
|
||||||
err := xml.Unmarshal(content, euroCentralBankData)
|
err := xml.Unmarshal(content, euroCentralBankData)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
latestExchangeRateResponse := euroCentralBankData.ToLatestExchangeRateResponse(c)
|
latestExchangeRateResponse := euroCentralBankData.ToLatestExchangeRateResponse(c)
|
||||||
|
|
||||||
if latestExchangeRateResponse == nil {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package exchangerates
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/core"
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
@@ -22,9 +21,7 @@ const euroCentralBankMinimumRequiredContent = "<?xml version=\"1.0\" encoding=\"
|
|||||||
|
|
||||||
func TestEuroCentralBankDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
|
func TestEuroCentralBankDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
|
||||||
dataSource := &EuroCentralBankDataSource{}
|
dataSource := &EuroCentralBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(euroCentralBankMinimumRequiredContent))
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(euroCentralBankMinimumRequiredContent))
|
||||||
assert.Equal(t, nil, err)
|
assert.Equal(t, nil, err)
|
||||||
@@ -33,9 +30,7 @@ func TestEuroCentralBankDataSource_StandardDataExtractBaseCurrency(t *testing.T)
|
|||||||
|
|
||||||
func TestEuroCentralBankDataSource_StandardDataExtractExchangeRates(t *testing.T) {
|
func TestEuroCentralBankDataSource_StandardDataExtractExchangeRates(t *testing.T) {
|
||||||
dataSource := &EuroCentralBankDataSource{}
|
dataSource := &EuroCentralBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(euroCentralBankMinimumRequiredContent))
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(euroCentralBankMinimumRequiredContent))
|
||||||
assert.Equal(t, nil, err)
|
assert.Equal(t, nil, err)
|
||||||
@@ -51,9 +46,7 @@ func TestEuroCentralBankDataSource_StandardDataExtractExchangeRates(t *testing.T
|
|||||||
|
|
||||||
func TestEuroCentralBankDataSource_BlankContent(t *testing.T) {
|
func TestEuroCentralBankDataSource_BlankContent(t *testing.T) {
|
||||||
dataSource := &EuroCentralBankDataSource{}
|
dataSource := &EuroCentralBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte(""))
|
_, err := dataSource.Parse(context, []byte(""))
|
||||||
assert.NotEqual(t, nil, err)
|
assert.NotEqual(t, nil, err)
|
||||||
@@ -61,9 +54,7 @@ func TestEuroCentralBankDataSource_BlankContent(t *testing.T) {
|
|||||||
|
|
||||||
func TestEuroCentralBankDataSource_OnlyXMLHeader(t *testing.T) {
|
func TestEuroCentralBankDataSource_OnlyXMLHeader(t *testing.T) {
|
||||||
dataSource := &EuroCentralBankDataSource{}
|
dataSource := &EuroCentralBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"))
|
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"))
|
||||||
assert.NotEqual(t, nil, err)
|
assert.NotEqual(t, nil, err)
|
||||||
@@ -71,9 +62,7 @@ func TestEuroCentralBankDataSource_OnlyXMLHeader(t *testing.T) {
|
|||||||
|
|
||||||
func TestEuroCentralBankDataSource_EmptyEnvelopeContent(t *testing.T) {
|
func TestEuroCentralBankDataSource_EmptyEnvelopeContent(t *testing.T) {
|
||||||
dataSource := &EuroCentralBankDataSource{}
|
dataSource := &EuroCentralBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
|
_, 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\">"+
|
"<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) {
|
func TestEuroCentralBankDataSource_EmptyCubeContent(t *testing.T) {
|
||||||
dataSource := &EuroCentralBankDataSource{}
|
dataSource := &EuroCentralBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
|
_, 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\">"+
|
"<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) {
|
func TestEuroCentralBankDataSource_InvalidCurrency(t *testing.T) {
|
||||||
dataSource := &EuroCentralBankDataSource{}
|
dataSource := &EuroCentralBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
|
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\">"+
|
"<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) {
|
func TestEuroCentralBankDataSource_EmptyRate(t *testing.T) {
|
||||||
dataSource := &EuroCentralBankDataSource{}
|
dataSource := &EuroCentralBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
|
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\">"+
|
"<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) {
|
func TestEuroCentralBankDataSource_InvalidRate(t *testing.T) {
|
||||||
dataSource := &EuroCentralBankDataSource{}
|
dataSource := &EuroCentralBankDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
|
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\">"+
|
"<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
|
GetRequestUrls() []string
|
||||||
|
|
||||||
// Parse returns the common response entity according to the data source raw response
|
// 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
|
// 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 {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@ func (e *NationalBankOfPolandExchangeRateData) ToLatestExchangeRateResponse(c *c
|
|||||||
timezone, err := time.LoadLocation(nationalBankOfPolandDataUpdateDateTimezone)
|
timezone, err := time.LoadLocation(nationalBankOfPolandDataUpdateDateTimezone)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,7 +77,7 @@ func (e *NationalBankOfPolandExchangeRateData) ToLatestExchangeRateResponse(c *c
|
|||||||
updateTime, err := time.ParseInLocation(nationalBankOfPolandDataUpdateDateFormat, updateDateTime, timezone)
|
updateTime, err := time.ParseInLocation(nationalBankOfPolandDataUpdateDateFormat, updateDateTime, timezone)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
// 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)
|
rate, err := utils.StringToFloat64(e.Rate)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if rate <= 0 {
|
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
|
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
|
// 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{}
|
nationalBankOfPolandData := &NationalBankOfPolandExchangeRateData{}
|
||||||
|
|
||||||
xmlDecoder := xml.NewDecoder(bytes.NewReader(content))
|
xmlDecoder := xml.NewDecoder(bytes.NewReader(content))
|
||||||
@@ -132,14 +132,14 @@ func (e *NationalBankOfPolandDataSource) Parse(c *core.Context, content []byte)
|
|||||||
err := xmlDecoder.Decode(&nationalBankOfPolandData)
|
err := xmlDecoder.Decode(&nationalBankOfPolandData)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
latestExchangeRateResponse := nationalBankOfPolandData.ToLatestExchangeRateResponse(c)
|
latestExchangeRateResponse := nationalBankOfPolandData.ToLatestExchangeRateResponse(c)
|
||||||
|
|
||||||
if latestExchangeRateResponse == nil {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package exchangerates
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/core"
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
@@ -29,9 +28,7 @@ const nationalBankOfPolandMinimumRequiredContent = "<?xml version=\"1.0\" encodi
|
|||||||
|
|
||||||
func TestNationalBankOfPolandDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
|
func TestNationalBankOfPolandDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
|
||||||
dataSource := &NationalBankOfPolandDataSource{}
|
dataSource := &NationalBankOfPolandDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(nationalBankOfPolandMinimumRequiredContent))
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(nationalBankOfPolandMinimumRequiredContent))
|
||||||
assert.Equal(t, nil, err)
|
assert.Equal(t, nil, err)
|
||||||
@@ -40,9 +37,7 @@ func TestNationalBankOfPolandDataSource_StandardDataExtractBaseCurrency(t *testi
|
|||||||
|
|
||||||
func TestNationalBankOfPolandDataSource_StandardDataExtractExchangeRates(t *testing.T) {
|
func TestNationalBankOfPolandDataSource_StandardDataExtractExchangeRates(t *testing.T) {
|
||||||
dataSource := &NationalBankOfPolandDataSource{}
|
dataSource := &NationalBankOfPolandDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(nationalBankOfPolandMinimumRequiredContent))
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(nationalBankOfPolandMinimumRequiredContent))
|
||||||
assert.Equal(t, nil, err)
|
assert.Equal(t, nil, err)
|
||||||
@@ -58,9 +53,7 @@ func TestNationalBankOfPolandDataSource_StandardDataExtractExchangeRates(t *test
|
|||||||
|
|
||||||
func TestNationalBankOfPolandDataSource_BlankContent(t *testing.T) {
|
func TestNationalBankOfPolandDataSource_BlankContent(t *testing.T) {
|
||||||
dataSource := &NationalBankOfPolandDataSource{}
|
dataSource := &NationalBankOfPolandDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte(""))
|
_, err := dataSource.Parse(context, []byte(""))
|
||||||
assert.NotEqual(t, nil, err)
|
assert.NotEqual(t, nil, err)
|
||||||
@@ -68,9 +61,7 @@ func TestNationalBankOfPolandDataSource_BlankContent(t *testing.T) {
|
|||||||
|
|
||||||
func TestNationalBankOfPolandDataSource_OnlyXMLHeader(t *testing.T) {
|
func TestNationalBankOfPolandDataSource_OnlyXMLHeader(t *testing.T) {
|
||||||
dataSource := &NationalBankOfPolandDataSource{}
|
dataSource := &NationalBankOfPolandDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>"))
|
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>"))
|
||||||
assert.NotEqual(t, nil, err)
|
assert.NotEqual(t, nil, err)
|
||||||
@@ -78,9 +69,7 @@ func TestNationalBankOfPolandDataSource_OnlyXMLHeader(t *testing.T) {
|
|||||||
|
|
||||||
func TestNationalBankOfPolandDataSource_EmptyArrayOfExchangeRatesTable(t *testing.T) {
|
func TestNationalBankOfPolandDataSource_EmptyArrayOfExchangeRatesTable(t *testing.T) {
|
||||||
dataSource := &NationalBankOfPolandDataSource{}
|
dataSource := &NationalBankOfPolandDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
|
_, 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"+
|
"<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) {
|
func TestNationalBankOfPolandDataSource_EmptyExchangeRatesTable(t *testing.T) {
|
||||||
dataSource := &NationalBankOfPolandDataSource{}
|
dataSource := &NationalBankOfPolandDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
|
_, 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"+
|
"<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) {
|
func TestNationalBankOfPolandDataSource_EmptyExchangeRatesContent(t *testing.T) {
|
||||||
dataSource := &NationalBankOfPolandDataSource{}
|
dataSource := &NationalBankOfPolandDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
|
_, 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"+
|
"<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) {
|
func TestNationalBankOfPolandDataSource_InvalidCurrency(t *testing.T) {
|
||||||
dataSource := &NationalBankOfPolandDataSource{}
|
dataSource := &NationalBankOfPolandDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
|
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"+
|
"<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) {
|
func TestNationalBankOfPolandDataSource_EmptyRate(t *testing.T) {
|
||||||
dataSource := &NationalBankOfPolandDataSource{}
|
dataSource := &NationalBankOfPolandDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
|
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"+
|
"<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) {
|
func TestNationalBankOfPolandDataSource_InvalidRate(t *testing.T) {
|
||||||
dataSource := &NationalBankOfPolandDataSource{}
|
dataSource := &NationalBankOfPolandDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
|
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"+
|
"<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
|
// 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 {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(e.Items) < 1 {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +99,7 @@ func (e *ReserveBankOfAustraliaData) ToLatestExchangeRateResponse(c *core.Contex
|
|||||||
updateTime, err := time.Parse(reserveBankOfAustraliaDataUpdateDateFormat, updateDateTime)
|
updateTime, err := time.Parse(reserveBankOfAustraliaDataUpdateDateFormat, updateDateTime)
|
||||||
|
|
||||||
if err != nil {
|
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
|
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
|
// 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{}
|
reserveBankOfAustraliaData := &ReserveBankOfAustraliaData{}
|
||||||
err := xml.Unmarshal(content, reserveBankOfAustraliaData)
|
err := xml.Unmarshal(content, reserveBankOfAustraliaData)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
latestExchangeRateResponse := reserveBankOfAustraliaData.ToLatestExchangeRateResponse(c)
|
latestExchangeRateResponse := reserveBankOfAustraliaData.ToLatestExchangeRateResponse(c)
|
||||||
|
|
||||||
if latestExchangeRateResponse == nil {
|
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
|
return nil, errs.ErrFailedToRequestRemoteApi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package exchangerates
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/core"
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
@@ -43,9 +42,7 @@ const reserveBankOfAustraliaMinimumRequiredContent = "<?xml version=\"1.0\" enco
|
|||||||
|
|
||||||
func TestReserveBankOfAustraliaDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
|
func TestReserveBankOfAustraliaDataSource_StandardDataExtractBaseCurrency(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(reserveBankOfAustraliaMinimumRequiredContent))
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(reserveBankOfAustraliaMinimumRequiredContent))
|
||||||
assert.Equal(t, nil, err)
|
assert.Equal(t, nil, err)
|
||||||
@@ -54,9 +51,7 @@ func TestReserveBankOfAustraliaDataSource_StandardDataExtractBaseCurrency(t *tes
|
|||||||
|
|
||||||
func TestReserveBankOfAustraliaDataSource_StandardDataExtractExchangeRates(t *testing.T) {
|
func TestReserveBankOfAustraliaDataSource_StandardDataExtractExchangeRates(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(reserveBankOfAustraliaMinimumRequiredContent))
|
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte(reserveBankOfAustraliaMinimumRequiredContent))
|
||||||
assert.Equal(t, nil, err)
|
assert.Equal(t, nil, err)
|
||||||
@@ -72,9 +67,7 @@ func TestReserveBankOfAustraliaDataSource_StandardDataExtractExchangeRates(t *te
|
|||||||
|
|
||||||
func TestReserveBankOfAustraliaDataSource_BlankContent(t *testing.T) {
|
func TestReserveBankOfAustraliaDataSource_BlankContent(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte(""))
|
_, err := dataSource.Parse(context, []byte(""))
|
||||||
assert.NotEqual(t, nil, err)
|
assert.NotEqual(t, nil, err)
|
||||||
@@ -82,9 +75,7 @@ func TestReserveBankOfAustraliaDataSource_BlankContent(t *testing.T) {
|
|||||||
|
|
||||||
func TestReserveBankOfAustraliaDataSource_OnlyXMLHeader(t *testing.T) {
|
func TestReserveBankOfAustraliaDataSource_OnlyXMLHeader(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"))
|
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"))
|
||||||
assert.NotEqual(t, nil, err)
|
assert.NotEqual(t, nil, err)
|
||||||
@@ -92,9 +83,7 @@ func TestReserveBankOfAustraliaDataSource_OnlyXMLHeader(t *testing.T) {
|
|||||||
|
|
||||||
func TestReserveBankOfAustraliaDataSource_EmptyRDFContent(t *testing.T) {
|
func TestReserveBankOfAustraliaDataSource_EmptyRDFContent(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
|
_, 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"+
|
"<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) {
|
func TestReserveBankOfAustraliaDataSource_EmptyChannelContent(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
|
_, 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"+
|
"<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) {
|
func TestReserveBankOfAustraliaDataSource_NoItem(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
|
_, 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"+
|
"<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) {
|
func TestReserveBankOfAustraliaDataSource_BaseCurrencyNotEqualPreset(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
|
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"+
|
"<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) {
|
func TestReserveBankOfAustraliaDataSource_UnitCurrencyNotEqualPreset(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
|
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"+
|
"<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) {
|
func TestReserveBankOfAustraliaDataSource_InvalidCurrency(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
|
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"+
|
"<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) {
|
func TestReserveBankOfAustraliaDataSource_EmptyRate(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
|
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"+
|
"<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) {
|
func TestReserveBankOfAustraliaDataSource_InvalidRate(t *testing.T) {
|
||||||
dataSource := &ReserveBankOfAustraliaDataSource{}
|
dataSource := &ReserveBankOfAustraliaDataSource{}
|
||||||
context := &core.Context{
|
context := core.NewNullContext()
|
||||||
Context: &gin.Context{},
|
|
||||||
}
|
|
||||||
|
|
||||||
actualLatestExchangeRateResponse, err := dataSource.Parse(context, []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
|
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"+
|
"<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"+
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ func (f *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
|
|||||||
b.WriteString("] ")
|
b.WriteString("] ")
|
||||||
}
|
}
|
||||||
|
|
||||||
if requestId, exists := entry.Data[logFieldRequestId]; exists {
|
if requestId, exists := entry.Data[logFieldRequestId]; exists && requestId != "" {
|
||||||
b.WriteString(fmt.Sprintf("[%s] ", requestId))
|
b.WriteString(fmt.Sprintf("[%s] ", requestId))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+53
-42
@@ -132,76 +132,87 @@ func SetLoggerConfiguration(config *settings.Config, isDisableBootLog bool) erro
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Debugf logs debug log with custom format
|
// DebugfWithRequestId logs debug log with custom format
|
||||||
func Debugf(format string, args ...any) {
|
func Debugf(c core.Context, format string, args ...any) {
|
||||||
defaultLogger.Debug(getFinalLog(format, args...))
|
if c == nil {
|
||||||
}
|
defaultLogger.Debug(getFinalLog(format, args...))
|
||||||
|
} else {
|
||||||
// DebugfWithRequestId logs debug log with custom format and request id
|
defaultLogger.WithField(logFieldRequestId, c.GetContextId()).Debug(getFinalLog(format, args...))
|
||||||
func DebugfWithRequestId(c *core.Context, format string, args ...any) {
|
}
|
||||||
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Debug(getFinalLog(format, args...))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Infof logs info log with custom format
|
// Infof logs info log with custom format
|
||||||
func Infof(format string, args ...any) {
|
func Infof(c core.Context, format string, args ...any) {
|
||||||
defaultLogger.Info(getFinalLog(format, args...))
|
if c == nil {
|
||||||
}
|
defaultLogger.Info(getFinalLog(format, args...))
|
||||||
|
} else {
|
||||||
// InfofWithRequestId logs info log with custom format and request id
|
defaultLogger.WithField(logFieldRequestId, c.GetContextId()).Info(getFinalLog(format, args...))
|
||||||
func InfofWithRequestId(c *core.Context, format string, args ...any) {
|
}
|
||||||
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Info(getFinalLog(format, args...))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Warnf logs warn log with custom format
|
// Warnf logs warn log with custom format
|
||||||
func Warnf(format string, args ...any) {
|
func Warnf(c core.Context, format string, args ...any) {
|
||||||
defaultLogger.Warn(getFinalLog(format, args...))
|
if c == nil {
|
||||||
}
|
defaultLogger.Warn(getFinalLog(format, args...))
|
||||||
|
} else {
|
||||||
// WarnfWithRequestId logs warn log with custom format and request id
|
defaultLogger.WithField(logFieldRequestId, c.GetContextId()).Warn(getFinalLog(format, args...))
|
||||||
func WarnfWithRequestId(c *core.Context, format string, args ...any) {
|
}
|
||||||
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Warn(getFinalLog(format, args...))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Errorf logs error log with custom format
|
// Errorf logs error log with custom format
|
||||||
func Errorf(format string, args ...any) {
|
func Errorf(c core.Context, format string, args ...any) {
|
||||||
defaultLogger.Error(getFinalLog(format, args...))
|
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
|
// ErrorfWithExtra logs error log with custom format and extra info
|
||||||
func ErrorfWithRequestId(c *core.Context, format string, args ...any) {
|
func ErrorfWithExtra(c core.Context, extraString string, format string, args ...any) {
|
||||||
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Error(getFinalLog(format, args...))
|
if c == nil {
|
||||||
}
|
defaultLogger.WithField(logFieldExtra, extraString).Error(getFinalLog(format, args...))
|
||||||
|
} else {
|
||||||
// ErrorfWithRequestIdAndExtra logs error log with custom format and request id and extra info
|
defaultLogger.WithField(logFieldRequestId, c.GetContextId()).WithField(logFieldExtra, extraString).Error(getFinalLog(format, args...))
|
||||||
func ErrorfWithRequestIdAndExtra(c *core.Context, extraString string, format string, args ...any) {
|
}
|
||||||
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).WithField(logFieldExtra, extraString).Error(getFinalLog(format, args...))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// BootInfof logs boot info log
|
// BootInfof logs boot info log
|
||||||
func BootInfof(format string, args ...any) {
|
func BootInfof(c core.Context, format string, args ...any) {
|
||||||
if bootLogger != nil {
|
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
|
// BootWarnf logs boot warn log
|
||||||
func BootWarnf(format string, args ...any) {
|
func BootWarnf(c core.Context, format string, args ...any) {
|
||||||
if bootLogger != nil {
|
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
|
// BootErrorf logs boot error log
|
||||||
func BootErrorf(format string, args ...any) {
|
func BootErrorf(c core.Context, format string, args ...any) {
|
||||||
if bootLogger != nil {
|
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
|
// 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 {
|
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"
|
const tokenCookieParam = "ebk_auth_token"
|
||||||
|
|
||||||
// AmapApiProxyAuthCookie adds amap api proxy auth cookie to cookies in response
|
// 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()
|
token := c.GetTextualToken()
|
||||||
|
|
||||||
if token != "" {
|
if token != "" {
|
||||||
|
|||||||
@@ -23,22 +23,22 @@ const (
|
|||||||
const tokenQueryStringParam = "token"
|
const tokenQueryStringParam = "token"
|
||||||
|
|
||||||
// JWTAuthorization verifies whether current request is valid by jwt token in header
|
// 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)
|
jwtAuthorization(c, TOKEN_SOURCE_TYPE_HEADER)
|
||||||
}
|
}
|
||||||
|
|
||||||
// JWTAuthorizationByQueryString verifies whether current request is valid by jwt token in query string
|
// 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)
|
jwtAuthorization(c, TOKEN_SOURCE_TYPE_ARGUMENT)
|
||||||
}
|
}
|
||||||
|
|
||||||
// JWTAuthorizationByCookie verifies whether current request is valid by jwt token in cookie
|
// 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)
|
jwtAuthorization(c, TOKEN_SOURCE_TYPE_COOKIE)
|
||||||
}
|
}
|
||||||
|
|
||||||
// JWTTwoFactorAuthorization verifies whether current request is valid by 2fa passcode
|
// 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)
|
claims, err := getTokenClaims(c, TOKEN_SOURCE_TYPE_HEADER)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -47,7 +47,7 @@ func JWTTwoFactorAuthorization(c *core.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if claims.Type != core.USER_TOKEN_TYPE_REQUIRE_2FA {
|
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)
|
utils.PrintJsonErrorResult(c, errs.ErrCurrentTokenNotRequire2FA)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -57,7 +57,7 @@ func JWTTwoFactorAuthorization(c *core.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// JWTEmailVerifyAuthorization verifies whether current request is email verification
|
// 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)
|
claims, err := getTokenClaims(c, TOKEN_SOURCE_TYPE_ARGUMENT)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -66,7 +66,7 @@ func JWTEmailVerifyAuthorization(c *core.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if claims.Type != core.USER_TOKEN_TYPE_EMAIL_VERIFY {
|
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)
|
utils.PrintJsonErrorResult(c, errs.ErrCurrentInvalidToken)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -76,7 +76,7 @@ func JWTEmailVerifyAuthorization(c *core.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// JWTResetPasswordAuthorization verifies whether current request is password reset
|
// 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)
|
claims, err := getTokenClaims(c, TOKEN_SOURCE_TYPE_ARGUMENT)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -85,7 +85,7 @@ func JWTResetPasswordAuthorization(c *core.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if claims.Type != core.USER_TOKEN_TYPE_PASSWORD_RESET {
|
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)
|
utils.PrintJsonErrorResult(c, errs.ErrCurrentInvalidToken)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -94,7 +94,7 @@ func JWTResetPasswordAuthorization(c *core.Context) {
|
|||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
|
|
||||||
func jwtAuthorization(c *core.Context, source TokenSourceType) {
|
func jwtAuthorization(c *core.WebContext, source TokenSourceType) {
|
||||||
claims, err := getTokenClaims(c, source)
|
claims, err := getTokenClaims(c, source)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -103,13 +103,13 @@ func jwtAuthorization(c *core.Context, source TokenSourceType) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if claims.Type == core.USER_TOKEN_TYPE_REQUIRE_2FA {
|
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)
|
utils.PrintJsonErrorResult(c, errs.ErrCurrentTokenRequire2FA)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if claims.Type != core.USER_TOKEN_TYPE_NORMAL {
|
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)
|
utils.PrintJsonErrorResult(c, errs.ErrCurrentInvalidTokenType)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -118,28 +118,28 @@ func jwtAuthorization(c *core.Context, source TokenSourceType) {
|
|||||||
c.Next()
|
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)
|
token, claims, err := parseToken(c, source)
|
||||||
|
|
||||||
if err != nil {
|
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)
|
return nil, errs.Or(err, errs.ErrUnauthorizedAccess)
|
||||||
}
|
}
|
||||||
|
|
||||||
if !token.Valid {
|
if !token.Valid {
|
||||||
log.WarnfWithRequestId(c, "[authorization.getTokenClaims] token is invalid")
|
log.Warnf(c, "[authorization.getTokenClaims] token is invalid")
|
||||||
return nil, errs.ErrCurrentInvalidToken
|
return nil, errs.ErrCurrentInvalidToken
|
||||||
}
|
}
|
||||||
|
|
||||||
if claims.Uid <= 0 {
|
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 nil, errs.ErrCurrentInvalidToken
|
||||||
}
|
}
|
||||||
|
|
||||||
return claims, nil
|
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 {
|
if source == TOKEN_SOURCE_TYPE_ARGUMENT {
|
||||||
return services.Tokens.ParseTokenByArgument(c, tokenQueryStringParam)
|
return services.Tokens.ParseTokenByArgument(c, tokenQueryStringParam)
|
||||||
} else if source == TOKEN_SOURCE_TYPE_COOKIE {
|
} else if source == TOKEN_SOURCE_TYPE_COOKIE {
|
||||||
|
|||||||
@@ -20,12 +20,12 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Recovery logs error message when error occurs
|
// Recovery logs error message when error occurs
|
||||||
func Recovery(c *core.Context) {
|
func Recovery(c *core.WebContext) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if err := recover(); err != nil {
|
if err := recover(); err != nil {
|
||||||
stack := stack(3)
|
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)
|
utils.PrintJsonErrorResult(c, errs.ErrSystemError)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|||||||
@@ -10,14 +10,14 @@ const requestIdHeader = "X-Request-ID"
|
|||||||
|
|
||||||
// RequestId generates a new request id and add it to context and response header
|
// RequestId generates a new request id and add it to context and response header
|
||||||
func RequestId(config *settings.Config) core.MiddlewareHandlerFunc {
|
func RequestId(config *settings.Config) core.MiddlewareHandlerFunc {
|
||||||
return func(c *core.Context) {
|
return func(c *core.WebContext) {
|
||||||
if requestid.Container.Current == nil {
|
if requestid.Container.Current == nil {
|
||||||
c.Next()
|
c.Next()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
requestId := requestid.Container.Current.GenerateRequestId(c.ClientIP(), c.ClientPort())
|
requestId := requestid.Container.Current.GenerateRequestId(c.ClientIP(), c.ClientPort())
|
||||||
c.SetRequestId(requestId)
|
c.SetContextId(requestId)
|
||||||
|
|
||||||
if config.EnableRequestIdHeader {
|
if config.EnableRequestIdHeader {
|
||||||
c.Header(requestIdHeader, requestId)
|
c.Header(requestIdHeader, requestId)
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// RequestLog logs the http request log
|
// RequestLog logs the http request log
|
||||||
func RequestLog(c *core.Context) {
|
func RequestLog(c *core.WebContext) {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
path := c.Request.URL.Path
|
path := c.Request.URL.Path
|
||||||
query := c.Request.URL.RawQuery
|
query := c.Request.URL.RawQuery
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ const settingsCookieName = "ebk_server_settings"
|
|||||||
|
|
||||||
// ServerSettingsCookie adds server settings to cookies in response
|
// ServerSettingsCookie adds server settings to cookies in response
|
||||||
func ServerSettingsCookie(config *settings.Config) core.MiddlewareHandlerFunc {
|
func ServerSettingsCookie(config *settings.Config) core.MiddlewareHandlerFunc {
|
||||||
return func(c *core.Context) {
|
return func(c *core.WebContext) {
|
||||||
settingsArr := []string{
|
settingsArr := []string{
|
||||||
buildBooleanSetting("r", config.EnableUserRegister),
|
buildBooleanSetting("r", config.EnableUserRegister),
|
||||||
buildBooleanSetting("f", config.EnableUserForgetPassword),
|
buildBooleanSetting("f", config.EnableUserForgetPassword),
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
"github.com/mayswind/ezbookkeeping/pkg/errs"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/log"
|
"github.com/mayswind/ezbookkeeping/pkg/log"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/settings"
|
"github.com/mayswind/ezbookkeeping/pkg/settings"
|
||||||
@@ -51,8 +52,8 @@ type DefaultRequestIdGenerator struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewDefaultRequestIdGenerator returns a new default request id generator
|
// NewDefaultRequestIdGenerator returns a new default request id generator
|
||||||
func NewDefaultRequestIdGenerator(config *settings.Config) (*DefaultRequestIdGenerator, error) {
|
func NewDefaultRequestIdGenerator(c core.Context, config *settings.Config) (*DefaultRequestIdGenerator, error) {
|
||||||
serverUniqId, err := getServerUniqId(config)
|
serverUniqId, err := getServerUniqId(c, config)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -68,7 +69,7 @@ func NewDefaultRequestIdGenerator(config *settings.Config) (*DefaultRequestIdGen
|
|||||||
return generator, nil
|
return generator, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getServerUniqId(config *settings.Config) (uint16, error) {
|
func getServerUniqId(c core.Context, config *settings.Config) (uint16, error) {
|
||||||
localAddr := ""
|
localAddr := ""
|
||||||
settingAddr := net.ParseIP(config.HttpAddr)
|
settingAddr := net.ParseIP(config.HttpAddr)
|
||||||
|
|
||||||
@@ -79,7 +80,7 @@ func getServerUniqId(config *settings.Config) (uint16, error) {
|
|||||||
localAddr, err = utils.GetLocalIPAddressesString()
|
localAddr, err = utils.GetLocalIPAddressesString()
|
||||||
|
|
||||||
if err != nil {
|
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
|
return 0, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,16 @@ import (
|
|||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/settings"
|
"github.com/mayswind/ezbookkeeping/pkg/settings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestNewDefaultRequestIdGenerator_Http(t *testing.T) {
|
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)
|
requestId := generator.GenerateRequestId("127.0.0.1", 20000)
|
||||||
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
|
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
|
||||||
|
|
||||||
@@ -23,7 +28,12 @@ func TestNewDefaultRequestIdGenerator_Http(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestNewDefaultRequestIdGenerator_UnixSocket(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)
|
requestId := generator.GenerateRequestId("127.0.0.1", 20000)
|
||||||
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
|
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
|
||||||
|
|
||||||
@@ -37,7 +47,12 @@ func TestNewDefaultRequestIdGenerator_UnixSocket(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestNewDefaultRequestIdGenerator_ClientIpv4(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)
|
requestId := generator.GenerateRequestId("127.0.0.1", 20000)
|
||||||
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
|
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
|
||||||
|
|
||||||
@@ -62,7 +77,12 @@ func TestNewDefaultRequestIdGenerator_ClientIpv4(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestNewDefaultRequestIdGenerator_ClientIpv6(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)
|
requestId := generator.GenerateRequestId("2001:abc:def:1234::1", 20000)
|
||||||
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
|
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
|
||||||
|
|
||||||
@@ -87,7 +107,12 @@ func TestNewDefaultRequestIdGenerator_ClientIpv6(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestNewDefaultRequestIdGenerator_ClientPort(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)
|
requestId := generator.GenerateRequestId("127.0.0.1", 0)
|
||||||
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
|
requestIdInfo := generator.parseRequestIdInfo(generator.parseRequestIdFromUuid(requestId))
|
||||||
|
|
||||||
@@ -132,7 +157,11 @@ func TestNewDefaultRequestIdGenerator_ClientPort(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestGenerateRequestId_100Times(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++ {
|
for i := 1; i <= 100; i++ {
|
||||||
requestId := generator.GenerateRequestId("127.0.0.1", 20000)
|
requestId := generator.GenerateRequestId("127.0.0.1", 20000)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package requestid
|
package requestid
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/mayswind/ezbookkeeping/pkg/core"
|
||||||
"github.com/mayswind/ezbookkeeping/pkg/settings"
|
"github.com/mayswind/ezbookkeeping/pkg/settings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -15,8 +16,8 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// InitializeRequestIdGenerator initializes the current request id generator according to the config
|
// InitializeRequestIdGenerator initializes the current request id generator according to the config
|
||||||
func InitializeRequestIdGenerator(config *settings.Config) error {
|
func InitializeRequestIdGenerator(c core.Context, config *settings.Config) error {
|
||||||
generator, err := NewDefaultRequestIdGenerator(config)
|
generator, err := NewDefaultRequestIdGenerator(c, config)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
+13
-13
@@ -33,7 +33,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// GetTotalAccountCountByUid returns total account count of user
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
return 0, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -44,7 +44,7 @@ func (s *AccountService) GetTotalAccountCountByUid(c *core.Context, uid int64) (
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetAllAccountsByUid returns all account models of user
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if mainAccount.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -316,7 +316,7 @@ func (s *AccountService) ModifyAccounts(c *core.Context, uid int64, accounts []*
|
|||||||
}
|
}
|
||||||
|
|
||||||
// HideAccount updates hidden field of given 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -368,7 +368,7 @@ func (s *AccountService) ModifyAccountDisplayOrders(c *core.Context, uid int64,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteAccount deletes an existed account from database
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// SendPasswordResetEmail sends password reset email according to specified parameters
|
// 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 {
|
if !s.CurrentConfig().EnableSMTP {
|
||||||
return errs.ErrSMTPServerNotEnabled
|
return errs.ErrSMTPServerNotEnabled
|
||||||
}
|
}
|
||||||
|
|||||||
+39
-29
@@ -38,7 +38,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// GetAllTokensByUid returns all token models of given user
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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{})
|
return s.parseToken(c, request.BearerExtractor{})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseTokenByArgument returns the token model according to request data
|
// 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})
|
return s.parseToken(c, request.ArgumentExtractor{tokenParameterName})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseTokenByCookie returns the token model according to request data
|
// 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})
|
return s.parseToken(c, utils.CookieExtractor{tokenCookieName})
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateToken generates a new normal token and saves to database
|
// 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)
|
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
|
// 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)
|
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
|
// 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)
|
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
|
// 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)
|
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
|
// 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 {
|
if tokenRecord.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -124,7 +134,7 @@ func (s *TokenService) UpdateTokenLastSeen(c *core.Context, tokenRecord *models.
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteToken deletes given token from database
|
// 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 {
|
if tokenRecord.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -147,7 +157,7 @@ func (s *TokenService) DeleteToken(c *core.Context, tokenRecord *models.TokenRec
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteTokens deletes given tokens from database
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -169,7 +179,7 @@ func (s *TokenService) DeleteTokens(c *core.Context, uid int64, tokenRecords []*
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteTokenByClaims deletes given token from database
|
// 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)
|
userTokenId, err := utils.StringToInt64(claims.UserTokenId)
|
||||||
|
|
||||||
if err != nil {
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -196,7 +206,7 @@ func (s *TokenService) DeleteTokensBeforeTime(c *core.Context, uid int64, create
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteTokensByType deletes specified type tokens
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -208,7 +218,7 @@ func (s *TokenService) DeleteTokensByType(c *core.Context, uid int64, tokenType
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteAllExpiredTokens deletes all expired tokens
|
// DeleteAllExpiredTokens deletes all expired tokens
|
||||||
func (s *TokenService) DeleteAllExpiredTokens(c *core.Context) error {
|
func (s *TokenService) DeleteAllExpiredTokens(c core.Context) error {
|
||||||
var errors []error
|
var errors []error
|
||||||
totalCount := int64(0)
|
totalCount := int64(0)
|
||||||
|
|
||||||
@@ -225,16 +235,16 @@ func (s *TokenService) DeleteAllExpiredTokens(c *core.Context) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if totalCount > 0 {
|
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 {
|
} 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...)
|
return errs.NewMultiErrorOrNil(errors...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExistsValidTokenByType returns whether the given token type exists
|
// 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 {
|
if uid <= 0 {
|
||||||
return false, errs.ErrUserIdInvalid
|
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)
|
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{}
|
claims := &core.UserTokenClaims{}
|
||||||
|
|
||||||
token, err := request.ParseFromRequest(c.Request, extractor,
|
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)
|
userTokenId, err := utils.StringToInt64(claims.UserTokenId)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrInvalidUserTokenId
|
||||||
}
|
}
|
||||||
|
|
||||||
tokenRecord, err := s.getTokenRecord(c, claims.Uid, userTokenId, claims.IssuedAt)
|
tokenRecord, err := s.getTokenRecord(c, claims.Uid, userTokenId, claims.IssuedAt)
|
||||||
|
|
||||||
if err != nil {
|
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
|
return nil, errs.ErrTokenRecordNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if tokenRecord.ExpiredUnixTime < now {
|
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
|
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 {
|
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
|
return nil, nil, errs.ErrCurrentInvalidToken
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -330,7 +340,7 @@ func (s *TokenService) parseToken(c *core.Context, extractor request.Extractor)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err == jwt.ErrTokenUsedBeforeIssued {
|
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
|
return nil, nil, errs.ErrCurrentInvalidToken
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -340,7 +350,7 @@ func (s *TokenService) parseToken(c *core.Context, extractor request.Extractor)
|
|||||||
return token, claims, err
|
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
|
var err error
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
|
||||||
@@ -383,7 +393,7 @@ func (s *TokenService) createToken(c *core.Context, user *models.User, tokenType
|
|||||||
return tokenString, claims, err
|
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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
return nil, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -406,7 +416,7 @@ func (s *TokenService) getTokenRecord(c *core.Context, uid int64, userTokenId in
|
|||||||
return tokenRecord, nil
|
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 {
|
if tokenRecord.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -429,7 +439,7 @@ func (s *TokenService) getUserTokenId() int64 {
|
|||||||
return userTokenId
|
return userTokenId
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *TokenService) getUserAgent(ctx *core.Context) string {
|
func (s *TokenService) getUserAgent(ctx *core.WebContext) string {
|
||||||
userAgent := ""
|
userAgent := ""
|
||||||
|
|
||||||
if ctx != nil && ctx.Request != nil {
|
if ctx != nil && ctx.Request != nil {
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// GetTotalCategoryCountByUid returns total category count of user
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
return 0, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -43,7 +43,7 @@ func (s *TransactionCategoryService) GetTotalCategoryCountByUid(c *core.Context,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetAllCategoriesByUid returns all transaction category models of user
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
return 0, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -199,7 +199,7 @@ func (s *TransactionCategoryService) GetMaxSubCategoryDisplayOrder(c *core.Conte
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CreateCategory saves a new transaction category model to database
|
// 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 {
|
if category.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if category.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -305,7 +305,7 @@ func (s *TransactionCategoryService) ModifyCategory(c *core.Context, category *m
|
|||||||
}
|
}
|
||||||
|
|
||||||
// HideCategory updates hidden field of given transaction categories
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -357,7 +357,7 @@ func (s *TransactionCategoryService) ModifyCategoryDisplayOrders(c *core.Context
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteCategory deletes an existed transaction category from database
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -406,7 +406,7 @@ func (s *TransactionCategoryService) DeleteCategory(c *core.Context, uid int64,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteAllCategories deletes all existed transaction categories from database
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// GetTotalTagCountByUid returns total tag count of user
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
return nil, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -99,7 +99,7 @@ func (s *TransactionTagService) GetTagsByTagIds(c *core.Context, uid int64, tagI
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetMaxDisplayOrder returns the max display order
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
return 0, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -119,7 +119,7 @@ func (s *TransactionTagService) GetMaxDisplayOrder(c *core.Context, uid int64) (
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetAllTagIdsOfAllTransactions returns all transaction tag ids
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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)
|
tagIndexes, err := s.GetAllTagIdsOfAllTransactions(c, uid)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -178,7 +178,7 @@ func (s *TransactionTagService) GetAllTagIdsMapOfAllTransactions(c *core.Context
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetAllTagIdsOfTransactions returns transaction tag ids for given transactions
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if tag.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if tag.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -303,7 +303,7 @@ func (s *TransactionTagService) ModifyTagDisplayOrders(c *core.Context, uid int6
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteTag deletes an existed transaction tag from database
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 == "" {
|
if name == "" {
|
||||||
return false, errs.ErrTransactionTagNameIsEmpty
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// GetTotalNormalTemplateCountByUid returns total template count of user
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
return 0, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -41,7 +41,7 @@ func (s *TransactionTemplateService) GetTotalNormalTemplateCountByUid(c *core.Co
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetAllTemplatesByUid returns all transaction template models of user
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
return nil, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -75,7 +75,7 @@ func (s *TransactionTemplateService) GetTemplateByTemplateId(c *core.Context, ui
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetMaxDisplayOrder returns the max display order
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if template.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if template.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -138,7 +138,7 @@ func (s *TransactionTemplateService) ModifyTemplate(c *core.Context, template *m
|
|||||||
}
|
}
|
||||||
|
|
||||||
// HideTemplate updates hidden field of given transaction templates
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -190,7 +190,7 @@ func (s *TransactionTemplateService) ModifyTemplateDisplayOrders(c *core.Context
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteTemplate deletes an existed transaction template from database
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -216,7 +216,7 @@ func (s *TransactionTemplateService) DeleteTemplate(c *core.Context, uid int64,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteAllTemplates deletes all existed transaction templates from database
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// GetTotalTransactionCountByUid returns total transaction count of user
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
return 0, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -48,7 +48,7 @@ func (s *TransactionService) GetTotalTransactionCountByUid(c *core.Context, uid
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetAllTransactions returns all transactions
|
// 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())
|
maxTransactionTime := utils.GetMaxTransactionTimeFromUnixTime(time.Now().Unix())
|
||||||
var allTransactions []*models.Transaction
|
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
|
// 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)
|
return s.GetTransactionsByMaxTime(c, uid, maxTransactionTime, 0, 0, nil, nil, nil, false, "", "", 1, count, false, noDuplicated)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetTransactionsByMaxTime returns transactions before given time
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
return nil, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -179,12 +179,12 @@ func (s *TransactionService) GetTransactionByTransactionId(c *core.Context, uid
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetAllTransactionCount returns total count of transactions
|
// 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, "", "")
|
return s.GetTransactionCount(c, uid, 0, 0, 0, nil, nil, nil, false, "", "")
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetTransactionCount returns count of transactions
|
// 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 {
|
if uid <= 0 {
|
||||||
return 0, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if transaction.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -430,7 +430,7 @@ func (s *TransactionService) CreateTransaction(c *core.Context, transaction *mod
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ModifyTransaction saves an existed transaction to database
|
// 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 {
|
if transaction.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -826,7 +826,7 @@ func (s *TransactionService) ModifyTransaction(c *core.Context, transaction *mod
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteTransaction deletes an existed transaction from database
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -950,7 +950,7 @@ func (s *TransactionService) DeleteTransaction(c *core.Context, uid int64, trans
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteAllTransactions deletes all existed transactions from database
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
return nil, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// GetUserTwoFactorSettingByUid returns the 2fa setting model according to user uid
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
return nil, errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -70,7 +70,7 @@ func (s *TwoFactorAuthorizationService) GetUserTwoFactorSettingByUid(c *core.Con
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GenerateTwoFactorSecret generates a new 2fa secret
|
// 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 {
|
if user == nil {
|
||||||
return nil, errs.ErrUserNotFound
|
return nil, errs.ErrUserNotFound
|
||||||
}
|
}
|
||||||
@@ -86,7 +86,7 @@ func (s *TwoFactorAuthorizationService) GenerateTwoFactorSecret(c *core.Context,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CreateTwoFactorSetting saves a new 2fa setting to database
|
// 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 {
|
if twoFactor.Uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -107,7 +107,7 @@ func (s *TwoFactorAuthorizationService) CreateTwoFactorSetting(c *core.Context,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteTwoFactorSetting deletes an existed 2fa setting from database
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -126,7 +126,7 @@ func (s *TwoFactorAuthorizationService) DeleteTwoFactorSetting(c *core.Context,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ExistsTwoFactorSetting returns whether the given user has existed 2fa setting
|
// 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 {
|
if uid <= 0 {
|
||||||
return false, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -173,7 +173,7 @@ func (s *TwoFactorAuthorizationService) GenerateTwoFactorRecoveryCodes() ([]stri
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CreateTwoFactorRecoveryCodes saves new 2fa recovery codes to database
|
// 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))
|
twoFactorRecoveryCodes := make([]*models.TwoFactorRecoveryCode, len(recoveryCodes))
|
||||||
|
|
||||||
for i := 0; i < len(recoveryCodes); i++ {
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
|
|||||||
+18
-18
@@ -58,7 +58,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// GetUserByUsernameOrEmailAndPassword returns the user model according to login name and password
|
// 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 user *models.User
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
@@ -82,7 +82,7 @@ func (s *UserService) GetUserByUsernameOrEmailAndPassword(c *core.Context, login
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetUserById returns the user model according to user uid
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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 == "" {
|
if username == "" {
|
||||||
return nil, errs.ErrUsernameIsEmpty
|
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
|
// 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 == "" {
|
if email == "" {
|
||||||
return nil, errs.ErrEmailIsEmpty
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return nil, errs.ErrUserIdInvalid
|
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
|
// 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)
|
exists, err := s.ExistsUsername(c, user.Username)
|
||||||
|
|
||||||
if err != nil {
|
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
|
// 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 {
|
if user.Uid <= 0 {
|
||||||
return false, false, errs.ErrUserIdInvalid
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -381,7 +381,7 @@ func (s *UserService) UpdateUserAvatar(c *core.Context, uid int64, avatarFile mu
|
|||||||
err = s.DeleteAvatar(uid, oldFileExtension)
|
err = s.DeleteAvatar(uid, oldFileExtension)
|
||||||
|
|
||||||
if err != nil {
|
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
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -414,7 +414,7 @@ func (s *UserService) RemoveUserAvatar(c *core.Context, uid int64, fileExtension
|
|||||||
}
|
}
|
||||||
|
|
||||||
// UpdateUserLastLoginTime updates the last login time field
|
// 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 {
|
if uid <= 0 {
|
||||||
return errs.ErrUserIdInvalid
|
return errs.ErrUserIdInvalid
|
||||||
}
|
}
|
||||||
@@ -426,7 +426,7 @@ func (s *UserService) UpdateUserLastLoginTime(c *core.Context, uid int64) error
|
|||||||
}
|
}
|
||||||
|
|
||||||
// EnableUser sets user enabled
|
// 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 == "" {
|
if username == "" {
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
@@ -449,7 +449,7 @@ func (s *UserService) EnableUser(c *core.Context, username string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DisableUser sets user disabled
|
// 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 == "" {
|
if username == "" {
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
@@ -472,7 +472,7 @@ func (s *UserService) DisableUser(c *core.Context, username string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetUserEmailVerified sets user email address verified
|
// 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 == "" {
|
if username == "" {
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
@@ -495,7 +495,7 @@ func (s *UserService) SetUserEmailVerified(c *core.Context, username string) err
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetUserEmailUnverified sets user email address unverified
|
// 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 == "" {
|
if username == "" {
|
||||||
return errs.ErrUsernameIsEmpty
|
return errs.ErrUsernameIsEmpty
|
||||||
}
|
}
|
||||||
@@ -518,7 +518,7 @@ func (s *UserService) SetUserEmailUnverified(c *core.Context, username string) e
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteUser deletes an existed user from database
|
// 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 == "" {
|
if username == "" {
|
||||||
return errs.ErrUsernameIsEmpty
|
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
|
// 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 == "" {
|
if username == "" {
|
||||||
return false, errs.ErrUsernameIsEmpty
|
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
|
// 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 == "" {
|
if email == "" {
|
||||||
return false, errs.ErrEmailIsEmpty
|
return false, errs.ErrEmailIsEmpty
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-4
@@ -12,7 +12,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// PrintJsonSuccessResult writes success response in json format to current http context
|
// 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{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"success": true,
|
"success": true,
|
||||||
"result": result,
|
"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
|
// 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 != "" {
|
if fileName != "" {
|
||||||
c.Header("Content-Disposition", "attachment;filename="+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
|
// 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)
|
c.SetResponseError(err)
|
||||||
|
|
||||||
errorMessage := err.Error()
|
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
|
// 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)
|
c.SetResponseError(err)
|
||||||
|
|
||||||
errorMessage := err.Error()
|
errorMessage := err.Error()
|
||||||
|
|||||||
Reference in New Issue
Block a user