mirror of
https://github.com/mayswind/ezbookkeeping.git
synced 2026-05-18 16:54:25 +08:00
add core/error/util files
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
module github.com/mayswind/lab
|
||||
|
||||
go 1.14
|
||||
|
||||
require (
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible
|
||||
github.com/gin-gonic/gin v1.6.3
|
||||
github.com/go-playground/validator/v10 v10.2.0
|
||||
github.com/stretchr/testify v1.4.0
|
||||
github.com/urfave/cli v1.22.4
|
||||
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897
|
||||
)
|
||||
@@ -0,0 +1,66 @@
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgrijalva/jwt-go v1.0.2 h1:KPldsxuKGsS2FPWsNeg9ZO18aCrGKujPoWXn2yo+KQM=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
|
||||
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
|
||||
github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
|
||||
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
|
||||
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
|
||||
github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no=
|
||||
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
|
||||
github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY=
|
||||
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
|
||||
github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
|
||||
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
|
||||
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
|
||||
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
||||
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
|
||||
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
||||
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
|
||||
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
|
||||
github.com/urfave/cli v1.22.4 h1:u7tSpNPPswAFymm8IehJhy4uJMlUuU/GmqSkvJ1InXA=
|
||||
github.com/urfave/cli v1.22.4/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 h1:pLI5jrR7OSLijeIDcmRxNmw2api+jEfxLoykJVice/E=
|
||||
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
@@ -0,0 +1,82 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"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"
|
||||
|
||||
type Context struct {
|
||||
*gin.Context
|
||||
// DO NOT ADD ANY FIELD IN THIS CONTEXT, THIS CONTEXT IS JUST A WRAPPER
|
||||
}
|
||||
|
||||
func (c *Context) SetRequestId(requestId string) {
|
||||
c.Set(FIELD_REQUEST_ID_KEY, requestId)
|
||||
}
|
||||
|
||||
func (c *Context) GetRequestId() string {
|
||||
requestId, exists := c.Get(FIELD_REQUEST_ID_KEY)
|
||||
|
||||
if !exists {
|
||||
return ""
|
||||
}
|
||||
|
||||
return requestId.(string)
|
||||
}
|
||||
|
||||
func (c *Context) SetTokenClaims(claims *UserTokenClaims) {
|
||||
c.Set(FIELD_TOKEN_CLAIMS_KEY, claims)
|
||||
}
|
||||
|
||||
func (c *Context) GetTokenClaims() *UserTokenClaims {
|
||||
claims, exists := c.Get(FIELD_TOKEN_CLAIMS_KEY)
|
||||
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
return claims.(*UserTokenClaims)
|
||||
}
|
||||
|
||||
func (c *Context) GetCurrentUid() int64 {
|
||||
claims := c.GetTokenClaims()
|
||||
|
||||
if claims == nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
uid, err := strconv.ParseInt(claims.Id, 10, 64)
|
||||
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
return uid
|
||||
}
|
||||
|
||||
func (c *Context) SetResponseError(error *errs.Error) {
|
||||
c.Set(FIELD_RESPONSE_ERROR, error)
|
||||
}
|
||||
|
||||
func (c *Context) GetResponseError() *errs.Error {
|
||||
err, exists := c.Get(FIELD_RESPONSE_ERROR)
|
||||
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
return err.(*errs.Error)
|
||||
}
|
||||
|
||||
func WrapContext(ginCtx *gin.Context) *Context {
|
||||
return &Context{
|
||||
Context: ginCtx,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package core
|
||||
|
||||
import "github.com/mayswind/lab/pkg/errs"
|
||||
|
||||
type MiddlewareHandlerFunc func(*Context)
|
||||
|
||||
type ApiHandlerFunc func(*Context) (interface{}, *errs.Error)
|
||||
@@ -0,0 +1,19 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
type TokenType byte
|
||||
|
||||
const (
|
||||
USER_TOKEN_TYPE_NORMAL TokenType = 1
|
||||
USER_TOKEN_TYPE_REQUIRE_2FA TokenType = 2
|
||||
)
|
||||
|
||||
type UserTokenClaims struct {
|
||||
UserTokenId string `json:"userTokenId"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Type TokenType `json:"type"`
|
||||
jwt.StandardClaims
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package errs
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
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")
|
||||
)
|
||||
@@ -0,0 +1,73 @@
|
||||
package errs
|
||||
|
||||
type ErrorCategory int
|
||||
|
||||
const (
|
||||
CATEGORY_SYSTEM ErrorCategory = 1
|
||||
CATEGORY_NORMAL ErrorCategory = 2
|
||||
|
||||
SYSTEM_SUBCATEGORY_DEFAULT = 0
|
||||
SYSTEM_SUBCATEGORY_SETTING = 1
|
||||
SYSTEM_SUBCATEGORY_DATABASE = 2
|
||||
|
||||
NORMAL_SUBCATEGORY_GLOBAL = 0
|
||||
NORMAL_SUBCATEGORY_USER = 1
|
||||
NORMAL_SUBCATEGORY_TOKEN = 2
|
||||
NORMAL_SUBCATEGORY_TWOFACTOR = 3
|
||||
NORMAL_SUBCATEGORY_ACCOUNT = 4
|
||||
NORMAL_SUBCATEGORY_JOURNAL = 5
|
||||
NORMAL_SUBCATEGORY_CATEGORY = 6
|
||||
NORMAL_SUBCATEGORY_TAG = 7
|
||||
)
|
||||
|
||||
type Error struct {
|
||||
Category ErrorCategory
|
||||
SubCategory int
|
||||
Index int
|
||||
HttpStatusCode int
|
||||
Message string
|
||||
BaseError []error
|
||||
}
|
||||
|
||||
func (err *Error) Error() string {
|
||||
return err.Message
|
||||
}
|
||||
|
||||
func (err *Error) Code() int {
|
||||
return int(err.Category)*100000 + err.SubCategory*1000 + err.Index
|
||||
}
|
||||
|
||||
func New(category ErrorCategory, subCategory int, index int, httpStatusCode int, message string, baseError ...error) *Error {
|
||||
return &Error{
|
||||
Category: category,
|
||||
SubCategory: subCategory,
|
||||
Index: index,
|
||||
HttpStatusCode: httpStatusCode,
|
||||
Message: message,
|
||||
BaseError: baseError,
|
||||
}
|
||||
}
|
||||
|
||||
func NewSystemError(subCategory int, index int, httpStatusCode int, message string) *Error {
|
||||
return New(CATEGORY_SYSTEM, subCategory, index, httpStatusCode, message)
|
||||
}
|
||||
|
||||
func NewNormalError(subCategory int, index int, httpStatusCode int, message string) *Error {
|
||||
return New(CATEGORY_NORMAL, subCategory, index, httpStatusCode, message)
|
||||
}
|
||||
|
||||
func NewIncompleteOrIncorrectSubmissionError(err error) *Error {
|
||||
return New(ErrIncompleteOrIncorrectSubmission.Category,
|
||||
ErrIncompleteOrIncorrectSubmission.SubCategory,
|
||||
ErrIncompleteOrIncorrectSubmission.Index,
|
||||
ErrIncompleteOrIncorrectSubmission.HttpStatusCode,
|
||||
ErrIncompleteOrIncorrectSubmission.Message, err)
|
||||
}
|
||||
|
||||
func Or(err error, defaultErr *Error) *Error {
|
||||
if finalError, ok := err.(*Error); ok {
|
||||
return finalError
|
||||
} else {
|
||||
return defaultErr
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package errs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
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")
|
||||
)
|
||||
|
||||
func GetParameterInvalidMessage(field string) string {
|
||||
return fmt.Sprintf("parameter \"%s\" is invalid", field)
|
||||
}
|
||||
|
||||
func GetParameterIsRequiredMessage(field string) string {
|
||||
return fmt.Sprintf("parameter \"%s\" is required", field)
|
||||
}
|
||||
|
||||
func GetParameterMustLessThanMessage(field string, param string) string {
|
||||
return fmt.Sprintf("parameter \"%s\" must be less than %s", field, param)
|
||||
}
|
||||
|
||||
func GetParameterMustMoreThanMessage(field string, param string) string {
|
||||
return fmt.Sprintf("parameter \"%s\" must be more than %s", field, param)
|
||||
}
|
||||
|
||||
func GetParameterLengthNotEqualMessage(field string, param string) string {
|
||||
return fmt.Sprintf("parameter \"%s\" length is not equal to %s", field, param)
|
||||
}
|
||||
|
||||
func GetParameterNotBeBlankMessage(field string) string {
|
||||
return fmt.Sprintf("parameter \"%s\" cannot be blank", field)
|
||||
}
|
||||
|
||||
func GetParameterInvalidUsernameMessage(field string) string {
|
||||
return fmt.Sprintf("parameter \"%s\" is invalid username format", field)
|
||||
}
|
||||
|
||||
func GetParameterInvalidEmailMessage(field string) string {
|
||||
return fmt.Sprintf("parameter \"%s\" is invalid email format", field)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package errs
|
||||
|
||||
import "net/http"
|
||||
|
||||
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")
|
||||
)
|
||||
@@ -0,0 +1,9 @@
|
||||
package errs
|
||||
|
||||
import "net/http"
|
||||
|
||||
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")
|
||||
)
|
||||
@@ -0,0 +1,18 @@
|
||||
package errs
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrTokenGenerating = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 0, http.StatusInternalServerError, "failed to generate token")
|
||||
ErrUnauthorizedAccess = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 1, http.StatusUnauthorized, "unauthorized access")
|
||||
ErrTokenExpired = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 2, http.StatusUnauthorized, "token is expired")
|
||||
ErrInvalidToken = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 3, http.StatusUnauthorized, "token is invalid")
|
||||
ErrInvalidUserTokenId = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 4, http.StatusUnauthorized, "user token id is invalid")
|
||||
ErrInvalidTokenId = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 5, http.StatusUnauthorized, "token id is invalid")
|
||||
ErrTokenRecordNotFound = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 6, http.StatusUnauthorized, "token is not found")
|
||||
ErrInvalidTokenType = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 7, http.StatusUnauthorized, "token type is invalid")
|
||||
ErrTokenRequire2FA = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 8, http.StatusUnauthorized, "token requires two factor authorization")
|
||||
ErrTokenNotRequire2FA = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 9, http.StatusUnauthorized, "token does not require two factor authorization")
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
package errs
|
||||
|
||||
import "net/http"
|
||||
|
||||
var (
|
||||
ErrPasscodeInvalid = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 0, http.StatusUnauthorized, "passcode is invalid")
|
||||
ErrTwoFactorRecoveryCodeInvalid = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 1, http.StatusUnauthorized, "two factor recovery code is invalid")
|
||||
ErrTwoFactorKeyIsNotEnabled = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 2, http.StatusBadRequest, "two factor key is not enabled")
|
||||
ErrTwoFactorKeyAlreadyEnabled = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 3, http.StatusBadRequest, "two factor key has already been enabled")
|
||||
ErrTwoFactorRecoveryCodeNotExist = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 4, http.StatusUnauthorized, "two factor recovery code does not exist")
|
||||
)
|
||||
@@ -0,0 +1,18 @@
|
||||
package errs
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUserIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_USER, 0, http.StatusBadRequest, "user id is invalid")
|
||||
ErrUsernameIsEmpty = NewNormalError(NORMAL_SUBCATEGORY_USER, 1, http.StatusBadRequest, "username is empty")
|
||||
ErrEmailIsEmpty = NewNormalError(NORMAL_SUBCATEGORY_USER, 2, http.StatusBadRequest, "email is empty")
|
||||
ErrPasswordIsEmpty = NewNormalError(NORMAL_SUBCATEGORY_USER, 3, http.StatusBadRequest, "password is empty")
|
||||
ErrUserNotFound = NewNormalError(NORMAL_SUBCATEGORY_USER, 4, http.StatusBadRequest, "user not found")
|
||||
ErrUserPasswordWrong = NewNormalError(NORMAL_SUBCATEGORY_USER, 5, http.StatusBadRequest, "password is wrong")
|
||||
ErrUsernameAlreadyExists = NewNormalError(NORMAL_SUBCATEGORY_USER, 6, http.StatusBadRequest, "username already exists")
|
||||
ErrUserEmailAlreadyExists = NewNormalError(NORMAL_SUBCATEGORY_USER, 7, http.StatusBadRequest, "email already exists")
|
||||
ErrLoginNameOrPasswordInvalid = NewNormalError(NORMAL_SUBCATEGORY_USER, 8, http.StatusUnauthorized, "login name or password is invalid")
|
||||
ErrLoginNameOrPasswordWrong = NewNormalError(NORMAL_SUBCATEGORY_USER, 9, http.StatusUnauthorized, "login name or password is wrong")
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
|
||||
"github.com/mayswind/lab/pkg/core"
|
||||
"github.com/mayswind/lab/pkg/errs"
|
||||
)
|
||||
|
||||
func PrintSuccessResult(c *core.Context, result interface{}) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func PrintErrorResult(c *core.Context, err *errs.Error) {
|
||||
c.SetResponseError(err)
|
||||
|
||||
errorMessage := err.Error()
|
||||
|
||||
if err.Code() == errs.ErrIncompleteOrIncorrectSubmission.Code() && len(err.BaseError) > 0 {
|
||||
validationErrors, ok := err.BaseError[0].(validator.ValidationErrors)
|
||||
|
||||
if ok {
|
||||
for _, err := range validationErrors {
|
||||
errorMessage = getValidationErrorText(err)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.AbortWithStatusJSON(err.HttpStatusCode, gin.H{
|
||||
"success": false,
|
||||
"errorCode": err.Code(),
|
||||
"errorMessage": errorMessage,
|
||||
})
|
||||
}
|
||||
|
||||
func getValidationErrorText(err validator.FieldError) string {
|
||||
fieldName := GetFirstLowerCharString(err.Field())
|
||||
|
||||
switch err.Tag() {
|
||||
case "required":
|
||||
return errs.GetParameterIsRequiredMessage(fieldName)
|
||||
case "max":
|
||||
return errs.GetParameterMustLessThanMessage(fieldName, err.Param())
|
||||
case "min":
|
||||
return errs.GetParameterMustMoreThanMessage(fieldName, err.Param())
|
||||
case "len":
|
||||
return errs.GetParameterLengthNotEqualMessage(fieldName, err.Param())
|
||||
case "notBlank":
|
||||
return errs.GetParameterNotBeBlankMessage(fieldName)
|
||||
case "validUsername":
|
||||
return errs.GetParameterInvalidUsernameMessage(fieldName)
|
||||
case "validEmail":
|
||||
return errs.GetParameterInvalidEmailMessage(fieldName)
|
||||
}
|
||||
|
||||
return errs.GetParameterInvalidMessage(fieldName)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package utils
|
||||
|
||||
import "strconv"
|
||||
|
||||
func Int32ToString(num int) string {
|
||||
return strconv.Itoa(num)
|
||||
}
|
||||
|
||||
func StringToInt32(str string) (int, error) {
|
||||
return strconv.Atoi(str)
|
||||
}
|
||||
|
||||
func StringTryToInt32(str string, defaultValue int) int {
|
||||
num, err := StringToInt32(str)
|
||||
|
||||
if err != nil {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
return num
|
||||
}
|
||||
|
||||
func Int64ToString(num int64) string {
|
||||
return strconv.FormatInt(num, 10)
|
||||
}
|
||||
|
||||
func StringToInt64(str string) (int64, error) {
|
||||
return strconv.ParseInt(str, 10, 64)
|
||||
}
|
||||
|
||||
func StringTryToInt64(str string, defaultValue int64) int64 {
|
||||
num, err := StringToInt64(str)
|
||||
|
||||
if err != nil {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
return num
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package utils
|
||||
|
||||
import "time"
|
||||
|
||||
func FormatToLongDateTime(t time.Time) string {
|
||||
return t.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net"
|
||||
|
||||
"github.com/mayswind/lab/pkg/errs"
|
||||
)
|
||||
|
||||
func GetLocalIPAddressesString() (string, error) {
|
||||
localAddrs, err := GetLocalIPAddresses()
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if len(localAddrs) < 1 {
|
||||
return "", errs.ErrGettingLocalAddress
|
||||
}
|
||||
|
||||
buff := &bytes.Buffer{}
|
||||
|
||||
for i := 0; i < len(localAddrs); i++ {
|
||||
if i > 0 {
|
||||
buff.WriteString(",")
|
||||
}
|
||||
|
||||
buff.WriteString(localAddrs[i].String())
|
||||
}
|
||||
|
||||
return string(buff.Bytes()), nil
|
||||
}
|
||||
|
||||
func GetLocalIPAddresses() ([]net.IP, error) {
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var localAddrs []net.IP
|
||||
|
||||
for _, addr := range addrs {
|
||||
if ipnet, ok := addr.(*net.IPNet); ok {
|
||||
if ipnet.IP.IsLoopback() {
|
||||
continue
|
||||
}
|
||||
|
||||
if ipnet.IP.IsLinkLocalUnicast() {
|
||||
continue
|
||||
}
|
||||
|
||||
ip := ipnet.IP.To16()
|
||||
|
||||
if ip != nil {
|
||||
localAddrs = append(localAddrs, ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return localAddrs, nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
func GetRandomInteger(max int) (int, error) {
|
||||
result, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
|
||||
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return int(result.Int64()), nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package utils
|
||||
|
||||
import "regexp"
|
||||
|
||||
var (
|
||||
UsernamePattern = regexp.MustCompile("^(?i)[a-z0-9_-]+$")
|
||||
EmailPattern = regexp.MustCompile("^(?i)(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$")
|
||||
)
|
||||
|
||||
func IsValidUsername(username string) bool {
|
||||
return UsernamePattern.MatchString(username)
|
||||
}
|
||||
|
||||
func IsValidEmail(email string) bool {
|
||||
return EmailPattern.MatchString(email)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestIsValidUsername_ValidUserName(t *testing.T) {
|
||||
username := "foobar"
|
||||
expectedValue := true
|
||||
actualValue := IsValidUsername(username)
|
||||
assert.Equal(t, expectedValue, actualValue)
|
||||
|
||||
username = "--foo_bar--"
|
||||
expectedValue = true
|
||||
actualValue = IsValidUsername(username)
|
||||
assert.Equal(t, expectedValue, actualValue)
|
||||
}
|
||||
|
||||
func TestIsValidUsername_InvalidUserName(t *testing.T) {
|
||||
username := "foo~bar~"
|
||||
expectedValue := false
|
||||
actualValue := IsValidUsername(username)
|
||||
assert.Equal(t, expectedValue, actualValue)
|
||||
}
|
||||
|
||||
func TestIsValidEmail_ValidEmail(t *testing.T) {
|
||||
email := "foo@bar.com"
|
||||
expectedValue := true
|
||||
actualValue := IsValidEmail(email)
|
||||
assert.Equal(t, expectedValue, actualValue)
|
||||
|
||||
email = "foo@1.2.3.4"
|
||||
expectedValue = true
|
||||
actualValue = IsValidEmail(email)
|
||||
assert.Equal(t, expectedValue, actualValue)
|
||||
|
||||
email = "foo_bar@foo.bar"
|
||||
expectedValue = true
|
||||
actualValue = IsValidEmail(email)
|
||||
assert.Equal(t, expectedValue, actualValue)
|
||||
}
|
||||
|
||||
func TestIsValidEmail_InvalidEmail(t *testing.T) {
|
||||
email := "foo"
|
||||
expectedValue := false
|
||||
actualValue := IsValidEmail(email)
|
||||
assert.Equal(t, expectedValue, actualValue)
|
||||
|
||||
email = "@bar"
|
||||
expectedValue = false
|
||||
actualValue = IsValidEmail(email)
|
||||
assert.Equal(t, expectedValue, actualValue)
|
||||
|
||||
email = "foo@bar"
|
||||
expectedValue = false
|
||||
actualValue = IsValidEmail(email)
|
||||
assert.Equal(t, expectedValue, actualValue)
|
||||
|
||||
email = "foo@bar."
|
||||
expectedValue = false
|
||||
actualValue = IsValidEmail(email)
|
||||
assert.Equal(t, expectedValue, actualValue)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package utils
|
||||
|
||||
func IsStringSliceEuqals(s1, s2 []string) bool {
|
||||
if (s1 == nil) != (s2 == nil) {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(s1) != len(s2) {
|
||||
return false
|
||||
}
|
||||
|
||||
for i := 0; i < len(s1); i++ {
|
||||
if s1[i] != s2[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
|
||||
"github.com/mayswind/lab/pkg/errs"
|
||||
)
|
||||
|
||||
const (
|
||||
CHARACTERS = "!#$&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"
|
||||
NUMBER_AND_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
CHARACTERS_LENGTH = len(CHARACTERS)
|
||||
NUMBER_AND_LETTERS_LENGTH = len(NUMBER_AND_LETTERS)
|
||||
)
|
||||
|
||||
func SubString(str string, start int, length int) string {
|
||||
chars := []rune(str)
|
||||
realLength := len(chars)
|
||||
end := 0
|
||||
|
||||
if start < 0 {
|
||||
start = realLength - 1 + start
|
||||
}
|
||||
end = start + length
|
||||
|
||||
if start > end {
|
||||
start, end = end, start
|
||||
}
|
||||
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
|
||||
if start > realLength {
|
||||
start = realLength
|
||||
}
|
||||
|
||||
if end < 0 {
|
||||
end = 0
|
||||
}
|
||||
|
||||
if end > realLength {
|
||||
end = realLength
|
||||
}
|
||||
|
||||
return string(chars[start:end])
|
||||
}
|
||||
|
||||
func GetFirstLowerCharString(s string) string {
|
||||
if s == "" {
|
||||
return s
|
||||
}
|
||||
|
||||
chars := []rune(s)
|
||||
|
||||
if unicode.IsLower(chars[0]) {
|
||||
return s
|
||||
}
|
||||
|
||||
chars[0] = unicode.ToLower(chars[0])
|
||||
return string(chars)
|
||||
}
|
||||
|
||||
func GetRandomString(n int) (string, error) {
|
||||
var result = make([]byte, n)
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
index, err := GetRandomInteger(CHARACTERS_LENGTH)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
result[i] = CHARACTERS[index]
|
||||
}
|
||||
|
||||
return string(result), nil
|
||||
}
|
||||
|
||||
func GetRandomNumberOrLetter(n int) (string, error) {
|
||||
var result = make([]byte, n)
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
index, err := GetRandomInteger(NUMBER_AND_LETTERS_LENGTH)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
result[i] = NUMBER_AND_LETTERS[index]
|
||||
}
|
||||
|
||||
return string(result), nil
|
||||
}
|
||||
|
||||
func MD5Encode(data []byte) []byte {
|
||||
m := md5.New()
|
||||
m.Write(data)
|
||||
return m.Sum(nil)
|
||||
}
|
||||
|
||||
func AESGCMEncrypt(key []byte, plainText []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
aesgcm, err := cipher.NewGCM(block)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
nonce := make([]byte, aesgcm.NonceSize())
|
||||
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ciphertext := aesgcm.Seal(nil, nonce, plainText, nil)
|
||||
result := append(nonce, ciphertext...)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func AESGCMDecrypt(key []byte, ciphertext []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
aesgcm, err := cipher.NewGCM(block)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
nonceSize := aesgcm.NonceSize()
|
||||
|
||||
if len(ciphertext) - nonceSize <= 0 {
|
||||
return nil, errs.ErrCiphertextInvalid
|
||||
}
|
||||
|
||||
nonce := ciphertext[:nonceSize]
|
||||
ciphertext = ciphertext[nonceSize:]
|
||||
|
||||
plainText, err := aesgcm.Open(nil, nonce, ciphertext, nil)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return plainText, nil
|
||||
}
|
||||
|
||||
func EncodePassword(password string, salt string) string {
|
||||
encodedPassword := pbkdf2.Key([]byte(password), []byte(salt), 10000, 48, sha256.New) // 256^48 = 64^64
|
||||
return strings.TrimRight(base64.StdEncoding.EncodeToString(encodedPassword), "=")
|
||||
}
|
||||
|
||||
func EncyptSecret(secret string, key string) (string, error) {
|
||||
encyptedSecret, err := AESGCMEncrypt(MD5Encode([]byte(key)), []byte(secret)) // md5encode make the aes key's length to 16
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return base64.StdEncoding.EncodeToString(encyptedSecret), nil
|
||||
}
|
||||
|
||||
func DecryptSecret(encyptedSecret string, key string) (string, error) {
|
||||
encyptedData, err := base64.StdEncoding.DecodeString(encyptedSecret)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
secret, err := AESGCMDecrypt(MD5Encode([]byte(key)), []byte(encyptedData))
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(secret), nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package validators
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
|
||||
"github.com/mayswind/lab/pkg/utils"
|
||||
)
|
||||
|
||||
func ValidEmail(fl validator.FieldLevel) bool {
|
||||
if value, ok := fl.Field().Interface().(string); ok {
|
||||
if utils.IsValidEmail(value) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package validators
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
func NotBlank(fl validator.FieldLevel) bool {
|
||||
if value, ok := fl.Field().Interface().(string); ok {
|
||||
if value != "" && strings.Trim(value, " ") != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package validators
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
|
||||
"github.com/mayswind/lab/pkg/utils"
|
||||
)
|
||||
|
||||
func ValidUsername(fl validator.FieldLevel) bool {
|
||||
if value, ok := fl.Field().Interface().(string); ok {
|
||||
if utils.IsValidUsername(value) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user