database

package
v0.0.0-...-e8f671e Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoMigrate

func AutoMigrate() error

AutoMigrate migrates the backend database tables to the latest structure

func Close

func Close() error

Close closes the backend database and attempts all maintenance and cleanup steps

func Create

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

Create inserts a value into the backend database

func DeploySampleData

func DeploySampleData() error

DeploySampleData applies development defaults and sample data to the backend database

func LogEvent

func LogEvent(userEntry *T_user, event Event, eventDetail string) error

LogEvent creates an event log entry in the database

func Open

func Open() error

Open opens the backend database from disk

func OpenForTesting

func OpenForTesting() error

OpenForTesting opens a shared in-memory SQLite database for use in tests. Call AutoMigrate after this to create the schema.

Types

type Event

type Event string

Event identifies an auditable user action

const EventApiToken Event = "API Token" // API token creation
const EventDatabaseAdd Event = "Database Added" // Database server creation
const EventDbPassword Event = "Database Password" // Database password reset
const EventLogin Event = "Login" // Successful user login
const EventScopeCreate Event = "Scope Created" // Scan scope creation
const EventScopeSecret Event = "Scope Secret" // Scan scope secret reset
const EventViewGrant Event = "User Granted" // View access grant
const EventViewToken Event = "Token Generated" // View token creation

type Result

type Result = map[string]interface{} // One dynamically shaped database result

type ResultSeries

type ResultSeries = []Result // Ordered set of database results

type ResultSeriesStats

type ResultSeriesStats = map[string]ResultSeries // Result series grouped by a handler-defined statistic

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
}

T_event represents an auditable user action persisted in the backend database

func GetEvents

func GetEvents(event Event, since time.Time, limit *int) ([]T_event, error)

GetEvents returns optionally limited events of the requested kind at or after the optional timestamp

func GetEventsAll

func GetEventsAll(since time.Time, limit *int) ([]T_event, error)

GetEventsAll returns all optionally limited events at or after the optional timestamp

func (*T_event) BeforeSave

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

BeforeSave sanitizes an event before GORM writes it to the database

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"`
}

T_group represents a user group and its ownership relations

func GetGroupById

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

GetGroupById searches a group by ID and returns a pointer to the found group. If no entry is found, a nil pointer is returned, make sure to check it!

func GetGroups

func GetGroups() ([]T_group, error)

GetGroups returns all groups from the database

func GetGroupsOfUser

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

GetGroupsOfUser returns the groups associated with a user

func (*T_group) AddOwner

func (group *T_group) AddOwner(userEntry *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 GetGroupById 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 creates a group in the database

func (*T_group) Delete

func (group *T_group) Delete() error

Delete removes a group from the database

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(userEntries []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 (*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
	Gid              string         `gorm:"column:gid;default:''" json:"-"`                        // Global user ID, e.g. within the company. May be util e.g. to query asset inventories.
	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.
	ApiTokenRevision uint           `gorm:"column:api_token_revision;default:0;not null" json:"-"` // A counter incremented on each API token issuance to invalidate previously issued API tokens.
	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"`
}

T_user represents a registered user and their details

func GetAdministrators

func GetAdministrators() ([]T_user, error)

GetAdministrators returns all administrative users from the database

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 entry is found, a nil pointer is returned, make sure to check it!

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 entry is found, a nil pointer is returned, make sure to check it!

func GetUsers

func GetUsers() ([]T_user, error)

GetUsers returns all users from the database

func NewUser

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

NewUser constructs a user model and pre-fills it with the given or default data

func (*T_user) AfterFind

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

AfterFind normalizes database values after GORM loads a user

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 creates a user in the database

func (*T_user) Delete

func (user *T_user) Delete() error

Delete removes a user from the database

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