db

package
v0.0.0-...-24fabdb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2024 License: GPL-3.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CACHE_DEFAULT_EXPIRE = 5 * time.Minute
	CACHE_DEFAULT_PURGE  = 10 * time.Minute
)
View Source
const (
	JWT_DEFAULT_PATH                = "/"
	JWT_DEFAULT_SESSION_EXPIRES     = time.Hour * 3
	JWT_DEFAULT_MAX_SESSION_EXPIRES = time.Hour * 6
	JWT_COOKIE_NAME                 = "session_token"
)
View Source
const (
	DefaultDBFolder = "db"
)

Variables

View Source
var (
	ErrRecordExists = fmt.Errorf("record exists")
	// Invalid parameters
	ErrInvalidID         = fmt.Errorf("invalid ID")
	ErrInvalidAuthType   = fmt.Errorf("invalid auth type")
	ErrInvalidPassphrase = fmt.Errorf("invalid passphrase")
	// Users
	ErrUserNotFound = fmt.Errorf("user not found")
	ErrUserExists   = fmt.Errorf("user exists")
	// User Groups
	ErrUserGroupNotFound = fmt.Errorf("user group not found")
	ErrUserGroupExists   = fmt.Errorf("user group exists")
	// Tokens
	ErrTokenNotFound = fmt.Errorf("token not found")
	ErrTokenExpired  = fmt.Errorf("token has expired")
)
View Source
var (
	TestDBRoot       = "/tmp/cuttle/db"
	TestCuttleDBName = "test_cuttle.db"
	TestAuthDBName   = "test_auth.db"
)
View Source
var (
	ErrExpiredCookie  = fmt.Errorf("cookie has expired")
	ErrSessionExpired = fmt.Errorf("session has expired")
)
View Source
var ErrKeyNotFound = fmt.Errorf("key not found")

Functions

func CreateJWT

func CreateJWT(userID int64, username, name, secret string, isAdmin bool) (string, error)

func DeleteDB

func DeleteDB(filename string)

func GenDBFolder

func GenDBFolder() string

func IsErrNotUnique

func IsErrNotUnique(err error) bool

IsErrNotUnique checks if the error is due to a unique constraint violation.

func RefreshJWT

func RefreshJWT(claims *Claims, secret string) (string, error)

func SetAuthSecret

func SetAuthSecret(secret string) error

SetAuthSecret sets the secret used to sign JWTs.

func SetDBRoot

func SetDBRoot(rootDir string) error

SetDBRoot sets the root directory for the database. If this is not set, the default behavior is to create a directory called "db" in the current working directory. Example:

db.InitDB("/path/to/db")

Expected Behavior:

db.InitDB("/tmp/db")
db.NewSqliteDB("mydb.db")
db.Open()

`ls /tmp/db/`
mydb.db

func TokensMigrate

func TokensMigrate(db *SqliteDB) error

UserGroupsMigrate creates the 'user_groups' table if it does not exist.

func UserGroupsMigrate

func UserGroupsMigrate(db *SqliteDB) error

UserGroupsMigrate creates the 'user_groups' table if it does not exist.

Types

type AuthDB

type AuthDB interface {
	Open() error
	AuthMigrate() error
	Close() error
	// AddRepo(file, alias string, migrate migrater) error
	// Attach(filename, alias string) error
	// Users
	UserIsUnique(username string) error
	UserCreate(username, name, password, groups string) (UserData, error)
	UserGet(id int64) (UserData, error)
	UserGetByUsername(username string) (UserData, error)
	UserUpdate(user UserData) (UserData, error)
	UserDelete(id int64) error
	// UserGroups
	UserGroupIsUnique(name string) error
	UserGroupCreate(name, members, profiles string) (UserGroupData, error)
	UserGroupGet(id int64) (UserGroupData, error)
	UserGroupGetByName(name string) (UserGroupData, error)
	UserGroupGetGroups(ids []int64) ([]UserGroupData, error)
	UserGroupUpdate(group UserGroupData) (UserGroupData, error)
	UserGroupDelete(id int64) error
	// Tokens
	TokenCreate(userID int64, username, name string, isAdmin bool) (string, error)
	TokenGet(bearer string) (*Claims, error)
	TokenUpdate(bearer string, claims *Claims) error
	TokenDelete(bearer string) error
}

type AuthMethodData

type AuthMethodData struct {
	ID       int
	Name     string
	AuthType string
	Data     string
}

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache is a wrapper around the go-cache library.

func DefaultCache

func DefaultCache() *Cache

DefaultCache returns a new Cache instance with default expiration and purge times.

func NewCache

func NewCache(expire, purge time.Duration) *Cache

NewCache returns a new Cache instance with the specified expiration and purge times.

func (*Cache) Delete

func (c *Cache) Delete(key string)

Delete the key from the cache.

func (*Cache) Get

func (c *Cache) Get(key string) (interface{}, bool)

Get the value for the key. Returns value and true if found.

func (*Cache) GetAndRefresh

func (c *Cache) GetAndRefresh(key string) (interface{}, bool)

Get the value for the key and refresh the expiration time to the instance's DefaultExpiration.

func (*Cache) Refresh

func (c *Cache) Refresh(key string) error

Refresh the expiration time for the key to the instance's DefaultExpiration.

func (*Cache) Set

func (c *Cache) Set(key string, value interface{})

Set the key to the value with the instance's DefaultExpiration.

func (*Cache) SetWithExpire

func (c *Cache) SetWithExpire(key string, value interface{}, expire time.Duration)

Set the key to the value with the specified expiration time.

type Claims

type Claims struct {
	UserID   int64  `json:"user_id"`
	Username string `json:"username"`
	Name     string `json:"name"`
	IsAdmin  bool   `json:"is_admin"`
	jwt.RegisteredClaims
}

func ParseJWT

func ParseJWT(tokenString, secret string) (*Claims, error)

type CuttleDB

type CuttleDB interface {
	Open() error
	CuttleMigrate() error
	Close() error
}

type SqliteDB

type SqliteDB struct {
	Name string // DB file name.
	*sql.DB
	// contains filtered or unexported fields
}

SqliteDB is a wrapper around the sqlite3 database. It also holds the db filename and context.

func NewSqliteDB

func NewSqliteDB(filename string) (*SqliteDB, error)

NewSqliteDB creates a new Sqlite3 DB instance.

func TestSqliteAuthDBSetup

func TestSqliteAuthDBSetup(t *testing.T) *SqliteDB

TestSqliteAuthDBSetup creates a new SqliteDB instance for testing. You will still need to run AuthMigrate.

func TestSqliteCuttleDBSetup

func TestSqliteCuttleDBSetup(t *testing.T) *SqliteDB

TestSqliteCuttleDBSetup creates a new SqliteDB instance for testing. You will still need to run CuttleMigrate.

func (*SqliteDB) AuthMigrate

func (db *SqliteDB) AuthMigrate() error

AuthMigrate runs the migrations for each table in the auth database.

func (*SqliteDB) Close

func (db *SqliteDB) Close() error

Close cancels the context and closes the database connection.

func (*SqliteDB) CuttleMigrate

func (db *SqliteDB) CuttleMigrate() error

CuttleMigrate runs the migrations for each table in the main cuttle database.

func (*SqliteDB) Exec

func (db *SqliteDB) Exec(query string, args ...any) (sql.Result, error)

func (*SqliteDB) IsUnique

func (db *SqliteDB) IsUnique(table string, where string, args ...any) error

IsUnique returns nil if no records exist in the table that match the where clause. If a record exists, it returns an ErrRecordExists error. The 'where' clause should not include the "WHERE" keyword but may include multiple column queries which are comma separated: 'col1 = ?, col2 = ?'. The 'args' are the values to be used in the where clause.

Example: db.IsUnique("users", "username = ?", "myusername")

func (*SqliteDB) Open

func (db *SqliteDB) Open() error

Open opens the database with WAL and foreign_keys enabled. Open then pings the database. If the database does not exist, it will be created.

func (*SqliteDB) Query

func (db *SqliteDB) Query(query string, args ...any) (*sql.Rows, error)

func (*SqliteDB) QueryRow

func (db *SqliteDB) QueryRow(query string, args ...any) (*sql.Row, error)

func (*SqliteDB) TokenClean

func (db *SqliteDB) TokenClean() error

func (*SqliteDB) TokenCreate

func (db *SqliteDB) TokenCreate(userID int64, username, name string, isAdmin bool) (string, error)

func (*SqliteDB) TokenDelete

func (db *SqliteDB) TokenDelete(bearer string) error

func (*SqliteDB) TokenGet

func (db *SqliteDB) TokenGet(bearer string) (*Claims, error)

func (*SqliteDB) TokenUpdate

func (db *SqliteDB) TokenUpdate(bearer string, claims *Claims) error

func (*SqliteDB) UserCreate

func (db *SqliteDB) UserCreate(username, name, pwHash, groups string) (UserData, error)

UserCreate creates a new user in the database and returns the new user data. A password should never be provided in plain text. UserCreate will check for hash formatting.

func (*SqliteDB) UserDelete

func (db *SqliteDB) UserDelete(id int64) error

UserDelete deletes a user from the database by ID.

func (*SqliteDB) UserGet

func (db *SqliteDB) UserGet(id int64) (UserData, error)

UserGet retrieves a user from the database by ID.

func (*SqliteDB) UserGetByUsername

func (db *SqliteDB) UserGetByUsername(username string) (UserData, error)

UserGetByUsername retrieves a user from the database by username.

func (*SqliteDB) UserGroupCreate

func (db *SqliteDB) UserGroupCreate(name, members, profiles string) (UserGroupData, error)

Create a new user group. Returns the new user group data.

Members should be a JSON array of user IDs. An ID of 0 is invalid: `[1,5,28,349]`

Profiles should be a JSON object of profile names and permissions: `{"profile_id": {"method": bool, ...}}`

Profiles Example: {124: {"POST": false, "GET": true, "PUT": false, "DELETE": false}, 5462: {"POST": false, "GET": true, "PUT": true, "DELETE": false}}

func (*SqliteDB) UserGroupDelete

func (db *SqliteDB) UserGroupDelete(id int64) error

UserGroupDelete deletes a user group from the database by ID.

func (*SqliteDB) UserGroupGet

func (db *SqliteDB) UserGroupGet(id int64) (UserGroupData, error)

UserGroupGet retrieves a user group from the database by ID.

func (*SqliteDB) UserGroupGetByName

func (db *SqliteDB) UserGroupGetByName(name string) (UserGroupData, error)

UserGroupGetByName retrieves a user group from the database by name.

func (*SqliteDB) UserGroupGetGroups

func (db *SqliteDB) UserGroupGetGroups(gids []int64) ([]UserGroupData, error)

UserGroupGetGroups retrieves multiple user groups from the database by ID.

func (*SqliteDB) UserGroupIsUnique

func (db *SqliteDB) UserGroupIsUnique(name string) error

UserGroupIsUnique checks if the user group name is unique in the database. If the name is not unique, it returns an ErrUserGroupExists error.

func (*SqliteDB) UserGroupUpdate

func (db *SqliteDB) UserGroupUpdate(data UserGroupData) (UserGroupData, error)

UserGroupUpdate updates a user group in the database and returns the updated user group data.

func (*SqliteDB) UserIsUnique

func (db *SqliteDB) UserIsUnique(username string) error

UserIsUnique checks if the username is unique in the database. If the username is not unique, it returns an ErrUserExists error.

func (*SqliteDB) UserUpdate

func (db *SqliteDB) UserUpdate(user UserData) (UserData, error)

UserUpdate updates a user in the database and returns the updated user data.

func (*SqliteDB) UsersMigrate

func (db *SqliteDB) UsersMigrate() error

UsersMigrate creates the 'users' table if it does not exist.

type TokenData

type TokenData struct {
	Bearer  string
	JWT     string    // Group name.
	Created time.Time // Time created.
	Expires time.Time // Time last updated.
}

UserGroupData represents a user group in the database.

type UserData

type UserData struct {
	ID       int64
	Username string    // Username to login with.
	Name     string    // Name to show in app.
	Hash     string    // Hashed password.
	Groups   string    // JSON string of group IDs. Empty should be "[]".
	IsAdmin  bool      // Is the user an admin.
	Created  time.Time // Time created.
	Updated  time.Time // Time last updated.
}

UserData represents a user in the database.

type UserGroupData

type UserGroupData struct {
	ID       int64
	Name     string    // Group name.
	Members  string    // JSON string of user IDs. Empty should be "[]". "[1,5,28,349]"
	Profiles string    // JSON string of profile IDs. Empty should be "{}". "{profile_id:{method: bool...}".
	Created  time.Time // Time created.
	Updated  time.Time // Time last updated.
}

UserGroupData represents a user group in the database.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL