code refactor
This commit is contained in:
+1
-1
@@ -62,7 +62,7 @@ func startWebServer(c *cli.Context) error {
|
||||
|
||||
serverInfo := fmt.Sprintf("current server id is %d, current instance id is %d", requestid.Container.Current.GetCurrentServerUniqId(), requestid.Container.Current.GetCurrentInstanceUniqId())
|
||||
uuidServerInfo := ""
|
||||
if config.UuidGeneratorType == settings.UUID_GENERATOR_TYPE_INTERNAL {
|
||||
if config.UuidGeneratorType == settings.InternalUuidGeneratorType {
|
||||
uuidServerInfo = fmt.Sprintf(", current uuid server id is %d", config.UuidServerId)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,13 +9,13 @@ import (
|
||||
"github.com/mayswind/lab/cmd"
|
||||
)
|
||||
|
||||
const LAB_VERSION = "0.1.0"
|
||||
const labVersion = "0.1.0"
|
||||
|
||||
func main() {
|
||||
app := &cli.App{
|
||||
Name: "lab",
|
||||
Usage: "A lightweight account book app hosted by yourself.",
|
||||
Version: LAB_VERSION,
|
||||
Version: labVersion,
|
||||
Commands: []*cli.Command{
|
||||
cmd.WebServer,
|
||||
cmd.Database,
|
||||
|
||||
+3
-3
@@ -53,7 +53,7 @@ func (a *AccountsApi) AccountListHandler(c *core.Context) (interface{}, *errs.Er
|
||||
continue
|
||||
}
|
||||
|
||||
if userAccountResp.ParentId <= models.ACCOUNT_PARENT_ID_LEVEL_ONE {
|
||||
if userAccountResp.ParentId <= models.LevelOneAccountParentId {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ func (a *AccountsApi) AccountListHandler(c *core.Context) (interface{}, *errs.Er
|
||||
userFinalAccountResps := make(models.AccountInfoResponseSlice, 0, len(userAllAccountResps))
|
||||
|
||||
for i := 0; i < len(userAllAccountResps); i++ {
|
||||
if userAllAccountResps[i].ParentId == models.ACCOUNT_PARENT_ID_LEVEL_ONE && (!accountListReq.VisibleOnly || !userAllAccountResps[i].Hidden) {
|
||||
if userAllAccountResps[i].ParentId == models.LevelOneAccountParentId && (!accountListReq.VisibleOnly || !userAllAccountResps[i].Hidden) {
|
||||
sort.Sort(userAllAccountResps[i].SubAccounts)
|
||||
userFinalAccountResps = append(userFinalAccountResps, userAllAccountResps[i])
|
||||
}
|
||||
@@ -142,7 +142,7 @@ func (a *AccountsApi) AccountCreateHandler(c *core.Context) (interface{}, *errs.
|
||||
return nil, errs.ErrAccountHaveNoSubAccount
|
||||
}
|
||||
|
||||
if accountCreateReq.Currency != validators.PARENT_ACCOUNT_CURRENCY_PLACEHODLER {
|
||||
if accountCreateReq.Currency != validators.ParentAccountCurrencyPlaceholder {
|
||||
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] parent account cannot set currency")
|
||||
return nil, errs.ErrParentAccountCannotSetCurrency
|
||||
}
|
||||
|
||||
@@ -335,7 +335,7 @@ func (a *TransactionCategoriesApi) getTransactionCategoryListByTypeResponse(cate
|
||||
for i := 0; i < len(categoryResps); i++ {
|
||||
categoryResp := categoryResps[i]
|
||||
|
||||
if categoryResp.ParentId <= models.TRANSACTION_PARENT_ID_LEVEL_ONE {
|
||||
if categoryResp.ParentId <= models.LevelOneTransactionParentId {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -351,7 +351,7 @@ func (a *TransactionCategoriesApi) getTransactionCategoryListByTypeResponse(cate
|
||||
finalCategoryResps := make(models.TransactionCategoryInfoResponseSlice, 0)
|
||||
|
||||
for i := 0; i < len(categoryResps); i++ {
|
||||
if parentId <= 0 && categoryResps[i].ParentId == models.TRANSACTION_PARENT_ID_LEVEL_ONE {
|
||||
if parentId <= 0 && categoryResps[i].ParentId == models.LevelOneTransactionParentId {
|
||||
sort.Sort(categoryResps[i].SubCategories)
|
||||
finalCategoryResps = append(finalCategoryResps, categoryResps[i])
|
||||
} else if parentId > 0 && categoryResps[i].ParentId == parentId {
|
||||
|
||||
+9
-9
@@ -8,9 +8,9 @@ import (
|
||||
"github.com/mayswind/lab/pkg/errs"
|
||||
)
|
||||
|
||||
const FIELD_REQUEST_ID_KEY = "REQUEST_ID"
|
||||
const FIELD_TOKEN_CLAIMS_KEY = "TOKEN_CLAIMS"
|
||||
const FIELD_RESPONSE_ERROR = "RESPONSE_ERROR"
|
||||
const requestIdFieldKey = "REQUEST_ID"
|
||||
const tokenClaimsFieldKey = "TOKEN_CLAIMS"
|
||||
const responseErrorFieldKey = "RESPONSE_ERROR"
|
||||
|
||||
type Context struct {
|
||||
*gin.Context
|
||||
@@ -18,11 +18,11 @@ type Context struct {
|
||||
}
|
||||
|
||||
func (c *Context) SetRequestId(requestId string) {
|
||||
c.Set(FIELD_REQUEST_ID_KEY, requestId)
|
||||
c.Set(requestIdFieldKey, requestId)
|
||||
}
|
||||
|
||||
func (c *Context) GetRequestId() string {
|
||||
requestId, exists := c.Get(FIELD_REQUEST_ID_KEY)
|
||||
requestId, exists := c.Get(requestIdFieldKey)
|
||||
|
||||
if !exists {
|
||||
return ""
|
||||
@@ -32,11 +32,11 @@ func (c *Context) GetRequestId() string {
|
||||
}
|
||||
|
||||
func (c *Context) SetTokenClaims(claims *UserTokenClaims) {
|
||||
c.Set(FIELD_TOKEN_CLAIMS_KEY, claims)
|
||||
c.Set(tokenClaimsFieldKey, claims)
|
||||
}
|
||||
|
||||
func (c *Context) GetTokenClaims() *UserTokenClaims {
|
||||
claims, exists := c.Get(FIELD_TOKEN_CLAIMS_KEY)
|
||||
claims, exists := c.Get(tokenClaimsFieldKey)
|
||||
|
||||
if !exists {
|
||||
return nil
|
||||
@@ -62,11 +62,11 @@ func (c *Context) GetCurrentUid() int64 {
|
||||
}
|
||||
|
||||
func (c *Context) SetResponseError(error *errs.Error) {
|
||||
c.Set(FIELD_RESPONSE_ERROR, error)
|
||||
c.Set(responseErrorFieldKey, error)
|
||||
}
|
||||
|
||||
func (c *Context) GetResponseError() *errs.Error {
|
||||
err, exists := c.Get(FIELD_RESPONSE_ERROR)
|
||||
err, exists := c.Get(responseErrorFieldKey)
|
||||
|
||||
if !exists {
|
||||
return nil
|
||||
|
||||
@@ -60,7 +60,7 @@ func initializeDatabase(dbConfig *settings.DatabaseConfig) (*Database, error) {
|
||||
var connStr string
|
||||
var err error
|
||||
|
||||
if dbConfig.DatabaseType == settings.DBTYPE_SQLITE3 {
|
||||
if dbConfig.DatabaseType == settings.Sqlite3DbType {
|
||||
if _, err = os.Stat(dbConfig.DatabasePath); err != nil {
|
||||
file, err := os.Create(dbConfig.DatabasePath)
|
||||
|
||||
@@ -72,11 +72,11 @@ func initializeDatabase(dbConfig *settings.DatabaseConfig) (*Database, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if dbConfig.DatabaseType == settings.DBTYPE_MYSQL {
|
||||
if dbConfig.DatabaseType == settings.MySqlDbType {
|
||||
connStr, err = getMysqlConnectionString(dbConfig)
|
||||
} else if dbConfig.DatabaseType == settings.DBTYPE_POSTGRES {
|
||||
} else if dbConfig.DatabaseType == settings.PostgresDbType {
|
||||
connStr, err = getPostgresConnectionString(dbConfig)
|
||||
} else if dbConfig.DatabaseType == settings.DBTYPE_SQLITE3 {
|
||||
} else if dbConfig.DatabaseType == settings.Sqlite3DbType {
|
||||
connStr, err = getSqlite3ConnectionString(dbConfig)
|
||||
} else {
|
||||
return nil, errs.ErrDatabaseTypeInvalid
|
||||
|
||||
+13
-13
@@ -4,17 +4,17 @@ import "net/http"
|
||||
|
||||
// Error codes related to accounts
|
||||
var (
|
||||
ErrAccountIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 0, http.StatusBadRequest, "account id is invalid")
|
||||
ErrAccountNotFound = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 1, http.StatusBadRequest, "account not found")
|
||||
ErrAccountTypeInvalid = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 2, http.StatusBadRequest, "account type is invalid")
|
||||
ErrAccountHaveNoSubAccount = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 3, http.StatusBadRequest, "account must have at least one sub account")
|
||||
ErrAccountCannotHaveSubAccounts = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 4, http.StatusBadRequest, "account cannot have sub accounts")
|
||||
ErrParentAccountCannotSetCurrency = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 5, http.StatusBadRequest, "parent account cannot set currency")
|
||||
ErrParentAccountCannotSetBalance = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 6, http.StatusBadRequest, "parent account cannot set balance")
|
||||
ErrSubAccountCategoryNotEqualsToParent = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 7, http.StatusBadRequest, "sub account category not equals to parent")
|
||||
ErrSubAccountTypeInvalid = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 8, http.StatusBadRequest, "sub account type invalid")
|
||||
ErrCannotAddOrDeleteSubAccountsWhenModify = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 9, http.StatusBadRequest, "cannot add or delete sub accounts when modify account")
|
||||
ErrSourceAccountNotFound = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 10, http.StatusBadRequest, "source account not found")
|
||||
ErrDestinationAccountNotFound = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 11, http.StatusBadRequest, "destination account not found")
|
||||
ErrAccountInUseCannotBeDeleted = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 12, http.StatusBadRequest, "account is in use and cannot be deleted")
|
||||
ErrAccountIdInvalid = NewNormalError(NormalSubcategoryAccount, 0, http.StatusBadRequest, "account id is invalid")
|
||||
ErrAccountNotFound = NewNormalError(NormalSubcategoryAccount, 1, http.StatusBadRequest, "account not found")
|
||||
ErrAccountTypeInvalid = NewNormalError(NormalSubcategoryAccount, 2, http.StatusBadRequest, "account type is invalid")
|
||||
ErrAccountHaveNoSubAccount = NewNormalError(NormalSubcategoryAccount, 3, http.StatusBadRequest, "account must have at least one sub account")
|
||||
ErrAccountCannotHaveSubAccounts = NewNormalError(NormalSubcategoryAccount, 4, http.StatusBadRequest, "account cannot have sub accounts")
|
||||
ErrParentAccountCannotSetCurrency = NewNormalError(NormalSubcategoryAccount, 5, http.StatusBadRequest, "parent account cannot set currency")
|
||||
ErrParentAccountCannotSetBalance = NewNormalError(NormalSubcategoryAccount, 6, http.StatusBadRequest, "parent account cannot set balance")
|
||||
ErrSubAccountCategoryNotEqualsToParent = NewNormalError(NormalSubcategoryAccount, 7, http.StatusBadRequest, "sub account category not equals to parent")
|
||||
ErrSubAccountTypeInvalid = NewNormalError(NormalSubcategoryAccount, 8, http.StatusBadRequest, "sub account type invalid")
|
||||
ErrCannotAddOrDeleteSubAccountsWhenModify = NewNormalError(NormalSubcategoryAccount, 9, http.StatusBadRequest, "cannot add or delete sub accounts when modify account")
|
||||
ErrSourceAccountNotFound = NewNormalError(NormalSubcategoryAccount, 10, http.StatusBadRequest, "source account not found")
|
||||
ErrDestinationAccountNotFound = NewNormalError(NormalSubcategoryAccount, 11, http.StatusBadRequest, "destination account not found")
|
||||
ErrAccountInUseCannotBeDeleted = NewNormalError(NormalSubcategoryAccount, 12, http.StatusBadRequest, "account is in use and cannot be deleted")
|
||||
)
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
|
||||
// Error codes related to database
|
||||
var (
|
||||
ErrDatabaseTypeInvalid = NewSystemError(SYSTEM_SUBCATEGORY_DATABASE, 0, http.StatusInternalServerError, "database type is invalid")
|
||||
ErrDatabaseHostInvalid = NewSystemError(SYSTEM_SUBCATEGORY_DATABASE, 1, http.StatusInternalServerError, "database host is invalid")
|
||||
ErrDatabaseIsNull = NewSystemError(SYSTEM_SUBCATEGORY_DATABASE, 2, http.StatusInternalServerError, "database cannot be null")
|
||||
ErrDatabaseOperationFailed = NewSystemError(SYSTEM_SUBCATEGORY_DATABASE, 3, http.StatusInternalServerError, "database operation failed")
|
||||
ErrDatabaseTypeInvalid = NewSystemError(SystemSubcategoryDatabase, 0, http.StatusInternalServerError, "database type is invalid")
|
||||
ErrDatabaseHostInvalid = NewSystemError(SystemSubcategoryDatabase, 1, http.StatusInternalServerError, "database host is invalid")
|
||||
ErrDatabaseIsNull = NewSystemError(SystemSubcategoryDatabase, 2, http.StatusInternalServerError, "database cannot be null")
|
||||
ErrDatabaseOperationFailed = NewSystemError(SystemSubcategoryDatabase, 3, http.StatusInternalServerError, "database operation failed")
|
||||
)
|
||||
|
||||
+11
-11
@@ -11,21 +11,21 @@ const (
|
||||
|
||||
// Sub categories of system error
|
||||
const (
|
||||
SYSTEM_SUBCATEGORY_DEFAULT = 0
|
||||
SYSTEM_SUBCATEGORY_SETTING = 1
|
||||
SYSTEM_SUBCATEGORY_DATABASE = 2
|
||||
SystemSubcategoryDefault = 0
|
||||
SystemSubcategorySetting = 1
|
||||
SystemSubcategoryDatabase = 2
|
||||
)
|
||||
|
||||
// Sub categories of normal error
|
||||
const (
|
||||
NORMAL_SUBCATEGORY_GLOBAL = 0
|
||||
NORMAL_SUBCATEGORY_USER = 1
|
||||
NORMAL_SUBCATEGORY_TOKEN = 2
|
||||
NORMAL_SUBCATEGORY_TWOFACTOR = 3
|
||||
NORMAL_SUBCATEGORY_ACCOUNT = 4
|
||||
NORMAL_SUBCATEGORY_TRANSACTION = 5
|
||||
NORMAL_SUBCATEGORY_CATEGORY = 6
|
||||
NORMAL_SUBCATEGORY_TAG = 7
|
||||
NormalSubcategoryGlobal = 0
|
||||
NormalSubcategoryUser = 1
|
||||
NormalSubcategoryToken = 2
|
||||
NormalSubcategoryTwofactor = 3
|
||||
NormalSubcategoryAccount = 4
|
||||
NormalSubcategoryTransaction = 5
|
||||
NormalSubcategoryCategory = 6
|
||||
NormalSubcategoryTag = 7
|
||||
)
|
||||
|
||||
// Error represents the specific error returned to user
|
||||
|
||||
+8
-8
@@ -7,14 +7,14 @@ import (
|
||||
|
||||
// General error codes
|
||||
var (
|
||||
ErrIncompleteOrIncorrectSubmission = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 0, http.StatusBadRequest, "incomplete or incorrect submission")
|
||||
ErrOperationFailed = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 1, http.StatusInternalServerError, "operation failed")
|
||||
ErrRequestIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 2, http.StatusInternalServerError, "request id is invalid")
|
||||
ErrCiphertextInvalid = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 3, http.StatusInternalServerError, "ciphertext is invalid")
|
||||
ErrNothingWillBeUpdated = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 4, http.StatusBadRequest, "nothing will be updated")
|
||||
ErrFailedToRequestRemoteApi = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 5, http.StatusBadRequest, "failed to request third party api")
|
||||
ErrPageIndexInvalid = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 6, http.StatusBadRequest, "page index is invalid")
|
||||
ErrPageCountInvalid = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 7, http.StatusBadRequest, "page count is invalid")
|
||||
ErrIncompleteOrIncorrectSubmission = NewNormalError(NormalSubcategoryGlobal, 0, http.StatusBadRequest, "incomplete or incorrect submission")
|
||||
ErrOperationFailed = NewNormalError(NormalSubcategoryGlobal, 1, http.StatusInternalServerError, "operation failed")
|
||||
ErrRequestIdInvalid = NewNormalError(NormalSubcategoryGlobal, 2, http.StatusInternalServerError, "request id is invalid")
|
||||
ErrCiphertextInvalid = NewNormalError(NormalSubcategoryGlobal, 3, http.StatusInternalServerError, "ciphertext is invalid")
|
||||
ErrNothingWillBeUpdated = NewNormalError(NormalSubcategoryGlobal, 4, http.StatusBadRequest, "nothing will be updated")
|
||||
ErrFailedToRequestRemoteApi = NewNormalError(NormalSubcategoryGlobal, 5, http.StatusBadRequest, "failed to request third party api")
|
||||
ErrPageIndexInvalid = NewNormalError(NormalSubcategoryGlobal, 6, http.StatusBadRequest, "page index is invalid")
|
||||
ErrPageCountInvalid = NewNormalError(NormalSubcategoryGlobal, 7, http.StatusBadRequest, "page count is invalid")
|
||||
)
|
||||
|
||||
// GetParameterInvalidMessage returns specific error message for invalid parameter error
|
||||
|
||||
+4
-4
@@ -4,8 +4,8 @@ import "net/http"
|
||||
|
||||
// Error codes related to settings
|
||||
var (
|
||||
ErrInvalidProtocol = NewSystemError(SYSTEM_SUBCATEGORY_SETTING, 0, http.StatusInternalServerError, "invalid server protocol")
|
||||
ErrInvalidLogMode = NewSystemError(SYSTEM_SUBCATEGORY_SETTING, 1, http.StatusInternalServerError, "invalid log mode")
|
||||
ErrGettingLocalAddress = NewSystemError(SYSTEM_SUBCATEGORY_SETTING, 2, http.StatusInternalServerError, "failed to get local address")
|
||||
ErrInvalidUuidMode = NewSystemError(SYSTEM_SUBCATEGORY_SETTING, 3, http.StatusInternalServerError, "invalid uuid mode")
|
||||
ErrInvalidProtocol = NewSystemError(SystemSubcategorySetting, 0, http.StatusInternalServerError, "invalid server protocol")
|
||||
ErrInvalidLogMode = NewSystemError(SystemSubcategorySetting, 1, http.StatusInternalServerError, "invalid log mode")
|
||||
ErrGettingLocalAddress = NewSystemError(SystemSubcategorySetting, 2, http.StatusInternalServerError, "failed to get local address")
|
||||
ErrInvalidUuidMode = NewSystemError(SystemSubcategorySetting, 3, http.StatusInternalServerError, "invalid uuid mode")
|
||||
)
|
||||
|
||||
+4
-4
@@ -4,8 +4,8 @@ import "net/http"
|
||||
|
||||
// Error codes related to transaction categories
|
||||
var (
|
||||
ErrSystemError = NewSystemError(SYSTEM_SUBCATEGORY_DEFAULT, 0, http.StatusInternalServerError, "system error")
|
||||
ErrApiNotFound = NewSystemError(SYSTEM_SUBCATEGORY_DEFAULT, 1, http.StatusNotFound, "api not found")
|
||||
ErrMethodNotAllowed = NewSystemError(SYSTEM_SUBCATEGORY_DEFAULT, 2, http.StatusMethodNotAllowed, "method not allowed")
|
||||
ErrNotImplemented = NewSystemError(SYSTEM_SUBCATEGORY_DEFAULT, 3, http.StatusNotImplemented, "not implemented")
|
||||
ErrSystemError = NewSystemError(SystemSubcategoryDefault, 0, http.StatusInternalServerError, "system error")
|
||||
ErrApiNotFound = NewSystemError(SystemSubcategoryDefault, 1, http.StatusNotFound, "api not found")
|
||||
ErrMethodNotAllowed = NewSystemError(SystemSubcategoryDefault, 2, http.StatusMethodNotAllowed, "method not allowed")
|
||||
ErrNotImplemented = NewSystemError(SystemSubcategoryDefault, 3, http.StatusNotImplemented, "not implemented")
|
||||
)
|
||||
|
||||
+12
-12
@@ -6,16 +6,16 @@ import (
|
||||
|
||||
// Error codes related to tokens
|
||||
var (
|
||||
ErrTokenGenerating = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 0, http.StatusInternalServerError, "failed to generate token")
|
||||
ErrUnauthorizedAccess = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 1, http.StatusUnauthorized, "unauthorized access")
|
||||
ErrCurrentInvalidToken = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 2, http.StatusUnauthorized, "current token is invalid")
|
||||
ErrCurrentTokenExpired = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 3, http.StatusUnauthorized, "current token is expired")
|
||||
ErrCurrentInvalidTokenType = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 4, http.StatusUnauthorized, "current token type is invalid")
|
||||
ErrCurrentTokenRequire2FA = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 5, http.StatusUnauthorized, "current token requires two factor authorization")
|
||||
ErrCurrentTokenNotRequire2FA = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 6, http.StatusUnauthorized, "current token does not require two factor authorization")
|
||||
ErrInvalidToken = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 7, http.StatusBadRequest, "token is invalid")
|
||||
ErrInvalidTokenId = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 8, http.StatusBadRequest, "token id is invalid")
|
||||
ErrInvalidUserTokenId = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 9, http.StatusBadRequest, "user token id is invalid")
|
||||
ErrTokenRecordNotFound = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 10, http.StatusBadRequest, "token is not found")
|
||||
ErrTokenExpired = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 11, http.StatusBadRequest, "token is expired")
|
||||
ErrTokenGenerating = NewNormalError(NormalSubcategoryToken, 0, http.StatusInternalServerError, "failed to generate token")
|
||||
ErrUnauthorizedAccess = NewNormalError(NormalSubcategoryToken, 1, http.StatusUnauthorized, "unauthorized access")
|
||||
ErrCurrentInvalidToken = NewNormalError(NormalSubcategoryToken, 2, http.StatusUnauthorized, "current token is invalid")
|
||||
ErrCurrentTokenExpired = NewNormalError(NormalSubcategoryToken, 3, http.StatusUnauthorized, "current token is expired")
|
||||
ErrCurrentInvalidTokenType = NewNormalError(NormalSubcategoryToken, 4, http.StatusUnauthorized, "current token type is invalid")
|
||||
ErrCurrentTokenRequire2FA = NewNormalError(NormalSubcategoryToken, 5, http.StatusUnauthorized, "current token requires two factor authorization")
|
||||
ErrCurrentTokenNotRequire2FA = NewNormalError(NormalSubcategoryToken, 6, http.StatusUnauthorized, "current token does not require two factor authorization")
|
||||
ErrInvalidToken = NewNormalError(NormalSubcategoryToken, 7, http.StatusBadRequest, "token is invalid")
|
||||
ErrInvalidTokenId = NewNormalError(NormalSubcategoryToken, 8, http.StatusBadRequest, "token id is invalid")
|
||||
ErrInvalidUserTokenId = NewNormalError(NormalSubcategoryToken, 9, http.StatusBadRequest, "user token id is invalid")
|
||||
ErrTokenRecordNotFound = NewNormalError(NormalSubcategoryToken, 10, http.StatusBadRequest, "token is not found")
|
||||
ErrTokenExpired = NewNormalError(NormalSubcategoryToken, 11, http.StatusBadRequest, "token is expired")
|
||||
)
|
||||
|
||||
+13
-13
@@ -4,17 +4,17 @@ import "net/http"
|
||||
|
||||
// Error codes related to transaction
|
||||
var (
|
||||
ErrTransactionIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 0, http.StatusBadRequest, "transaction id is invalid")
|
||||
ErrTransactionNotFound = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 1, http.StatusBadRequest, "transaction not found")
|
||||
ErrTransactionTypeInvalid = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 2, http.StatusBadRequest, "transaction type is invalid")
|
||||
ErrTransactionSourceAndDestinationIdNotEqual = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 3, http.StatusBadRequest, "transaction source and destination account id not equal")
|
||||
ErrTransactionSourceAndDestinationIdCannotBeEqual = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 4, http.StatusBadRequest, "transaction source and destination account id cannot be equal")
|
||||
ErrTransactionSourceAndDestinationAmountNotEqual = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 5, http.StatusBadRequest, "transaction source and destination amount not equal")
|
||||
ErrTooMuchTransactionInOneSecond = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 6, http.StatusBadRequest, "too much transaction in one second")
|
||||
ErrBalanceModificationTransactionCannotSetCategory = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 7, http.StatusBadRequest, "balance modification transaction cannot set category")
|
||||
ErrBalanceModificationTransactionCannotChangeAccountId = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 8, http.StatusBadRequest, "balance modification transaction cannot change account id")
|
||||
ErrBalanceModificationTransactionCannotAddWhenNotEmpty = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 9, http.StatusBadRequest, "balance modification transaction cannot add when other transaction exists")
|
||||
ErrCannotAddTransactionToHiddenAccount = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 10, http.StatusBadRequest, "cannot add transaction to hidden account")
|
||||
ErrCannotModifyTransactionInHiddenAccount = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 11, http.StatusBadRequest, "cannot modify transaction of hidden account")
|
||||
ErrCannotDeleteTransactionInHiddenAccount = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 12, http.StatusBadRequest, "cannot delete transaction in hidden account")
|
||||
ErrTransactionIdInvalid = NewNormalError(NormalSubcategoryTransaction, 0, http.StatusBadRequest, "transaction id is invalid")
|
||||
ErrTransactionNotFound = NewNormalError(NormalSubcategoryTransaction, 1, http.StatusBadRequest, "transaction not found")
|
||||
ErrTransactionTypeInvalid = NewNormalError(NormalSubcategoryTransaction, 2, http.StatusBadRequest, "transaction type is invalid")
|
||||
ErrTransactionSourceAndDestinationIdNotEqual = NewNormalError(NormalSubcategoryTransaction, 3, http.StatusBadRequest, "transaction source and destination account id not equal")
|
||||
ErrTransactionSourceAndDestinationIdCannotBeEqual = NewNormalError(NormalSubcategoryTransaction, 4, http.StatusBadRequest, "transaction source and destination account id cannot be equal")
|
||||
ErrTransactionSourceAndDestinationAmountNotEqual = NewNormalError(NormalSubcategoryTransaction, 5, http.StatusBadRequest, "transaction source and destination amount not equal")
|
||||
ErrTooMuchTransactionInOneSecond = NewNormalError(NormalSubcategoryTransaction, 6, http.StatusBadRequest, "too much transaction in one second")
|
||||
ErrBalanceModificationTransactionCannotSetCategory = NewNormalError(NormalSubcategoryTransaction, 7, http.StatusBadRequest, "balance modification transaction cannot set category")
|
||||
ErrBalanceModificationTransactionCannotChangeAccountId = NewNormalError(NormalSubcategoryTransaction, 8, http.StatusBadRequest, "balance modification transaction cannot change account id")
|
||||
ErrBalanceModificationTransactionCannotAddWhenNotEmpty = NewNormalError(NormalSubcategoryTransaction, 9, http.StatusBadRequest, "balance modification transaction cannot add when other transaction exists")
|
||||
ErrCannotAddTransactionToHiddenAccount = NewNormalError(NormalSubcategoryTransaction, 10, http.StatusBadRequest, "cannot add transaction to hidden account")
|
||||
ErrCannotModifyTransactionInHiddenAccount = NewNormalError(NormalSubcategoryTransaction, 11, http.StatusBadRequest, "cannot modify transaction of hidden account")
|
||||
ErrCannotDeleteTransactionInHiddenAccount = NewNormalError(NormalSubcategoryTransaction, 12, http.StatusBadRequest, "cannot delete transaction in hidden account")
|
||||
)
|
||||
|
||||
@@ -4,11 +4,11 @@ import "net/http"
|
||||
|
||||
// Error codes related to transaction categories
|
||||
var (
|
||||
ErrTransactionCategoryIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 0, http.StatusBadRequest, "transaction category id is invalid")
|
||||
ErrTransactionCategoryNotFound = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 1, http.StatusBadRequest, "transaction category not found")
|
||||
ErrTransactionCategoryTypeInvalid = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 2, http.StatusBadRequest, "transaction category type is invalid")
|
||||
ErrParentTransactionCategoryNotFound = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 3, http.StatusBadRequest, "parent transaction category not found")
|
||||
ErrCannotAddToSecondaryTransactionCategory = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 4, http.StatusBadRequest, "cannot add to secondary transaction category")
|
||||
ErrCannotUsePrimaryCategoryForTransaction = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 5, http.StatusBadRequest, "cannot use primary category for transaction category")
|
||||
ErrTransactionCategoryInUseCannotBeDeleted = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 6, http.StatusBadRequest, "transaction category is in use and cannot be deleted")
|
||||
ErrTransactionCategoryIdInvalid = NewNormalError(NormalSubcategoryCategory, 0, http.StatusBadRequest, "transaction category id is invalid")
|
||||
ErrTransactionCategoryNotFound = NewNormalError(NormalSubcategoryCategory, 1, http.StatusBadRequest, "transaction category not found")
|
||||
ErrTransactionCategoryTypeInvalid = NewNormalError(NormalSubcategoryCategory, 2, http.StatusBadRequest, "transaction category type is invalid")
|
||||
ErrParentTransactionCategoryNotFound = NewNormalError(NormalSubcategoryCategory, 3, http.StatusBadRequest, "parent transaction category not found")
|
||||
ErrCannotAddToSecondaryTransactionCategory = NewNormalError(NormalSubcategoryCategory, 4, http.StatusBadRequest, "cannot add to secondary transaction category")
|
||||
ErrCannotUsePrimaryCategoryForTransaction = NewNormalError(NormalSubcategoryCategory, 5, http.StatusBadRequest, "cannot use primary category for transaction category")
|
||||
ErrTransactionCategoryInUseCannotBeDeleted = NewNormalError(NormalSubcategoryCategory, 6, http.StatusBadRequest, "transaction category is in use and cannot be deleted")
|
||||
)
|
||||
|
||||
@@ -4,9 +4,9 @@ import "net/http"
|
||||
|
||||
// Error codes related to transaction tags
|
||||
var (
|
||||
ErrTransactionTagIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_TAG, 0, http.StatusBadRequest, "transaction tag id is invalid")
|
||||
ErrTransactionTagNotFound = NewNormalError(NORMAL_SUBCATEGORY_TAG, 1, http.StatusBadRequest, "transaction tag not found")
|
||||
ErrTransactionTagNameIsEmpty = NewNormalError(NORMAL_SUBCATEGORY_TAG, 2, http.StatusBadRequest, "transaction tag name is empty")
|
||||
ErrTransactionTagNameAlreadyExists = NewNormalError(NORMAL_SUBCATEGORY_TAG, 3, http.StatusBadRequest, "transaction tag name already exists")
|
||||
ErrTransactionTagInUseCannotBeDeleted = NewNormalError(NORMAL_SUBCATEGORY_TAG, 4, http.StatusBadRequest, "transaction tag is in use and cannot be deleted")
|
||||
ErrTransactionTagIdInvalid = NewNormalError(NormalSubcategoryTag, 0, http.StatusBadRequest, "transaction tag id is invalid")
|
||||
ErrTransactionTagNotFound = NewNormalError(NormalSubcategoryTag, 1, http.StatusBadRequest, "transaction tag not found")
|
||||
ErrTransactionTagNameIsEmpty = NewNormalError(NormalSubcategoryTag, 2, http.StatusBadRequest, "transaction tag name is empty")
|
||||
ErrTransactionTagNameAlreadyExists = NewNormalError(NormalSubcategoryTag, 3, http.StatusBadRequest, "transaction tag name already exists")
|
||||
ErrTransactionTagInUseCannotBeDeleted = NewNormalError(NormalSubcategoryTag, 4, http.StatusBadRequest, "transaction tag is in use and cannot be deleted")
|
||||
)
|
||||
|
||||
@@ -4,9 +4,9 @@ import "net/http"
|
||||
|
||||
// Error codes related to two factor authorization
|
||||
var (
|
||||
ErrPasscodeInvalid = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 0, http.StatusUnauthorized, "passcode is invalid")
|
||||
ErrTwoFactorRecoveryCodeInvalid = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 1, http.StatusUnauthorized, "two factor backup code is invalid")
|
||||
ErrTwoFactorRecoveryCodeNotExist = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 2, http.StatusUnauthorized, "two factor backup code does not exist")
|
||||
ErrTwoFactorIsNotEnabled = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 3, http.StatusBadRequest, "two factor is not enabled")
|
||||
ErrTwoFactorAlreadyEnabled = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 4, http.StatusBadRequest, "two factor has already been enabled")
|
||||
ErrPasscodeInvalid = NewNormalError(NormalSubcategoryTwofactor, 0, http.StatusUnauthorized, "passcode is invalid")
|
||||
ErrTwoFactorRecoveryCodeInvalid = NewNormalError(NormalSubcategoryTwofactor, 1, http.StatusUnauthorized, "two factor backup code is invalid")
|
||||
ErrTwoFactorRecoveryCodeNotExist = NewNormalError(NormalSubcategoryTwofactor, 2, http.StatusUnauthorized, "two factor backup code does not exist")
|
||||
ErrTwoFactorIsNotEnabled = NewNormalError(NormalSubcategoryTwofactor, 3, http.StatusBadRequest, "two factor is not enabled")
|
||||
ErrTwoFactorAlreadyEnabled = NewNormalError(NormalSubcategoryTwofactor, 4, http.StatusBadRequest, "two factor has already been enabled")
|
||||
)
|
||||
|
||||
+11
-11
@@ -6,15 +6,15 @@ import (
|
||||
|
||||
// Error codes related to users
|
||||
var (
|
||||
ErrLoginNameInvalid = NewNormalError(NORMAL_SUBCATEGORY_USER, 0, http.StatusUnauthorized, "login name is invalid")
|
||||
ErrLoginNameOrPasswordInvalid = NewNormalError(NORMAL_SUBCATEGORY_USER, 1, http.StatusUnauthorized, "login name or password is invalid")
|
||||
ErrLoginNameOrPasswordWrong = NewNormalError(NORMAL_SUBCATEGORY_USER, 2, http.StatusUnauthorized, "login name or password is wrong")
|
||||
ErrUserIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_USER, 3, http.StatusBadRequest, "user id is invalid")
|
||||
ErrUsernameIsEmpty = NewNormalError(NORMAL_SUBCATEGORY_USER, 4, http.StatusBadRequest, "username is empty")
|
||||
ErrEmailIsEmpty = NewNormalError(NORMAL_SUBCATEGORY_USER, 5, http.StatusBadRequest, "email is empty")
|
||||
ErrPasswordIsEmpty = NewNormalError(NORMAL_SUBCATEGORY_USER, 6, http.StatusBadRequest, "password is empty")
|
||||
ErrUserNotFound = NewNormalError(NORMAL_SUBCATEGORY_USER, 7, http.StatusBadRequest, "user not found")
|
||||
ErrUserPasswordWrong = NewNormalError(NORMAL_SUBCATEGORY_USER, 8, http.StatusBadRequest, "password is wrong")
|
||||
ErrUsernameAlreadyExists = NewNormalError(NORMAL_SUBCATEGORY_USER, 9, http.StatusBadRequest, "username already exists")
|
||||
ErrUserEmailAlreadyExists = NewNormalError(NORMAL_SUBCATEGORY_USER, 10, http.StatusBadRequest, "email already exists")
|
||||
ErrLoginNameInvalid = NewNormalError(NormalSubcategoryUser, 0, http.StatusUnauthorized, "login name is invalid")
|
||||
ErrLoginNameOrPasswordInvalid = NewNormalError(NormalSubcategoryUser, 1, http.StatusUnauthorized, "login name or password is invalid")
|
||||
ErrLoginNameOrPasswordWrong = NewNormalError(NormalSubcategoryUser, 2, http.StatusUnauthorized, "login name or password is wrong")
|
||||
ErrUserIdInvalid = NewNormalError(NormalSubcategoryUser, 3, http.StatusBadRequest, "user id is invalid")
|
||||
ErrUsernameIsEmpty = NewNormalError(NormalSubcategoryUser, 4, http.StatusBadRequest, "username is empty")
|
||||
ErrEmailIsEmpty = NewNormalError(NormalSubcategoryUser, 5, http.StatusBadRequest, "email is empty")
|
||||
ErrPasswordIsEmpty = NewNormalError(NormalSubcategoryUser, 6, http.StatusBadRequest, "password is empty")
|
||||
ErrUserNotFound = NewNormalError(NormalSubcategoryUser, 7, http.StatusBadRequest, "user not found")
|
||||
ErrUserPasswordWrong = NewNormalError(NormalSubcategoryUser, 8, http.StatusBadRequest, "password is wrong")
|
||||
ErrUsernameAlreadyExists = NewNormalError(NormalSubcategoryUser, 9, http.StatusBadRequest, "username already exists")
|
||||
ErrUserEmailAlreadyExists = NewNormalError(NormalSubcategoryUser, 10, http.StatusBadRequest, "email already exists")
|
||||
)
|
||||
|
||||
@@ -41,13 +41,13 @@ func (f *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
|
||||
|
||||
b.WriteString(entry.Message)
|
||||
|
||||
if requestId, exists := entry.Data[LOG_FIELD_REQUEST_ID]; exists {
|
||||
if requestId, exists := entry.Data[logFieldRequestId]; exists {
|
||||
b.WriteString(fmt.Sprintf(", r=%s", requestId))
|
||||
}
|
||||
|
||||
b.WriteString("\n")
|
||||
|
||||
if extra, exists := entry.Data[LOG_FIELD_EXTRA]; exists {
|
||||
if extra, exists := entry.Data[logFieldExtra]; exists {
|
||||
b.WriteString(extra.(string))
|
||||
}
|
||||
|
||||
|
||||
+8
-8
@@ -12,8 +12,8 @@ import (
|
||||
"github.com/mayswind/lab/pkg/settings"
|
||||
)
|
||||
|
||||
const LOG_FIELD_REQUEST_ID = "REQUEST_ID"
|
||||
const LOG_FIELD_EXTRA = "EXTRA"
|
||||
const logFieldRequestId = "REQUEST_ID"
|
||||
const logFieldExtra = "EXTRA"
|
||||
|
||||
var bootLogger = logrus.New()
|
||||
var defaultLogger = logrus.New()
|
||||
@@ -97,7 +97,7 @@ func Debugf(format string, args ...interface{}) {
|
||||
}
|
||||
|
||||
func DebugfWithRequestId(c *core.Context, format string, args ...interface{}) {
|
||||
defaultLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).Debugf(getFinalLog(format, args...))
|
||||
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Debugf(getFinalLog(format, args...))
|
||||
}
|
||||
|
||||
func Infof(format string, args ...interface{}) {
|
||||
@@ -105,7 +105,7 @@ func Infof(format string, args ...interface{}) {
|
||||
}
|
||||
|
||||
func InfofWithRequestId(c *core.Context, format string, args ...interface{}) {
|
||||
defaultLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).Infof(getFinalLog(format, args...))
|
||||
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Infof(getFinalLog(format, args...))
|
||||
}
|
||||
|
||||
func Warnf(format string, args ...interface{}) {
|
||||
@@ -113,7 +113,7 @@ func Warnf(format string, args ...interface{}) {
|
||||
}
|
||||
|
||||
func WarnfWithRequestId(c *core.Context, format string, args ...interface{}) {
|
||||
defaultLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).Warnf(getFinalLog(format, args...))
|
||||
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Warnf(getFinalLog(format, args...))
|
||||
}
|
||||
|
||||
func Errorf(format string, args ...interface{}) {
|
||||
@@ -121,11 +121,11 @@ func Errorf(format string, args ...interface{}) {
|
||||
}
|
||||
|
||||
func ErrorfWithRequestId(c *core.Context, format string, args ...interface{}) {
|
||||
defaultLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).Errorf(getFinalLog(format, args...))
|
||||
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Errorf(getFinalLog(format, args...))
|
||||
}
|
||||
|
||||
func ErrorfWithRequestIdAndExtra(c *core.Context, extraString string, format string, args ...interface{}) {
|
||||
defaultLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).WithField(LOG_FIELD_EXTRA, extraString).Errorf(getFinalLog(format, args...))
|
||||
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).WithField(logFieldExtra, extraString).Errorf(getFinalLog(format, args...))
|
||||
}
|
||||
|
||||
func BootInfof(format string, args ...interface{}) {
|
||||
@@ -148,7 +148,7 @@ func BootErrorf(format string, args ...interface{}) {
|
||||
|
||||
func Requestf(c *core.Context, format string, args ...interface{}) {
|
||||
if requestLogger != nil {
|
||||
requestLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).Infof(getFinalLog(format, args...))
|
||||
requestLogger.WithField(logFieldRequestId, c.GetRequestId()).Infof(getFinalLog(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"github.com/mayswind/lab/pkg/settings"
|
||||
)
|
||||
|
||||
const REQUEST_ID_HEADER = "X-Request-ID"
|
||||
const requestIdHeader = "X-Request-ID"
|
||||
|
||||
func RequestId(config *settings.Config) core.MiddlewareHandlerFunc {
|
||||
return func(c *core.Context) {
|
||||
@@ -19,7 +19,7 @@ func RequestId(config *settings.Config) core.MiddlewareHandlerFunc {
|
||||
c.SetRequestId(requestId)
|
||||
|
||||
if config.EnableRequestIdHeader {
|
||||
c.Header(REQUEST_ID_HEADER, requestId)
|
||||
c.Header(requestIdHeader, requestId)
|
||||
}
|
||||
|
||||
c.Next()
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"github.com/mayswind/lab/pkg/settings"
|
||||
)
|
||||
|
||||
const SETTINGS_COOKIE_NAME = "ACP_SETTINGS"
|
||||
const settingsCookieName = "ACP_SETTINGS"
|
||||
|
||||
func ServerSettingsCookie(config *settings.Config) core.MiddlewareHandlerFunc {
|
||||
return func(c *core.Context) {
|
||||
@@ -17,7 +17,7 @@ func ServerSettingsCookie(config *settings.Config) core.MiddlewareHandlerFunc {
|
||||
}
|
||||
|
||||
bundledSettings := strings.Join(settingsArr, "_")
|
||||
c.SetCookie(SETTINGS_COOKIE_NAME, bundledSettings, config.TokenExpiredTime, "", "", false, false)
|
||||
c.SetCookie(settingsCookieName, bundledSettings, config.TokenExpiredTime, "", "", false, false)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package models
|
||||
|
||||
// Level-One Account
|
||||
const ACCOUNT_PARENT_ID_LEVEL_ONE = 0
|
||||
// LevelOneAccountParentId represents the parent id of level-one account
|
||||
const LevelOneAccountParentId = 0
|
||||
|
||||
// AccountCategory represents account category
|
||||
type AccountCategory byte
|
||||
|
||||
@@ -2,8 +2,8 @@ package models
|
||||
|
||||
import "github.com/mayswind/lab/pkg/core"
|
||||
|
||||
// The maximum size of user agent stored in database
|
||||
const TOKEN_USER_AGENT_MAX_LENGTH = 255
|
||||
// TokenMaxUserAgentLength represents the maximum size of user agent stored in database
|
||||
const TokenMaxUserAgentLength = 255
|
||||
|
||||
// TokenRecord represents token data stored in database
|
||||
type TokenRecord struct {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package models
|
||||
|
||||
// Level-One Transaction Category
|
||||
const TRANSACTION_PARENT_ID_LEVEL_ONE = 0
|
||||
// LevelOneTransactionParentId represents the parent id of level-one transaction category
|
||||
const LevelOneTransactionParentId = 0
|
||||
|
||||
// TransactionCategoryType represents transaction category type
|
||||
type TransactionCategoryType byte
|
||||
|
||||
@@ -19,15 +19,15 @@ import (
|
||||
|
||||
// Length and mask of all information in request id
|
||||
const (
|
||||
REQUEST_ID_LENGTH = 36
|
||||
SECONDS_TODAY_BITS = 17
|
||||
SECONDS_TODAY_BITS_MASK = (1 << SECONDS_TODAY_BITS) - 1
|
||||
RANDOM_NUMBER_BITS = 15
|
||||
RANDOM_NUMBER_BITS_MASK = (1 << RANDOM_NUMBER_BITS) - 1
|
||||
REQ_SEQ_NUMBER_BITS = 31
|
||||
REQ_SEQ_NUMBER_BITS_MASK = (1 << REQ_SEQ_NUMBER_BITS) - 1
|
||||
CLIENT_IPV6_BIT = 1
|
||||
CLIENT_IPV6_BIT_MASK = 1
|
||||
requestIdLength = 36
|
||||
secondsTodayBits = 17
|
||||
secondsTodayBitsMask = (1 << secondsTodayBits) - 1
|
||||
randomNumberBits = 15
|
||||
randomNumberBitsMask = (1 << randomNumberBits) - 1
|
||||
reqSeqNumberBits = 31
|
||||
reqSeqNumberBitsMask = (1 << reqSeqNumberBits) - 1
|
||||
clientIpv6Bit = 1
|
||||
clientIpv6BitMask = 1
|
||||
)
|
||||
|
||||
// RequestIdInfo represents a struct which has all information in request id
|
||||
@@ -102,7 +102,7 @@ func getInstanceUniqId(config *settings.Config) uint16 {
|
||||
|
||||
// ParseRequestIdInfo returns a info struct which contains all information in request id
|
||||
func (r *DefaultRequestIdGenerator) ParseRequestIdInfo(requestId string) (*RequestIdInfo, error) {
|
||||
if requestId == "" || len(requestId) != REQUEST_ID_LENGTH {
|
||||
if requestId == "" || len(requestId) != requestIdLength {
|
||||
return nil, errs.ErrRequestIdInvalid
|
||||
}
|
||||
|
||||
@@ -147,17 +147,17 @@ func (r *DefaultRequestIdGenerator) getRequestId(serverUniqId uint16, instanceUn
|
||||
// 128bits = serverUniqId(16bits) + instanceUniqId(16bits) + secondsElapsedToday(17bits) + randomNumber(15bits) + sequentialNumber(31bits) + clientIpv6Flag(1bit) + clientIp(32bits)
|
||||
|
||||
secondsElapsedToday := r.getSecondsElapsedToday()
|
||||
secondsLow17bits := uint32(secondsElapsedToday & SECONDS_TODAY_BITS_MASK)
|
||||
secondsLow17bits := uint32(secondsElapsedToday & secondsTodayBitsMask)
|
||||
|
||||
randomNumber, _ := utils.GetRandomInteger(math.MaxInt16)
|
||||
randomNumberLow15bits := uint32(randomNumber & RANDOM_NUMBER_BITS_MASK)
|
||||
randomNumberLow15bits := uint32(randomNumber & randomNumberBitsMask)
|
||||
|
||||
secondsAndRandomNumber := (secondsLow17bits << RANDOM_NUMBER_BITS) | randomNumberLow15bits
|
||||
secondsAndRandomNumber := (secondsLow17bits << randomNumberBits) | randomNumberLow15bits
|
||||
|
||||
seqId := atomic.AddUint32(&r.requestSeqId, 1)
|
||||
seqIdLow31bits := seqId & REQ_SEQ_NUMBER_BITS_MASK
|
||||
seqIdLow31bits := seqId & reqSeqNumberBitsMask
|
||||
|
||||
seqIdAndClientIpv6Flag := (seqIdLow31bits << CLIENT_IPV6_BIT) | (clientIpv6Flag & CLIENT_IPV6_BIT_MASK)
|
||||
seqIdAndClientIpv6Flag := (seqIdLow31bits << clientIpv6Bit) | (clientIpv6Flag & clientIpv6BitMask)
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
_ = binary.Write(buf, binary.BigEndian, serverUniqId)
|
||||
@@ -208,11 +208,11 @@ func (r *DefaultRequestIdGenerator) parseRequestIdInfo(data []byte) *RequestIdIn
|
||||
_ = binary.Read(buf, binary.BigEndian, &seqIdAndClientIpv6Flag)
|
||||
_ = binary.Read(buf, binary.BigEndian, &clientIp)
|
||||
|
||||
secondsElapsedToday := (secondsAndRandomNumber >> RANDOM_NUMBER_BITS) & SECONDS_TODAY_BITS_MASK
|
||||
randomNumber := (secondsAndRandomNumber & RANDOM_NUMBER_BITS_MASK)
|
||||
secondsElapsedToday := (secondsAndRandomNumber >> randomNumberBits) & secondsTodayBitsMask
|
||||
randomNumber := (secondsAndRandomNumber & randomNumberBitsMask)
|
||||
|
||||
seqId := (seqIdAndClientIpv6Flag >> CLIENT_IPV6_BIT) & REQ_SEQ_NUMBER_BITS_MASK
|
||||
isClientIpv6Flag := (seqIdAndClientIpv6Flag & CLIENT_IPV6_BIT_MASK)
|
||||
seqId := (seqIdAndClientIpv6Flag >> clientIpv6Bit) & reqSeqNumberBitsMask
|
||||
isClientIpv6Flag := (seqIdAndClientIpv6Flag & clientIpv6BitMask)
|
||||
isClientIpv6 := false
|
||||
|
||||
if isClientIpv6Flag == 1 {
|
||||
|
||||
@@ -60,7 +60,7 @@ func (s *AccountService) GetMaxDisplayOrder(uid int64, category models.AccountCa
|
||||
}
|
||||
|
||||
account := &models.Account{}
|
||||
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_account_id", "display_order").Where("uid=? AND deleted=? AND parent_account_id=? AND category=?", uid, false, models.ACCOUNT_PARENT_ID_LEVEL_ONE, category).OrderBy("display_order desc").Limit(1).Get(account)
|
||||
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_account_id", "display_order").Where("uid=? AND deleted=? AND parent_account_id=? AND category=?", uid, false, models.LevelOneAccountParentId, category).OrderBy("display_order desc").Limit(1).Get(account)
|
||||
|
||||
if err != nil {
|
||||
return 0, err
|
||||
|
||||
@@ -314,8 +314,8 @@ func (s *TokenService) getUserAgent(ctx *core.Context) string {
|
||||
userAgent = ctx.Request.UserAgent()
|
||||
}
|
||||
|
||||
if len(userAgent) > models.TOKEN_USER_AGENT_MAX_LENGTH {
|
||||
userAgent = utils.SubString(userAgent, 0, models.TOKEN_USER_AGENT_MAX_LENGTH)
|
||||
if len(userAgent) > models.TokenMaxUserAgentLength {
|
||||
userAgent = utils.SubString(userAgent, 0, models.TokenMaxUserAgentLength)
|
||||
}
|
||||
|
||||
return userAgent
|
||||
|
||||
@@ -80,7 +80,7 @@ func (s *TransactionCategoryService) GetMaxDisplayOrder(uid int64, categoryType
|
||||
}
|
||||
|
||||
category := &models.TransactionCategory{}
|
||||
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_category_id", "display_order").Where("uid=? AND deleted=? AND type=? AND parent_category_id=?", uid, false, categoryType, models.TRANSACTION_PARENT_ID_LEVEL_ONE).OrderBy("display_order desc").Limit(1).Get(category)
|
||||
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_category_id", "display_order").Where("uid=? AND deleted=? AND type=? AND parent_category_id=?", uid, false, categoryType, models.LevelOneTransactionParentId).OrderBy("display_order desc").Limit(1).Get(category)
|
||||
|
||||
if err != nil {
|
||||
return 0, err
|
||||
|
||||
@@ -16,10 +16,10 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
TWOFACTOR_PERIOD uint = 30 // seconds
|
||||
TWOFACTOR_SECRET_SIZE uint = 20 // bytes
|
||||
TWOFACTOR_RECOVERY_CODE_COUNT int = 10
|
||||
TWOFACTOR_RECOVERY_CODE_LENGTH int = 10 // bytes
|
||||
twoFactorPeriod uint = 30 // seconds
|
||||
twoFactorSecretSize uint = 20 // bytes
|
||||
twoFactorRecoveryCodeCount int = 10
|
||||
twoFactorRecoveryCodeLength int = 10 // bytes
|
||||
)
|
||||
|
||||
type TwoFactorAuthorizationService struct {
|
||||
@@ -73,8 +73,8 @@ func (s *TwoFactorAuthorizationService) GenerateTwoFactorSecret(user *models.Use
|
||||
key, err := totp.Generate(totp.GenerateOpts{
|
||||
Issuer: s.CurrentConfig().AppName,
|
||||
AccountName: user.Username,
|
||||
Period: TWOFACTOR_PERIOD,
|
||||
SecretSize: TWOFACTOR_SECRET_SIZE,
|
||||
Period: twoFactorPeriod,
|
||||
SecretSize: twoFactorSecretSize,
|
||||
})
|
||||
|
||||
return key, err
|
||||
@@ -147,10 +147,10 @@ func (s *TwoFactorAuthorizationService) GetAndUseUserTwoFactorRecoveryCode(uid i
|
||||
}
|
||||
|
||||
func (s *TwoFactorAuthorizationService) GenerateTwoFactorRecoveryCodes() ([]string, error) {
|
||||
recoveryCodes := make([]string, TWOFACTOR_RECOVERY_CODE_COUNT)
|
||||
recoveryCodes := make([]string, twoFactorRecoveryCodeCount)
|
||||
|
||||
for i := 0; i < TWOFACTOR_RECOVERY_CODE_COUNT; i++ {
|
||||
recoveryCode, err := utils.GetRandomNumberOrLetter(TWOFACTOR_RECOVERY_CODE_LENGTH)
|
||||
for i := 0; i < twoFactorRecoveryCodeCount; i++ {
|
||||
recoveryCode, err := utils.GetRandomNumberOrLetter(twoFactorRecoveryCodeLength)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
+47
-47
@@ -14,10 +14,10 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
LAB_WORK_DIR = "LAB_WORK_DIR"
|
||||
LAB_ENVIRONMENT_KEY_PREFIX = "LAB"
|
||||
DEFAULT_CONFIG_PATH = "/conf/lab.ini"
|
||||
DEFAULT_STATIC_ROOT_PATH = "public"
|
||||
labWorkDirEnvName = "LAB_WORK_DIR"
|
||||
labEnvNamePrefix = "LAB"
|
||||
defaultConfigPath = "/conf/lab.ini"
|
||||
defaultStaticRootPath = "public"
|
||||
)
|
||||
|
||||
type SystemMode string
|
||||
@@ -45,34 +45,34 @@ const (
|
||||
)
|
||||
|
||||
const (
|
||||
DBTYPE_MYSQL string = "mysql"
|
||||
DBTYPE_POSTGRES string = "postgres"
|
||||
DBTYPE_SQLITE3 string = "sqlite3"
|
||||
MySqlDbType string = "mysql"
|
||||
PostgresDbType string = "postgres"
|
||||
Sqlite3DbType string = "sqlite3"
|
||||
)
|
||||
|
||||
const (
|
||||
UUID_GENERATOR_TYPE_INTERNAL string = "internal"
|
||||
InternalUuidGeneratorType string = "internal"
|
||||
)
|
||||
|
||||
const (
|
||||
DEFAULT_APP_NAME string = "lab"
|
||||
defaultAppName string = "lab"
|
||||
|
||||
DEFAULT_HTTP_ADDR string = "0.0.0.0"
|
||||
DEFAULT_HTTP_PORT int = 8080
|
||||
DEFAULT_DOMAIN string = "localhost"
|
||||
defaultHttpAddr string = "0.0.0.0"
|
||||
defaultHttpPort int = 8080
|
||||
defaultDomain string = "localhost"
|
||||
|
||||
DEFAULT_DATABASE_HOST string = "127.0.0.1:3306"
|
||||
DEFAULT_DATABASE_NAME string = "lab"
|
||||
DEFAULT_DATABASE_MAX_IDLE_CONN int = 2
|
||||
DEFAULT_DATABASE_MAX_OPEN_CONN int = 0
|
||||
DEFAULT_DATABASE_CONN_MAX_LIFETIME int = 14400
|
||||
defaultDatabaseHost string = "127.0.0.1:3306"
|
||||
defaultDatabaseName string = "lab"
|
||||
defaultDatabaseMaxIdleConn int = 2
|
||||
defaultDatabaseMaxOpenConn int = 0
|
||||
defaultDatabaseConnMaxLifetime int = 14400
|
||||
|
||||
DEFAULT_LOG_MODE string = "console"
|
||||
DEFAULT_LOG_LEVEL Level = LOGLEVEL_INFO
|
||||
defaultLogMode string = "console"
|
||||
defaultLoglevel Level = LOGLEVEL_INFO
|
||||
|
||||
DEFAULT_SECRET_KEY string = "lab"
|
||||
DEFAULT_TOKEN_EXPIRED_TIME int = 604800 // 7 days
|
||||
DEFAULT_TEMPORARY_TOKEN_EXPIRED_TIME int = 300 // 5 minutes
|
||||
defaultSecretKey string = "lab"
|
||||
defaultTokenExpiredTime int = 604800 // 7 days
|
||||
defaultTemporaryTokenExpiredTime int = 300 // 5 minutes
|
||||
)
|
||||
|
||||
type DatabaseConfig struct {
|
||||
@@ -213,7 +213,7 @@ func GetDefaultConfigFilePath() (string, error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
cfgFilePath := filepath.Join(workingPath, DEFAULT_CONFIG_PATH)
|
||||
cfgFilePath := filepath.Join(workingPath, defaultConfigPath)
|
||||
_, err = os.Stat(cfgFilePath)
|
||||
|
||||
if err != nil {
|
||||
@@ -224,7 +224,7 @@ func GetDefaultConfigFilePath() (string, error) {
|
||||
}
|
||||
|
||||
func loadGlobalConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
||||
config.AppName = getConfigItemStringValue(configFile, sectionName, "app_name", DEFAULT_APP_NAME)
|
||||
config.AppName = getConfigItemStringValue(configFile, sectionName, "app_name", defaultAppName)
|
||||
config.Mode = MODE_PRODUCTION
|
||||
|
||||
if getConfigItemStringValue(configFile, sectionName, "mode") == "development" {
|
||||
@@ -238,13 +238,13 @@ func loadServerConfiguration(config *Config, configFile *ini.File, sectionName s
|
||||
if getConfigItemStringValue(configFile, sectionName, "protocol") == "http" {
|
||||
config.Protocol = SCHEME_HTTP
|
||||
|
||||
config.HttpAddr = getConfigItemStringValue(configFile, sectionName, "http_addr", DEFAULT_HTTP_ADDR)
|
||||
config.HttpPort = getConfigItemIntValue(configFile, sectionName, "http_port", DEFAULT_HTTP_PORT)
|
||||
config.HttpAddr = getConfigItemStringValue(configFile, sectionName, "http_addr", defaultHttpAddr)
|
||||
config.HttpPort = getConfigItemIntValue(configFile, sectionName, "http_port", defaultHttpPort)
|
||||
} else if getConfigItemStringValue(configFile, sectionName, "protocol") == "https" {
|
||||
config.Protocol = SCHEME_HTTPS
|
||||
|
||||
config.HttpAddr = getConfigItemStringValue(configFile, sectionName, "http_addr", DEFAULT_HTTP_ADDR)
|
||||
config.HttpPort = getConfigItemIntValue(configFile, sectionName, "http_port", DEFAULT_HTTP_PORT)
|
||||
config.HttpAddr = getConfigItemStringValue(configFile, sectionName, "http_addr", defaultHttpAddr)
|
||||
config.HttpPort = getConfigItemIntValue(configFile, sectionName, "http_port", defaultHttpPort)
|
||||
|
||||
config.CertFile = getConfigItemStringValue(configFile, sectionName, "cert_file")
|
||||
config.CertKeyFile = getConfigItemStringValue(configFile, sectionName, "cert_key_file")
|
||||
@@ -256,14 +256,14 @@ func loadServerConfiguration(config *Config, configFile *ini.File, sectionName s
|
||||
return errs.ErrInvalidProtocol
|
||||
}
|
||||
|
||||
config.Domain = getConfigItemStringValue(configFile, sectionName, "domain", DEFAULT_DOMAIN)
|
||||
config.Domain = getConfigItemStringValue(configFile, sectionName, "domain", defaultDomain)
|
||||
config.RootUrl = getConfigItemStringValue(configFile, sectionName, "root_url", fmt.Sprintf("%s://%s:%d/", string(config.Protocol), config.Domain, config.HttpPort))
|
||||
|
||||
if config.RootUrl[len(config.RootUrl)-1] != '/' {
|
||||
config.RootUrl += "/"
|
||||
}
|
||||
|
||||
staticRootPath := getConfigItemStringValue(configFile, sectionName, "static_root_path", DEFAULT_STATIC_ROOT_PATH)
|
||||
staticRootPath := getConfigItemStringValue(configFile, sectionName, "static_root_path", defaultStaticRootPath)
|
||||
finalStaticRootPath, err := getFinalPath(config.WorkingPath, staticRootPath)
|
||||
|
||||
if err != nil {
|
||||
@@ -281,25 +281,25 @@ func loadServerConfiguration(config *Config, configFile *ini.File, sectionName s
|
||||
func loadDatabaseConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
||||
dbConfig := &DatabaseConfig{}
|
||||
|
||||
dbConfig.DatabaseType = getConfigItemStringValue(configFile, sectionName, "type", DBTYPE_MYSQL)
|
||||
dbConfig.DatabaseHost = getConfigItemStringValue(configFile, sectionName, "host", DEFAULT_DATABASE_HOST)
|
||||
dbConfig.DatabaseName = getConfigItemStringValue(configFile, sectionName, "name", DEFAULT_DATABASE_NAME)
|
||||
dbConfig.DatabaseType = getConfigItemStringValue(configFile, sectionName, "type", MySqlDbType)
|
||||
dbConfig.DatabaseHost = getConfigItemStringValue(configFile, sectionName, "host", defaultDatabaseHost)
|
||||
dbConfig.DatabaseName = getConfigItemStringValue(configFile, sectionName, "name", defaultDatabaseName)
|
||||
dbConfig.DatabaseUser = getConfigItemStringValue(configFile, sectionName, "user")
|
||||
dbConfig.DatabasePassword = getConfigItemStringValue(configFile, sectionName, "passwd")
|
||||
|
||||
if dbConfig.DatabaseType == DBTYPE_POSTGRES {
|
||||
if dbConfig.DatabaseType == PostgresDbType {
|
||||
dbConfig.DatabaseSSLMode = getConfigItemStringValue(configFile, sectionName, "ssl_mode")
|
||||
}
|
||||
|
||||
if dbConfig.DatabaseType == DBTYPE_SQLITE3 {
|
||||
if dbConfig.DatabaseType == Sqlite3DbType {
|
||||
staticDBPath := getConfigItemStringValue(configFile, sectionName, "db_path")
|
||||
finalStaticDBPath, _ := getFinalPath(config.WorkingPath, staticDBPath)
|
||||
dbConfig.DatabasePath = finalStaticDBPath
|
||||
}
|
||||
|
||||
dbConfig.MaxIdleConnection = getConfigItemIntValue(configFile, sectionName, "max_idle_conn", DEFAULT_DATABASE_MAX_IDLE_CONN)
|
||||
dbConfig.MaxOpenConnection = getConfigItemIntValue(configFile, sectionName, "max_open_conn", DEFAULT_DATABASE_MAX_OPEN_CONN)
|
||||
dbConfig.ConnectionMaxLifeTime = getConfigItemIntValue(configFile, sectionName, "conn_max_lifetime", DEFAULT_DATABASE_CONN_MAX_LIFETIME)
|
||||
dbConfig.MaxIdleConnection = getConfigItemIntValue(configFile, sectionName, "max_idle_conn", defaultDatabaseMaxIdleConn)
|
||||
dbConfig.MaxOpenConnection = getConfigItemIntValue(configFile, sectionName, "max_open_conn", defaultDatabaseMaxOpenConn)
|
||||
dbConfig.ConnectionMaxLifeTime = getConfigItemIntValue(configFile, sectionName, "conn_max_lifetime", defaultDatabaseConnMaxLifetime)
|
||||
|
||||
config.DatabaseConfig = dbConfig
|
||||
config.EnableQueryLog = getConfigItemBoolValue(configFile, sectionName, "log_query", false)
|
||||
@@ -309,7 +309,7 @@ func loadDatabaseConfiguration(config *Config, configFile *ini.File, sectionName
|
||||
}
|
||||
|
||||
func loadLogConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
||||
config.LogModes = strings.Split(getConfigItemStringValue(configFile, sectionName, "mode", DEFAULT_LOG_MODE), " ")
|
||||
config.LogModes = strings.Split(getConfigItemStringValue(configFile, sectionName, "mode", defaultLogMode), " ")
|
||||
|
||||
for i := 0; i < len(config.LogModes); i++ {
|
||||
logMode := config.LogModes[i]
|
||||
@@ -323,7 +323,7 @@ func loadLogConfiguration(config *Config, configFile *ini.File, sectionName stri
|
||||
}
|
||||
}
|
||||
|
||||
config.LogLevel = getLogLevel(getConfigItemStringValue(configFile, sectionName, "level"), DEFAULT_LOG_LEVEL)
|
||||
config.LogLevel = getLogLevel(getConfigItemStringValue(configFile, sectionName, "level"), defaultLoglevel)
|
||||
|
||||
if config.EnableFileLog {
|
||||
config.FileLogPath = getConfigItemStringValue(configFile, sectionName, "log_path")
|
||||
@@ -333,8 +333,8 @@ func loadLogConfiguration(config *Config, configFile *ini.File, sectionName stri
|
||||
}
|
||||
|
||||
func loadUuidConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
||||
if getConfigItemStringValue(configFile, sectionName, "generator_type") == UUID_GENERATOR_TYPE_INTERNAL {
|
||||
config.UuidGeneratorType = UUID_GENERATOR_TYPE_INTERNAL
|
||||
if getConfigItemStringValue(configFile, sectionName, "generator_type") == InternalUuidGeneratorType {
|
||||
config.UuidGeneratorType = InternalUuidGeneratorType
|
||||
} else {
|
||||
return errs.ErrInvalidUuidMode
|
||||
}
|
||||
@@ -345,13 +345,13 @@ func loadUuidConfiguration(config *Config, configFile *ini.File, sectionName str
|
||||
}
|
||||
|
||||
func loadSecurityConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
||||
config.SecretKey = getConfigItemStringValue(configFile, sectionName, "secret_key", DEFAULT_SECRET_KEY)
|
||||
config.SecretKey = getConfigItemStringValue(configFile, sectionName, "secret_key", defaultSecretKey)
|
||||
config.EnableTwoFactor = getConfigItemBoolValue(configFile, sectionName, "enable_two_factor", true)
|
||||
|
||||
config.TokenExpiredTime = getConfigItemIntValue(configFile, sectionName, "token_expired_time", DEFAULT_TOKEN_EXPIRED_TIME)
|
||||
config.TokenExpiredTime = getConfigItemIntValue(configFile, sectionName, "token_expired_time", defaultTokenExpiredTime)
|
||||
config.TokenExpiredTimeDuration = time.Duration(config.TokenExpiredTime) * time.Second
|
||||
|
||||
config.TemporaryTokenExpiredTime = getConfigItemIntValue(configFile, sectionName, "temporary_token_expired_time", DEFAULT_TEMPORARY_TOKEN_EXPIRED_TIME)
|
||||
config.TemporaryTokenExpiredTime = getConfigItemIntValue(configFile, sectionName, "temporary_token_expired_time", defaultTemporaryTokenExpiredTime)
|
||||
config.TemporaryTokenExpiredTimeDuration = time.Duration(config.TemporaryTokenExpiredTime) * time.Second
|
||||
|
||||
config.EnableRequestIdHeader = getConfigItemBoolValue(configFile, sectionName, "request_id_header", true)
|
||||
@@ -366,7 +366,7 @@ func loadUserConfiguration(config *Config, configFile *ini.File, sectionName str
|
||||
}
|
||||
|
||||
func getWorkingPath() (string, error) {
|
||||
workingPath := os.Getenv(LAB_WORK_DIR)
|
||||
workingPath := os.Getenv(labWorkDirEnvName)
|
||||
|
||||
if workingPath != "" {
|
||||
return workingPath, nil
|
||||
@@ -445,7 +445,7 @@ func getConfigItemBoolValue(configFile *ini.File, sectionName string, itemName s
|
||||
}
|
||||
|
||||
func getEnvironmentKey(sectionName string, itemName string) string {
|
||||
return fmt.Sprintf("%s_%s_%s", LAB_ENVIRONMENT_KEY_PREFIX, strings.ToUpper(sectionName), strings.ToUpper(itemName))
|
||||
return fmt.Sprintf("%s_%s_%s", labEnvNamePrefix, strings.ToUpper(sectionName), strings.ToUpper(itemName))
|
||||
}
|
||||
|
||||
func getLogLevel(logLevelStr string, defaultLogLevel Level) Level {
|
||||
|
||||
@@ -16,10 +16,10 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
CHARACTERS = "!#$&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"
|
||||
NUMBER_AND_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
CHARACTERS_LENGTH = len(CHARACTERS)
|
||||
NUMBER_AND_LETTERS_LENGTH = len(NUMBER_AND_LETTERS)
|
||||
availableCharacters = "!#$&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"
|
||||
availableNumberAndLetters = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
availableCharactersLength = len(availableCharacters)
|
||||
availableNumberAndLettersLength = len(availableNumberAndLetters)
|
||||
)
|
||||
|
||||
// SubString returns part of the source string according to start index and length
|
||||
@@ -77,13 +77,13 @@ func GetRandomString(n int) (string, error) {
|
||||
var result = make([]byte, n)
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
index, err := GetRandomInteger(CHARACTERS_LENGTH)
|
||||
index, err := GetRandomInteger(availableCharactersLength)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
result[i] = CHARACTERS[index]
|
||||
result[i] = availableCharacters[index]
|
||||
}
|
||||
|
||||
return string(result), nil
|
||||
@@ -94,13 +94,13 @@ func GetRandomNumberOrLetter(n int) (string, error) {
|
||||
var result = make([]byte, n)
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
index, err := GetRandomInteger(NUMBER_AND_LETTERS_LENGTH)
|
||||
index, err := GetRandomInteger(availableNumberAndLettersLength)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
result[i] = NUMBER_AND_LETTERS[index]
|
||||
result[i] = availableNumberAndLetters[index]
|
||||
}
|
||||
|
||||
return string(result), nil
|
||||
|
||||
@@ -9,20 +9,20 @@ import (
|
||||
|
||||
// Length and mask of all information in uuid
|
||||
const (
|
||||
INTERNAL_UUID_UNIX_TIME_BITS = 32
|
||||
INTERNAL_UUID_UNIX_TIME_MASK = (1 << INTERNAL_UUID_UNIX_TIME_BITS) - 1
|
||||
internalUuidUnixTimeBits = 32
|
||||
internalUuidUnixTimeMask = (1 << internalUuidUnixTimeBits) - 1
|
||||
|
||||
INTERNAL_UUID_TYPE_BITS = 4
|
||||
INTERNAL_UUID_TYPE_MASK = (1 << INTERNAL_UUID_TYPE_BITS) - 1
|
||||
internalUuidTypeBits = 4
|
||||
internalUuidTypeMask = (1 << internalUuidTypeBits) - 1
|
||||
|
||||
INTERNAL_UUID_SERVER_ID_BITS = 8
|
||||
INTERNAL_UUID_SERVER_ID_MASK = (1 << INTERNAL_UUID_SERVER_ID_BITS) - 1
|
||||
internalUuidServerIdBits = 8
|
||||
internalUuidServerIdMask = (1 << internalUuidServerIdBits) - 1
|
||||
|
||||
INTERNAL_UUID_SEQ_ID_BITS = 19
|
||||
INTERNAL_UUID_SEQ_ID_MASK = (1 << INTERNAL_UUID_SEQ_ID_BITS) - 1
|
||||
internalUuidSeqIdBits = 19
|
||||
internalUuidSeqIdMask = (1 << internalUuidSeqIdBits) - 1
|
||||
|
||||
SEQ_NUMBER_ID_BITS = 32
|
||||
SEQ_NUMBER_ID_MASK = (1 << SEQ_NUMBER_ID_BITS) - 1
|
||||
seqNumberIdBits = 32
|
||||
seqNumberIdMask = (1 << seqNumberIdBits) - 1
|
||||
)
|
||||
|
||||
// InternalUuidInfo represents a struct which has all information in uuid
|
||||
@@ -36,7 +36,7 @@ type InternalUuidInfo struct {
|
||||
// InternalUuidGenerator represents internal bundled uuid generator
|
||||
type InternalUuidGenerator struct {
|
||||
uuidServerId uint8
|
||||
uuidSeqNumbers [1 << INTERNAL_UUID_TYPE_BITS]uint64
|
||||
uuidSeqNumbers [1 << internalUuidTypeBits]uint64
|
||||
}
|
||||
|
||||
// NewInternalUuidGenerator returns a new internal uuid generator
|
||||
@@ -60,24 +60,24 @@ func (u *InternalUuidGenerator) GenerateUuid(idType UuidType) int64 {
|
||||
unixTime = uint64(time.Now().Unix())
|
||||
newSeqId = atomic.AddUint64(&u.uuidSeqNumbers[uuidType], 1)
|
||||
|
||||
if newSeqId>>SEQ_NUMBER_ID_BITS == unixTime {
|
||||
if newSeqId>>seqNumberIdBits == unixTime {
|
||||
break
|
||||
}
|
||||
|
||||
currentSeqId := newSeqId
|
||||
newSeqId = unixTime << SEQ_NUMBER_ID_BITS
|
||||
newSeqId = unixTime << seqNumberIdBits
|
||||
|
||||
if atomic.CompareAndSwapUint64(&u.uuidSeqNumbers[uuidType], currentSeqId, newSeqId) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
seqId := newSeqId & SEQ_NUMBER_ID_MASK
|
||||
seqId := newSeqId & seqNumberIdMask
|
||||
|
||||
unixTimePart := (int64(unixTime) & INTERNAL_UUID_UNIX_TIME_MASK) << (INTERNAL_UUID_TYPE_BITS + INTERNAL_UUID_SERVER_ID_BITS + INTERNAL_UUID_SEQ_ID_BITS)
|
||||
uuidTypePart := (int64(uuidType) & INTERNAL_UUID_TYPE_MASK) << (INTERNAL_UUID_SERVER_ID_BITS + INTERNAL_UUID_SEQ_ID_BITS)
|
||||
uuidServerIdPart := (int64(u.uuidServerId) & INTERNAL_UUID_SERVER_ID_MASK) << INTERNAL_UUID_SEQ_ID_BITS
|
||||
seqIdPart := int64(seqId) & INTERNAL_UUID_SEQ_ID_MASK
|
||||
unixTimePart := (int64(unixTime) & internalUuidUnixTimeMask) << (internalUuidTypeBits + internalUuidServerIdBits + internalUuidSeqIdBits)
|
||||
uuidTypePart := (int64(uuidType) & internalUuidTypeMask) << (internalUuidServerIdBits + internalUuidSeqIdBits)
|
||||
uuidServerIdPart := (int64(u.uuidServerId) & internalUuidServerIdMask) << internalUuidSeqIdBits
|
||||
seqIdPart := int64(seqId) & internalUuidSeqIdMask
|
||||
|
||||
uuid := unixTimePart | uuidTypePart | uuidServerIdPart | seqIdPart
|
||||
|
||||
@@ -86,16 +86,16 @@ func (u *InternalUuidGenerator) GenerateUuid(idType UuidType) int64 {
|
||||
|
||||
// ParseUuidInfo returns a info struct which contains all information in uuid
|
||||
func (u *InternalUuidGenerator) ParseUuidInfo(uuid int64) *InternalUuidInfo {
|
||||
seqId := uint32(uuid & INTERNAL_UUID_SEQ_ID_MASK)
|
||||
uuid = uuid >> INTERNAL_UUID_SEQ_ID_BITS
|
||||
seqId := uint32(uuid & internalUuidSeqIdMask)
|
||||
uuid = uuid >> internalUuidSeqIdBits
|
||||
|
||||
uuidServerId := uint8(uuid & INTERNAL_UUID_SERVER_ID_MASK)
|
||||
uuid = uuid >> INTERNAL_UUID_SERVER_ID_BITS
|
||||
uuidServerId := uint8(uuid & internalUuidServerIdMask)
|
||||
uuid = uuid >> internalUuidServerIdBits
|
||||
|
||||
uuidType := uint8(uuid & INTERNAL_UUID_TYPE_MASK)
|
||||
uuid = uuid >> INTERNAL_UUID_TYPE_BITS
|
||||
uuidType := uint8(uuid & internalUuidTypeMask)
|
||||
uuid = uuid >> internalUuidTypeBits
|
||||
|
||||
unixTime := uint32(uuid & INTERNAL_UUID_UNIX_TIME_MASK)
|
||||
unixTime := uint32(uuid & internalUuidUnixTimeMask)
|
||||
|
||||
return &InternalUuidInfo{
|
||||
UnixTime: unixTime,
|
||||
|
||||
@@ -17,7 +17,7 @@ var (
|
||||
|
||||
// InitializeUuidGenerator initialized the current uuid generator according to the config
|
||||
func InitializeUuidGenerator(config *settings.Config) error {
|
||||
if config.UuidGeneratorType == settings.UUID_GENERATOR_TYPE_INTERNAL {
|
||||
if config.UuidGeneratorType == settings.InternalUuidGeneratorType {
|
||||
generator, err := NewInternalUuidGenerator(config)
|
||||
Container.Current = generator
|
||||
|
||||
|
||||
@@ -4,10 +4,11 @@ import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
const PARENT_ACCOUNT_CURRENCY_PLACEHODLER = "---"
|
||||
// ParentAccountCurrencyPlaceholder represents the currency field of parent account stored in database
|
||||
const ParentAccountCurrencyPlaceholder = "---"
|
||||
|
||||
// ISO 4217
|
||||
var ALL_CURRENCY_NAMES = map[string]bool{
|
||||
var allCurrencyNames = map[string]bool{
|
||||
"AED": true, //UAE Dirham
|
||||
"AFN": true, //Afghani
|
||||
"ALL": true, //Lek
|
||||
@@ -169,11 +170,11 @@ var ALL_CURRENCY_NAMES = map[string]bool{
|
||||
|
||||
func ValidCurrency(fl validator.FieldLevel) bool {
|
||||
if value, ok := fl.Field().Interface().(string); ok {
|
||||
if value == PARENT_ACCOUNT_CURRENCY_PLACEHODLER {
|
||||
if value == ParentAccountCurrencyPlaceholder {
|
||||
return true
|
||||
}
|
||||
|
||||
_, ok := ALL_CURRENCY_NAMES[value]
|
||||
_, ok := allCurrencyNames[value]
|
||||
return ok
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user