database

package
v0.0.14-beta Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2022 License: GPL-2.0 Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Permissions = []Permission{
		{

			Permission:  PermissionAuthentication,
			Name:        "Authentication",
			Description: "Allows the user to authenticate",
		},
		{

			Permission:  PermissionSetPower,
			Name:        "Set Power",
			Description: "Interact with switches",
		},
		{

			Permission:  PermissionAddLogEvent,
			Name:        "Add Log Event",
			Description: "Use the internal logging system",
		},
		{

			Permission:  PermissionDeleteLogs,
			Name:        "Flush Logs All or Old",
			Description: "Delete logs events which are older than 30 days or delete all log events",
		},
		{

			Permission:  PermissionListLogs,
			Name:        "List Logs",
			Description: "List all internal logs",
		},
		{

			Permission:  PermissionChangeAvatar,
			Name:        "Upload / Delete / Change Avatar",
			Description: "Allows the user to customize their avatar",
		},
		{

			Permission:  PermissionChangeUserPermissions,
			Name:        "Change User Permissions",
			Description: "Add / delete permissions to / from users",
		},
		{

			Permission:  PermissionChangeSwitchPermissions,
			Name:        "Change User Switch Permissions",
			Description: "Add / delete switch permissions to / from users",
		},
		{

			Permission:  PermissionGetDebugInfo,
			Name:        "Display Debug Info",
			Description: "Obtain debug information about the system",
		},
		{

			Permission:  PermissionChangeUsers,
			Name:        "Add / Delete users",
			Description: "Create a new user or delete users",
		},
		{

			Permission:  PermissionListUsers,
			Name:        "List users",
			Description: "See a list of all users",
		},
		{

			Permission:  PermissionHomescript,
			Name:        "Use Homescript",
			Description: "List, add, delete, run, and modify Homescripts",
		},
		{

			Permission:  PermissionAutomation,
			Name:        "Use Automations",
			Description: "List, add, delete, and modify automations",
		},
		{

			Permission:  PermissionWildCard,
			Name:        "Permission Wildcard *",
			Description: "Allows all permissions",
		},
	}
)

Functions

func AddLogEvent

func AddLogEvent(name string, description string, level int) error

Add a logged internal event based on `name, description, and level`

func AddNotification

func AddNotification(receiverUsername string, name string, description string, priority uint8) error

Adds a new notification to a user's `inbox`, can return an error if the database fails

func AddUser

func AddUser(user FullUser) error

Helper function to create a User which is given a set of basic permissions Will return an error if the database fails Does not check for duplicate users

func AddUserPermission

func AddUserPermission(username string, permission PermissionType) (bool, error)

Adds a permission to a user, if database fails, then an error is returned Does not check for username so additional checks should be completed beforehand

func AddUserSwitchPermission

func AddUserSwitchPermission(username string, switchId string) (bool, error)

Adds a given switchId to a given user The existence of the switch should be validated beforehand If this permission already resides inside the table, it is ignored and modified=false, error=nil is returned

func CheckDatabase

func CheckDatabase() error

Executes a ping to the database in order to check if it is online

func CreateHardwareNode

func CreateHardwareNode(name string, url string, token string) error

Adds a new hardware node to the database, if the node already exists (same url), its name will be updated

func CreateNewAutomation

func CreateNewAutomation(automation Automation) (uint, error)

Creates a new automation item, does not check the validity of the user or the homescript Id

func CreateNewHomescript

func CreateNewHomescript(homescript Homescript) error

Creates a new homescript entry

func CreateRoom

func CreateRoom(RoomId string, Name string, Description string) error

Creates a new room

func CreateSwitch

func CreateSwitch(id string, name string, roomId string) error

Creates a new switch Will return an error if the database fails

func DeleteAllNotificationsFromUser

func DeleteAllNotificationsFromUser(username string) error

If the user requests to empty their notification area, all hist notifications will be deleted

func DeleteAutomationById

func DeleteAutomationById(automationId uint) error

Deletes an automation item given its Id Does not validate the validity of the provided Id

func DeleteHardwareNode

func DeleteHardwareNode(url string) error

Deletes a node given its url

func DeleteHomescriptById

func DeleteHomescriptById(homescriptId string) error

Deletes a homescript by its Id, does not check if the user has access to the homescript

func DeleteNotificationFromUserById

func DeleteNotificationFromUserById(notificationId uint, username string) error

Deletes a given notification, can return an error

func DeleteSwitch

func DeleteSwitch(switchId string) error

Delete a given switch after all data which depends on this switch has been deleted

func DeleteTables

func DeleteTables() error

func DeleteUser

func DeleteUser(username string) error

Deletes a User based on a given Username, can return an error if the database fails The function does not validate the existence of this username itself, so additional checks should be done beforehand The avatar is removed in `core/user/user`

func DoesHomescriptExist

func DoesHomescriptExist(homescriptId string) (bool, error)

Checks if a Homescript with an id exists in the database

func DoesPermissionExist

func DoesPermissionExist(permission string) bool

Checks the validity of a given permission string

func DoesSwitchExist

func DoesSwitchExist(switchId string) (bool, error)

Returns (exists, error), err when the database fails

func DoesUserExist

func DoesUserExist(username string) (bool, error)

Returns <true> if a provided user exists If the database fails, it returns an error

func FlushAllLogs

func FlushAllLogs() error

func FlushOldLogs

func FlushOldLogs() error

Deletes log events older than 30 days in order to save storage space This function will later be used by a scheduler for daily jobs

func GetAvatarPathByUsername

func GetAvatarPathByUsername(username string) (string, error)

Returns the path of the avatar image of a given user, does not check if the user exists, additional checks needed beforehand

func GetPowerStateOfSwitch

func GetPowerStateOfSwitch(switchId string) (bool, error)

Returns the power state of a given switch as a boolean Does not check if the switch exists. If the switch does not exist, an error is returned

func GetUserNotificationCount

func GetUserNotificationCount(username string) (uint16, error)

Used for displaying the notification count for a given user Used in the frontend before the actual permissions are fetched

func GetUserPasswordHash

func GetUserPasswordHash(username string) (string, error)

Returns the password of a given user

func GetUserPermissions

func GetUserPermissions(username string) ([]string, error)

Returns a list of permissions assigned to a given user, if it exists

func GetUserSwitchPermissions

func GetUserSwitchPermissions(username string) ([]string, error)

Returns a list of strings which resemble switch permissions

func Init

func Init(databaseConfig DatabaseConfig, adminPassword string) error

func InitLogger

func InitLogger(logger *logrus.Logger)

func InsertUser

func InsertUser(user FullUser) error

Creates a new user based on a the supplied `User` struct Won't panic if user already exists, but will change password

func ModifyAutomation

func ModifyAutomation(automationId uint, newItem AutomationWithoutIdAndUsername) error

Modifies the metadata of a given automation item Does not validate the provided metadata

func ModifyHomescriptById

func ModifyHomescriptById(id string, homescript HomescriptFrontend) error

Modifies the metadata of a given homescript Does not check the validity of the homescript's id

func RemoveAllPermissionsOfUser

func RemoveAllPermissionsOfUser(username string) error

Removes all permissions of a given user, used when deleting a user in order to prevent foreign key failure Does not validate username, additional checks required, returns an error if the database fails

func RemoveAllSwitchPermissionsOfUser

func RemoveAllSwitchPermissionsOfUser(username string) error

Removes all switch permission of a given user, used when deleing a user Does not validate the existence of said user

func RemoveSwitchFromPermissions

func RemoveSwitchFromPermissions(switchId string) error

Deletes all occurrences of a given switch, used if a certain switch is deleted completely

func RemoveUserPermission

func RemoveUserPermission(username string, permission PermissionType) (bool, error)

Attempts to remove a provided permission from a provided user Fails if permission does not exist or if the database fails Warns and returns `false` for the `modified` boolean the user does not have the permission

func RemoveUserSwitchPermission

func RemoveUserSwitchPermission(username string, switchId string) (bool, error)

TODO: check naming consistency of `ADD / CREATE` and `DELETE / REMOVE` Removes a switch permission from a user, but does not delete if from the switch permission list

func SetNodeOnline

func SetNodeOnline(nodeUrl string, online bool) error

Updates the online / offline state of a given node (url)

func SetPowerState

func SetPowerState(switchId string, isPoweredOn bool) (bool, error)

Used when marking a power state of a switch Does not check the validity of the switch Id The returned boolean indicates if the power state had changed

func SetUserAvatarPath

func SetUserAvatarPath(username string, avatarPath string) error

Sets the path of the avatar for a given user, does not check if the user exists, additional checks needed beforehand

func UserHasPermission

func UserHasPermission(username string, permission PermissionType) (bool, error)

Checks if a provided user is in possession of a provided permission, can return an error, if the database fails

func UserHasSwitchPermission

func UserHasSwitchPermission(username string, switchId string) (bool, error)

Will return a boolean if a user has a switch permission

Types

type Automation

type Automation struct {
	Id             uint
	Name           string
	Description    string
	CronExpression string
	HomescriptId   string
	Owner          string
}

func GetAutomationById

func GetAutomationById(id uint) (Automation, bool, error)

Returns a Automation struct which matches the given Id If the id does not match a struct, an error is returned

func GetAutomations

func GetAutomations() ([]Automation, error)

Returns a list with automations of all users Used for activating persistent automations when the server starts

func GetUserAutomations

func GetUserAutomations(username string) ([]Automation, error)

Returns a list with automations of a given user Does not check the validity of the user

type AutomationWithoutIdAndUsername

type AutomationWithoutIdAndUsername struct {
	Name           string
	Description    string
	CronExpression string
	HomescriptId   string
	Owner          string
}

type Camera

type Camera struct {
	Id     int    `json:"id"`
	RoomId string `json:"roomId"`
	Url    string `json:"url"`
	Name   string `json:"name"`
}

Camera struct, used in `config.rooms.cameras“

type DBStatus

type DBStatus struct {
	OpenConnections int `json:"openConnections"`
	InUse           int `json:""`
	Idle            int `json:""`
}

func GetDatabaseStats

func GetDatabaseStats() DBStatus

type DatabaseConfig

type DatabaseConfig struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Hostname string `json:"hostname"`
	Database string `json:"database"`
	Port     int    `json:"port"`
}

type FullUser

type FullUser struct {
	Username     string `json:"username"`
	Firstname    string `json:"firstname"`
	Surname      string `json:"surname"`
	PrimaryColor string `json:"primaryColor"`
	Password     string `json:"password"`
	AvatarPath   string `json:"avatarPath"`
}

Identified by a username, has a password and an avatar path

type HardwareNode

type HardwareNode struct {
	Name    string `json:"name"`
	Online  bool   `json:"online"`
	Enabled bool   `json:"enabled"` // Can be used to temporarely deactivate a node in case of maintenance
	Url     string `json:"url"`
	Token   string `json:"token"`
}

Hardware node

func GetHardwareNodes

func GetHardwareNodes() ([]HardwareNode, error)

Returns a list of hardware nodes

type Homescript

type Homescript struct {
	Id                  string `json:"id"`
	Owner               string `json:"owner"`
	Name                string `json:"name"`
	Description         string `json:"description"`
	QuickActionsEnabled bool   `json:"quickActionsEnabled"`
	SchedulerEnabled    bool   `json:"schedulerEnabled"`
	Code                string `json:"code"`
}

func GetUserHomescriptById

func GetUserHomescriptById(homescriptId string, username string) (Homescript, bool, error)

Returns a Homescript given its id Returns Homescript, has been found, error

func ListHomescriptFiles

func ListHomescriptFiles() ([]Homescript, error)

Lists all Homescript files in the database

func ListHomescriptOfUser

func ListHomescriptOfUser(username string) ([]Homescript, error)

Returns a list of homescripts owned by a given user

type HomescriptFrontend

type HomescriptFrontend struct {
	Name                string `json:"name"`
	Description         string `json:"description"`
	QuickActionsEnabled bool   `json:"quickActionsEnabled"`
	SchedulerEnabled    bool   `json:"schedulerEnabled"`
	Code                string `json:"code"`
}

type LogEvent

type LogEvent struct {
	Id          uint      `json:"id"`
	Name        string    `json:"name"`
	Description string    `json:"description"`
	Level       int       `json:"level"`
	Date        time.Time `json:"date"`
}

internal logging-related

func GetLogs

func GetLogs() ([]LogEvent, error)

type Notification

type Notification struct {
	Id          uint      `json:"id"`
	Priority    uint8     `json:"priority"` // Includes 1: info, 2: warning, 3: alert
	Name        string    `json:"name"`
	Description string    `json:"description"`
	Date        time.Time `json:"date"`
}

User notification

func GetUserNotifications

func GetUserNotifications(username string) ([]Notification, error)

Used when requesting the user's permissions in the frontend Returns a list containing the permissions of a given user

type Permission

type Permission struct {
	Permission  PermissionType `json:"permission"`
	Name        string         `json:"name"`
	Description string         `json:"description"`
}

This file defines which permissions exists and describes their attributes

type PermissionType

type PermissionType string
const (
	PermissionAuthentication          PermissionType = "authentication"
	PermissionSetPower                PermissionType = "setPower"
	PermissionAddLogEvent             PermissionType = "addLogEvent"
	PermissionDeleteLogs              PermissionType = "deleteLogs"
	PermissionListLogs                PermissionType = "listLogs"
	PermissionChangeAvatar            PermissionType = "changeAvatar"
	PermissionChangeUserPermissions   PermissionType = "changeUserPermissions"
	PermissionChangeSwitchPermissions PermissionType = "changeSwitchPermissions"
	PermissionGetDebugInfo            PermissionType = "getDebugInfo"
	PermissionChangeUsers             PermissionType = "changeUsers"
	PermissionListUsers               PermissionType = "listUsers"
	PermissionHomescript              PermissionType = "homescript"
	PermissionAutomation              PermissionType = "automation"

	// Dangerous
	PermissionWildCard PermissionType = "*"
)

Different types of permissions

type PowerState

type PowerState struct {
	Switch  string `json:"switch"`
	PowerOn bool   `json:"powerOn"`
}

Contains the switch id and a matching boolean Used when requesting global power states

func GetPowerStates

func GetPowerStates() ([]PowerState, error)

Returns a list of PowerStates Can return a database error

type Room

type Room struct {
	Id          string   `json:"id"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Switches    []Switch `json:"switches"`
	Cameras     []Camera `json:"cameras"`
}

Identified by a unique Id, has a Name and Description When used in config file, the Switches slice is also populated

func ListPersonalRoomsAll

func ListPersonalRoomsAll(username string) ([]Room, error)

Returns a complete list of rooms, includes metadata like switches

func ListRooms

func ListRooms() ([]Room, error)

Returns a list of rooms, excludes metadata like switches and cameras

type Switch

type Switch struct {
	Id      string `json:"id"`
	Name    string `json:"name"`
	RoomId  string `json:"roomId"`
	PowerOn bool   `json:"powerOn"`
}

Identified by a Switch Id, has a name and belongs to a room

func ListSwitches

func ListSwitches() ([]Switch, error)

Returns a list of available switches with their attributes

func ListUserSwitches

func ListUserSwitches(username string) ([]Switch, error)

Same as `ListSwitches()` but takes a user sting as a filter

type User

type User struct {
	Username     string `json:"username"`
	Firstname    string `json:"firstname"`
	Surname      string `json:"surname"`
	PrimaryColor string `json:"primaryColor"`
}

func GetUserByUsername

func GetUserByUsername(username string) (User, error)

Returns a user struct based on a username, does not check if the user exists, additional checks needed beforehand

func ListUsers

func ListUsers() ([]User, error)

Lists users which are currently in the Database Returns an empty list with an error when failing

Jump to

Keyboard shortcuts

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