database

package
v0.0.0-...-7c04fb6 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2025 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoMigrate

func AutoMigrate() error

AutoMigrate migrates the cache database's tables to the latest structure

func Close

func Close() error

Close closes an open backendDb

func Create

func Create(value interface{}) (tx *gorm.DB)

func DeploySampleData

func DeploySampleData() error

DeploySampleData applies a default configuration for development purposes and some sample data to the db

func NewEvent

func NewEvent(user *T_user, eventType Event, eventDetail string) error

NewEvent creates an event log entry in the database.

func Open

func Open() error

Open opens the backendDb from disk

Types

type Event

type Event string
const (
	EventLogin       Event = "Login"
	EventDbPassword  Event = "Database Password"
	EventScopeCreate Event = "Scope Created"
	EventScopeSecret Event = "Scope Secret"
	EventViewGrant   Event = "User Granted"
	EventViewToken   Event = "Token Generated"
	EventDatabaseAdd Event = "Database Added"
)

Definition of some standard event values

type T_event

type T_event struct {
	// - Set the JSON ignore flag (json:"-") for sensitive columns that may NEVER be leaked by a JSON response.
	// - Make columns "not null" if possible. Otherwise, use null-types (e.g. sql.NullString).
	// - Avoid 'default' constraints or gorm will replace empty values (0, "", false) with set default values on CREATE!
	// - Define a lower-snake-case json name for every attribute.
	Id          uint64    `gorm:"column:id;primaryKey" json:"-"`
	IdTUser     uint64    `gorm:"column:id_t_user;type:int" json:"-"`
	Email       string    `gorm:"column:email;not null" json:"email"`
	Timestamp   time.Time `gorm:"column:timestamp;default:CURRENT_TIMESTAMP" json:"timestamp"`
	Event       Event     `gorm:"column:event;not null" json:"event"`
	EventDetail string    `gorm:"column:event_detail;default:''" json:"event_detail"`

	User *T_user `gorm:"foreignKey:IdTUser;constraint:OnUpdate:CASCADE,OnDelete:SET NULL" json:"user"` // User must be pointer *T_user, because it can be null OnDelete
}

func GetEvents

func GetEvents(eventType Event, since time.Time) ([]T_event, error)

func (*T_event) BeforeSave

func (user *T_event) BeforeSave(tx *gorm.DB) error

BeforeSave is a GORM hook that's executed every time the user object is written to the DB. This should be used to do some data sanitization, e.g. to strip illegal HTML tags in user attributes or to convert values to a certain format.

type T_group

type T_group struct {
	// - Set the JSON ignore flag (json:"-") for sensitive columns that may NEVER be leaked by a JSON response.
	// - Make columns "not null" if possible. Otherwise, use null-types (e.g. sql.NullString).
	// - Avoid 'default' constraints or gorm will replace empty values (0, "", false) with set default values on CREATE!
	// - Define a lower-snake-case json name for every attribute.
	Id         uint64    `gorm:"column:id;primaryKey" json:"id"`
	Name       string    `gorm:"column:name;not null" json:"name"`
	Created    time.Time `gorm:"column:created;not null;default:CURRENT_TIMESTAMP" json:"created"`
	CreatedBy  string    `gorm:"column:created_by;not null" json:"created_by"`
	DbServerId uint64    `gorm:"column:db_server_id;not null;default:1" json:"db_server_id"`
	MaxScopes  int       `gorm:"column:max_scopes;not null" json:"max_scopes"`
	MaxViews   int       `gorm:"column:max_views;not null" json:"max_views"`
	MaxTargets int       `gorm:"column:max_targets;not null" json:"max_targets"`
	MaxOwners  int       `gorm:"column:max_owners;not null" json:"max_owners"`

	AllowCustom  bool `gorm:"column:allow_custom;not null;default:true" json:"allow_custom"`
	AllowNetwork bool `gorm:"column:allow_network;not null;default:false" json:"allow_network"`
	AllowAsset   bool `gorm:"column:allow_asset;not null;default:false" json:"allow_asset"`

	Ownerships []T_ownership `gorm:"foreignKey:IdTGroup;constraint:OnUpdate:CASCADE,OnDelete:CASCADE" json:"ownerships"`
}

func GetGroup

func GetGroup(id uint64) (*T_group, error)

GetGroup searches a group by ID and returns a pointer to the found group. If no group is found, a nil pointer but no error will be returned.

func GetGroups

func GetGroups() ([]T_group, error)

GetGroups gets all groups from the db

func GetGroupsOfUser

func GetGroupsOfUser(userId uint64) ([]T_group, error)

func (*T_group) AddOwner

func (group *T_group) AddOwner(user *T_user) error

AddOwner creates an ownership by adding a user to a group. The ownerships set in the group will be updated by this function. However, the existing ownerships must not have the User.Ownerships or Group values set, as this will result in an endless SQL query. (The group returned by GetGroup is valid)

func (*T_group) BeforeSave

func (group *T_group) BeforeSave(tx *gorm.DB) error

BeforeSave is a GORM hook that's executed every time the user object is written to the DB. This should be used to do some data sanitization, e.g. to strip illegal HTML tags in user attributes or to convert values to a certain format.

func (*T_group) Create

func (group *T_group) Create() error

Create a group

func (*T_group) Delete

func (group *T_group) Delete() error

Delete a group

func (*T_group) Save

func (group *T_group) Save(columns ...string) (int64, error)

Save updates defined columns of a group entry in the database. It updates defined columns, to the currently set values, even if the values are empty ones, such as 0, false or "". ATTENTION: Only update required columns to avoid overwriting changes of parallel processes (with data in memory)

func (*T_group) UpdateOwners

func (group *T_group) UpdateOwners(users []T_user) error

UpdateOwners removes all owners and sets them to the given list of new owners. The ownerships set in the group will be updated by this function.

type T_ownership

type T_ownership struct {
	// "uniqueIndex" is a workaround to introduce a "unique" mechanism across multiple columns (group id and user id)
	Id       uint64 `gorm:"column:id;primaryKey" json:"id"`
	IdTGroup uint64 `gorm:"column:id_t_group;type:int;not null;uniqueIndex:idx_group_user"` // SQLITE3 does only support FK via type definition https://github.com/go-gorm/gorm/issues/765 https://www.sqlite.org/foreignkeys.html
	IdTUser  uint64 `gorm:"column:id_t_user;type:int;not null;uniqueIndex:idx_group_user"`  // SQLITE3 does only support FK via type definition https://github.com/go-gorm/gorm/issues/765 https://www.sqlite.org/foreignkeys.html

	Group T_group `gorm:"foreignKey:IdTGroup" json:"group"`
	User  T_user  `gorm:"foreignKey:IdTUser" json:"user"`
}

T_ownership is a join-table to establish a many-to-many relationship between users and groups. Each expressed relationship contains additional attributes, like whether it is an administrative relationship.

func GetOwnership

func GetOwnership(groupId, userId uint64) (*T_ownership, error)

GetOwnership searches an ownership for given Group ID and User ID and returns the associated entry if existing. This function can return one entry at most, as the group id and user id are used for a composite unique index. If the entry does not exist nil and no error will be returned.

func (*T_ownership) Delete

func (ownership *T_ownership) Delete() error

Delete an ownership relation

type T_user

type T_user struct {
	// - Set the JSON ignore flag (json:"-") for sensitive columns that may NEVER be leaked by a JSON response.
	// - Make columns "not null" if possible. Otherwise, use null-types (e.g. sql.NullString).
	// - Avoid 'default' constraints or gorm will replace empty values (0, "", false) with set default values on CREATE!
	// - Define a lower-snake-case json name for every attribute.
	Id             uint64         `gorm:"column:id;primaryKey" json:"id"`
	Email          string         `gorm:"column:email;not null;unique" json:"email"`       // User ID. Notification e-mail == user ID, to make sure this is always in sync
	Password       sql.NullString `gorm:"column:password" json:"-"`                        // Password hash for users not using a dedicated authenticator, such as oauth SSO. Empty password indicates other authentication mechanism.
	Company        string         `gorm:"column:company;not null" json:"company"`          // Field to mark users of the same company, as those will be able to see each other
	Department     string         `gorm:"column:department;default:'';" json:"department"` // Field to support distinguishing users of a company from different departments
	Created        time.Time      `gorm:"column:created;not null" json:"created"`          //
	LastLogin      time.Time      `gorm:"column:last_login;not null" json:"last_login"`    // Last time an access token was requested
	LogoutCount    uint           `gorm:"column:logout_count;default:0" json:"-"`          // A counter incremented on each logout and incorporated into every JWT token to invalidate previously issued ones ahead of time.
	Active         bool           `gorm:"column:active;not null" json:"active"`            //
	Admin          bool           `gorm:"column:admin;not null" json:"admin"`              //
	Name           string         `gorm:"column:name;not null" json:"name"`                //
	Surname        string         `gorm:"column:surname;not null" json:"surname"`          //
	Gender         string         `gorm:"column:gender;default:''" json:"gender"`          // Gender could be either M/W/D, but can also be left empty
	Demo           bool           `gorm:"column:demo;not null;default:false" json:"demo"`  // Whether the user is allowed to view modules but not execute them
	Certificate    []byte         `gorm:"column:certificate;not null" json:"certificate"`  // User's public key to allow sending encrypted messages
	DbPasswordHash string         `gorm:"column:db_password;default:''" json:"-"`          // Hashed password generated by the system and used as the user's temporary password to access database views. This hash is injected into the database user object, to avoid clear-text password handling.

	Ownerships []T_ownership `gorm:"foreignKey:IdTUser;constraint:OnUpdate:CASCADE,OnDelete:CASCADE" json:"ownerships"`
}

func GetAdministrators

func GetAdministrators() ([]T_user, error)

GetAdministrators gets all administrative users from the db

func GetUser

func GetUser(id uint64) (*T_user, error)

GetUser searches a user by ID and returns a pointer to the found user. If no user is found, a nil pointer but no error will be returned.

func GetUserByMail

func GetUserByMail(mail string) (*T_user, error)

GetUserByMail searches a user by e-mail address and returns a pointer to the found user. This function will only find zero or one user, because the e-mail address is a unique attribute. If no user is found, a nil pointer but no error will be returned.

func GetUsers

func GetUsers() ([]T_user, error)

GetUsers gets all users from the db

func NewUser

func NewUser(email string, company string, department string, name string, surname string) *T_user

NewUser constructs a User struct and pre-fills it with given or default data

func (*T_user) AfterFind

func (user *T_user) AfterFind(tx *gorm.DB) (err error)

func (*T_user) BeforeSave

func (user *T_user) BeforeSave(tx *gorm.DB) error

BeforeSave is a GORM hook that's executed every time the user object is written to the DB. This should be used to do some data sanitization, e.g. to strip illegal HTML tags in user attributes or to convert values to a certain format.

func (*T_user) Create

func (user *T_user) Create() error

Create crates a user in the database

func (*T_user) Delete

func (user *T_user) Delete() error

Delete a user

func (*T_user) Save

func (user *T_user) Save(columns ...string) (int64, error)

Save updates defined columns of a user entry in the database. It updates defined columns, to the currently set values, even if the values are empty ones, such as 0, false or "". ATTENTION: Only update required columns to avoid overwriting changes of parallel processes (with data in memory)

Jump to

Keyboard shortcuts

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