Documentation ¶
Index ¶
- Constants
- Variables
- func AddRoleForUser(db *gorm.DB, uid uint, rid uint) error
- func CORSEnabled() gin.HandlerFunc
- func CheckGroupInUse(db *gorm.DB, gid uint) (bool, error)
- func CheckPassword(dbPassword, password string) bool
- func CheckPermissionInUse(db *gorm.DB, pid uint) (bool, error)
- func CheckPermissionNameExist(db *gorm.DB, name string) (bool, error)
- func CheckRoleInUse(db *gorm.DB, rid uint) (bool, error)
- func CheckRoleNameExist(db *gorm.DB, name string) (bool, error)
- func CheckRolePermission(db *gorm.DB, rid uint, uri, method string) (bool, error)
- func CheckUserPermission(db *gorm.DB, uid uint, uri, method string) (bool, error)
- func CheckValue(db *gorm.DB, key, default_value string)
- func Count[T any](db *gorm.DB, where ...any) (int, error)
- func CreateDatabaseInstance(driver, dsn string, cfg *gorm.Config) (*gorm.DB, error)
- func CurrentTimezone(c *gin.Context) *time.Location
- func Debugf(format string, v ...any)
- func Debugln(v ...any)
- func DeletePermission(db *gorm.DB, pid uint) error
- func DeleteRole(db *gorm.DB, rid uint) error
- func EncodeHashToken(user *User, timestamp int64, useLastLogin bool) (hash string)
- func Errorf(format string, v ...any)
- func Errorln(v ...any)
- func GenUniqueKey(tx *gorm.DB, field string, size int) (key string)
- func Get[T any](db *gorm.DB, val *T, where ...any) (*T, error)
- func GetBoolValue(db *gorm.DB, key string) bool
- func GetByID[T any, E ~uint | ~int | ~string](db *gorm.DB, id E, where ...any) (*T, error)
- func GetEnv(key string) string
- func GetIntValue(db *gorm.DB, key string, default_value int) int
- func GetPkColumnName[T any]() string
- func GetValue(db *gorm.DB, key string) string
- func HandleError(c *gin.Context, code int, err error)
- func HandleErrorMessage(c *gin.Context, code int, msg string)
- func HashPassword(password string) string
- func InTimezone(c *gin.Context, timezone string)
- func Infof(format string, v ...any)
- func Infoln(v ...any)
- func InitDatabase(driver, dsn string, logWrite io.Writer) *gorm.DB
- func InitMigrate(db *gorm.DB) error
- func InitRabbit(db *gorm.DB, r *gin.Engine)
- func IsExistByEmail(db *gorm.DB, email string) bool
- func Login(c *gin.Context, user *User)
- func Logout(c *gin.Context, user *User)
- func LookupEnv(key string) (string, bool)
- func MakeMigrates(db *gorm.DB, insts ...any) error
- func RandNumberText(n int) string
- func RandText(n int) string
- func RegisterAuthenticationHandlers(prefix string, db *gorm.DB, r *gin.Engine)
- func RegisterAuthorizationHandlers(db *gorm.DB, r gin.IRoutes)
- func SetLastLogin(db *gorm.DB, user *User, lastIp string) error
- func SetLogLevel(level int)
- func SetPassword(db *gorm.DB, user *User, password string) (err error)
- func SetValue(db *gorm.DB, key, value string)
- func StructAsMap(form any, fields []string) (vals map[string]any)
- func SwitchGroup(c *gin.Context, gid uint)
- func UpdateFields[T any](db *gorm.DB, model *T, vals map[string]any) error
- func Warningf(format string, v ...any)
- func Warningln(v ...any)
- func WithAuthentication() gin.HandlerFunc
- func WithAuthorization(prefix string) gin.HandlerFunc
- func WithCookieSession(secret string) gin.HandlerFunc
- func WithGormDB(db *gorm.DB) gin.HandlerFunc
- func WithMemSession(secret string) gin.HandlerFunc
- type ChangePasswordForm
- type Config
- type Group
- func CreateGroupByUser(db *gorm.DB, uid uint, name string) (*Group, error)
- func CurrentGroup(c *gin.Context) *Group
- func GetFirstGroupByUser(db *gorm.DB, uid uint) (*Group, error)
- func GetGroupByID(db *gorm.DB, gid uint) (*Group, error)
- func GetGroupByName(db *gorm.DB, name string) (*Group, error)
- func GetGroupsByUser(db *gorm.DB, uid uint) ([]*Group, error)
- type GroupMember
- type LoginForm
- type Permission
- func GetPermission(db *gorm.DB, uri, method string) (*Permission, error)
- func GetPermissionByID(db *gorm.DB, pid uint) (*Permission, error)
- func GetPermissionByName(db *gorm.DB, name string) (*Permission, error)
- func GetPermissionChildren(db *gorm.DB, pid uint) ([]*Permission, error)
- func GetPermissionsByRole(db *gorm.DB, rid uint) ([]*Permission, error)
- func SavePermission(db *gorm.DB, id, pid uint, name, uri, method string, anonymous bool) (*Permission, error)
- type Profile
- type RegisterUserForm
- type Role
- func AddRoleWithPermissions(db *gorm.DB, name, label string, ps []uint) (*Role, error)
- func CreateRole(db *gorm.DB, name, label string) (*Role, error)
- func CreateRoleWithPermissions(db *gorm.DB, name, label string, ps []*Permission) (*Role, error)
- func GetRoleByID(db *gorm.DB, rid uint) (*Role, error)
- func GetRoleByName(db *gorm.DB, name string) (*Role, error)
- func GetRolesByUser(db *gorm.DB, uid uint) ([]*Role, error)
- func UpdateRoleWithPermissions(db *gorm.DB, rid uint, name, label string, ps []uint) (*Role, error)
- type RoleForm
- type RolePermission
- type SigHandler
- type Signals
- type TestClient
- func (c *TestClient) Call(method, path string, form any, result any) error
- func (c *TestClient) CallDelete(path string, form, result any) error
- func (c *TestClient) CallGet(path string, form, result any) error
- func (c *TestClient) CallPatch(path string, form, result any) error
- func (c *TestClient) CallPost(path string, form any, result any) error
- func (c *TestClient) CallPut(path string, form, result any) error
- func (c *TestClient) Get(path string) *httptest.ResponseRecorder
- func (c *TestClient) Post(path string, body []byte) *httptest.ResponseRecorder
- func (c *TestClient) SendReq(path string, req *http.Request) *httptest.ResponseRecorder
- type User
- func CreateUser(db *gorm.DB, email, password string) (*User, error)
- func CurrentUser(c *gin.Context) *User
- func DecodeHashToken(db *gorm.DB, hash string, useLastLogin bool) (user *User, err error)
- func GetUserByEmail(db *gorm.DB, email string) (user *User, err error)
- func GetUserByID(db *gorm.DB, userID uint) (*User, error)
- func GetUsersByGroup(db *gorm.DB, gid uint) ([]*User, error)
- func GetUsersByRole(db *gorm.DB, rid uint) ([]*User, error)
- func UpdateRolesForUser(db *gorm.DB, uid uint, rids []uint) (*User, error)
- type UserRole
Constants ¶
const ( DbField = "_rabbit_db" TzField = "_rabbit_tz" UserField = "_rabbit_uid" // for session: uid, for context: *User GroupField = "_rabbit_gid" // for session: gid, for context: *Group )
const ( LevelDebug = iota LevelInfo LevelWarning LevelError )
const ( // SigUserLogin: user *User, c *gin.Context SigUserLogin = "user.login" // SigUserLogout: user *User, c *gin.Context SigUserLogout = "user.logout" //SigUserCreate: user *User, c *gin.Context SigUserCreate = "user.create" )
const CORS_ALLOW_ALL = "*"
const CORS_ALLOW_CREDENTIALS = "true"
const CORS_ALLOW_HEADERS = "" /* 137-byte string literal not displayed */
const CORS_ALLOW_METHODS = "POST, OPTIONS, GET, PUT, PATCH, DELETE"
const ENV_AUTH_PREFIX = "AUTH_PREFIX"
const ENV_DB_DRIVER = "DB_DRIVER"
DB
const ENV_DSN = "DSN"
const ENV_PASSWORD_SALT = "PASSWORD_SALT" // User Password salt
const ENV_SESSION_SECRET = "SESSION_SECRET"
const KEY_API_NEED_AUTH = "API_NEED_AUTH"
const KEY_USER_NEED_ACTIVATE = "USER_NEED_ACTIVATE"
const SessionField = "rabbit"
Gin session field
const XAuthTokenHeader = "X-Auth-Token"
Variables ¶
var EnabledConsoleColor = false
var LogLevel = LevelDebug
Functions ¶
func CORSEnabled ¶
func CORSEnabled() gin.HandlerFunc
1. set CORS header 2. if method is OPTIONS, return 204
func CheckRolePermission ¶
check
func CheckUserPermission ¶
func CheckValue ¶
CheckValue check if key exists, if not, set default_value
func CreateDatabaseInstance ¶
func CurrentTimezone ¶
1. try get cache from context 2. try get from session 3. set context cache
func DeletePermission ¶
if the permission is a parent permission, delete all its children
func EncodeHashToken ¶
timestamp-uid-token base64(email$timestamp) + "-" + sha256(salt + logintimestamp + password + email$timestamp)
func GenUniqueKey ¶
GenUniqueKey generate unique key for field
func GetPkColumnName ¶
func HashPassword ¶
func InTimezone ¶
1. set *time.Location to gin context, for cache 2. set [timezone string] to session
func InitMigrate ¶
func InitRabbit ¶
InitRabbit start with default middleware and auth handler 1. migrate models 2. gin middleware 3. setup env 4. setup config 5. auth handler
func RandNumberText ¶
func SetLogLevel ¶
func SetLogLevel(level int)
func SwitchGroup ¶
func WithAuthentication ¶
func WithAuthentication() gin.HandlerFunc
1. auth from session 2. auth from token
func WithAuthorization ¶
func WithAuthorization(prefix string) gin.HandlerFunc
check if the user has permission to access the url superuser no need to check
func WithCookieSession ¶
func WithCookieSession(secret string) gin.HandlerFunc
func WithGormDB ¶
func WithGormDB(db *gorm.DB) gin.HandlerFunc
func WithMemSession ¶
func WithMemSession(secret string) gin.HandlerFunc
Types ¶
type ChangePasswordForm ¶
type ChangePasswordForm struct {
Password string `json:"password" binding:"required"`
}
type Group ¶
type Group struct { ID uint `json:"id" gorm:"primarykey"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` Name string `json:"name" gorm:"size:200;uniqueIndex"` Extra string `json:"extra"` // for association Users []*User `json:"users" gorm:"many2many:group_members;"` }
TODO:
func CurrentGroup ¶
type GroupMember ¶
type GroupMember struct { UserID uint `json:"-" gorm:"primarykey"` GroupID uint `json:"-" gorm:"primarykey"` // for association User User `json:"user"` Group Group `json:"group"` }
TODO:
type Permission ¶
type Permission struct { ID uint `json:"id" gorm:"primarykey"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` ParentID uint `json:"parentId"` Name string `json:"name" gorm:"size:200;uniqueIndex"` Uri string `json:"uri" gorm:"size:200"` Method string `json:"method" gorm:"size:200"` Anonymous bool `json:"anonymous"` // any role can access // for association Groups []*Group `json:"groups" gorm:"many2many:group_permissions;"` Roles []*Role `json:"roles" gorm:"many2many:role_permissions;"` // for tree Children []*Permission `json:"children,omitempty" gorm:"-"` }
func GetPermission ¶
func GetPermission(db *gorm.DB, uri, method string) (*Permission, error)
func GetPermissionByID ¶
func GetPermissionByID(db *gorm.DB, pid uint) (*Permission, error)
func GetPermissionByName ¶
func GetPermissionByName(db *gorm.DB, name string) (*Permission, error)
func GetPermissionChildren ¶
func GetPermissionChildren(db *gorm.DB, pid uint) ([]*Permission, error)
func GetPermissionsByRole ¶
func GetPermissionsByRole(db *gorm.DB, rid uint) ([]*Permission, error)
func SavePermission ¶
func SavePermission(db *gorm.DB, id, pid uint, name, uri, method string, anonymous bool) (*Permission, error)
permission
type Profile ¶
type RegisterUserForm ¶
type RegisterUserForm struct { Email string `json:"email" binding:"required"` Password string `json:"password" binding:"required"` DisplayName string `json:"displayName"` FirstName string `json:"firstName"` LastName string `json:"lastName"` Locale string `json:"locale"` Timezone string `json:"timezone"` Source string `json:"source"` }
type Role ¶
type Role struct { ID uint `json:"id" gorm:"primarykey"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` Name string `json:"name" gorm:"size:50;uniqueIndex"` Label string `json:"label" gorm:"size:200"` // for association Users []*User `json:"users" gorm:"many2many:user_roles;"` Permissions []*Permission `json:"permissions" gorm:"many2many:role_permissions;"` }
func AddRoleWithPermissions ¶
func CreateRoleWithPermissions ¶
for test
type RolePermission ¶
type RolePermission struct { RoleID uint `json:"-" gorm:"primarykey"` PermissionID uint `json:"-" gorm:"primarykey"` // for association Role Role `json:"role"` Permission Permission `json:"permission"` }
type SigHandler ¶
type Signals ¶
type Signals struct {
// contains filtered or unexported fields
}
func NewSignals ¶
func NewSignals() *Signals
func (*Signals) Connect ¶
func (s *Signals) Connect(event string, handler SigHandler)
func (*Signals) DisConnect ¶
type TestClient ¶
type TestClient struct { CookieJar http.CookieJar Scheme string Host string // contains filtered or unexported fields }
func NewTestClient ¶
func NewTestClient(r http.Handler) (c *TestClient)
func (*TestClient) Call ¶
func (c *TestClient) Call(method, path string, form any, result any) error
func (*TestClient) CallDelete ¶
func (c *TestClient) CallDelete(path string, form, result any) error
func (*TestClient) CallPost ¶
func (c *TestClient) CallPost(path string, form any, result any) error
func (*TestClient) Get ¶
func (c *TestClient) Get(path string) *httptest.ResponseRecorder
Get return *httptest.ResponseRecorder
func (*TestClient) Post ¶
func (c *TestClient) Post(path string, body []byte) *httptest.ResponseRecorder
Post return *httptest.ResponseRecorder
func (*TestClient) SendReq ¶
func (c *TestClient) SendReq(path string, req *http.Request) *httptest.ResponseRecorder
type User ¶
type User struct { ID uint `json:"id" gorm:"primarykey"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` Email string `json:"email" gorm:"size:128;uniqueIndex"` Password string `json:"-" gorm:"size:128"` FirstName string `json:"firstName,omitempty" gorm:"size:128"` LastName string `json:"lastName,omitempty" gorm:"size:128"` DisplayName string `json:"displayName,omitempty" gorm:"size:128"` IsSuperUser bool `json:"isSuper"` Enabled bool `json:"enabled"` Activated bool `json:"activated"` LastLogin *time.Time `json:"lastLogin,omitempty"` LastLoginIP string `json:"lastLoginIP" gorm:"size:128"` Source string `json:"-" gorm:"size:64;index"` Locale string `json:"locale,omitempty" gorm:"size:20"` Timezone string `json:"timezone,omitempty" gorm:"size:200"` Profile *Profile `json:"profile,omitempty"` AuthToken string `json:"token,omitempty" gorm:"-"` // for association Groups []*Group `json:"groups" gorm:"many2many:group_members;"` Roles []*Role `json:"roles" gorm:"many2many:user_roles;"` }
func CurrentUser ¶
1. try get cache from context 2. try get user from token/session 3. set context cache
func DecodeHashToken ¶
base64(email$timestamp) + "-" + sha256(salt + logintimestamp + password + email$timestamp)