db

package
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2023 License: GPL-3.0 Imports: 19 Imported by: 0

Documentation

Overview

Package db stores and manipulates dotfiles via a sqlite3 database.

Index

Constants

View Source
const (
	// DefaultLimit is the default limit for paginated queries.
	DefaultLimit = 100
	// MaxLimit is the max limit for paginated queries.
	MaxLimit = 500
)

Variables

View Source
var Connection *sql.DB

Connection is a global database connection. Call Start() to initialize.

Functions

func CheckPassword

func CheckPassword(e Executor, username, password string) error

CheckPassword checks username and password combination. Tells the user when the password does not match.

func CheckPasswordResetToken

func CheckPasswordResetToken(e Executor, token string) (string, error)

CheckPasswordResetToken checks if the password reset token exists. Returns username for the token on success.

func ClearCommits

func ClearCommits(tx *sql.Tx, username, alias string) error

ClearCommits deletes all commits for a file except the current.

func Close

func Close()

Close closes the connection.

func DeleteFile

func DeleteFile(tx *sql.Tx, username, alias string) error

DeleteFile deletes a users file.

func DeleteTempFile

func DeleteTempFile(e Executor, username string) error

DeleteTempFile deletes a users temp file.

func DeleteUser

func DeleteUser(username, password string) error

DeleteUser deletes a user and their data.

func FileData

func FileData(e Executor, username, alias string) (*dotfile.TrackingData, error)

FileData returns the files dotfile data structure.

func ForkFile

func ForkFile(username, alias, hash string, newUserID int64) error

ForkFile creates a copy of username/alias/hash for the user newUserID.

func InitOrCommit

func InitOrCommit(userID int64, alias, message string) error

InitOrCommit uses the content in a temp file to initialize a file or create a new commit.

func Logout

func Logout(e Executor, session string) error

Logout sets the session to deleted.

func NotFound

func NotFound(err error) bool

NotFound returns whether err is wrapping a no rows error.

func ResetPassword

func ResetPassword(e Executor, token, newPassword string) (string, error)

ResetPassword hashes and sets a new password to the user with the password reset token.

func Rollback

func Rollback(tx *sql.Tx, err error) error

Rollback reverts a database transaction. Always returns an error.

func RotateCLIToken

func RotateCLIToken(e Executor, userID int64, currentToken string) error

RotateCLIToken creates a new CLI token for the user.

func SeedReservedUsernames

func SeedReservedUsernames(e Executor, usernames []interface{}) error

SeedReservedUsernames sets usernames which are not allowed to be used. This should be called when the service is started.

func SetFileToHash

func SetFileToHash(e Executor, username, alias, hash string) error

SetFileToHash sets file to the commit at hash.

func SetPasswordResetToken

func SetPasswordResetToken(e Executor, email string) (string, error)

SetPasswordResetToken creates and saves a reset token for the user. Returns the newly created token.

func Start

func Start(dbPath string) (err error)

Start opens a connection a sqlite3 database. Creates a new sqlite database with all required tables when not found. Create an in memory database when dbPath is empty.

func UpdateEmail

func UpdateEmail(e Executor, userID int64, email string) error

UpdateEmail updates a users email and sets email_confirmed to false.

func UpdatePassword

func UpdatePassword(e Executor, username string, currentPass, newPassword string) error

UpdatePassword updates a users password. currentPass must match the current hash.

func UpdateTheme

func UpdateTheme(e Executor, userID int64, theme UserTheme) error

UpdateTheme updates a users theme setting.

func UpdateTimezone

func UpdateTimezone(e Executor, userID int64, timezone string) error

UpdateTimezone checks if the timezone is able to be loaded and updates the user record.

func UserLoginAPI

func UserLoginAPI(e Executor, username, cliToken string) (int64, error)

UserLoginAPI checks a username and CLI token combination.

func ValidateFileNotExists

func ValidateFileNotExists(e Executor, userID int64, alias, path string) error

ValidateFileNotExists validates that no other file for user exists with alias or path.

func ValidateUserExists

func ValidateUserExists(e Executor, username string) error

ValidateUserExists throws a sql.ErrNoRows when the username does not exist.

Types

type CommitRecord

type CommitRecord struct {
	ID         int64
	ForkedFrom *int64 // A commit id.
	FileID     int64  `validate:"required"`
	Hash       string `validate:"required"` // Hash of the uncompressed file.
	Message    string
	Revision   []byte `validate:"required"` // Compressed version of file at hash.
	Timestamp  int64  `validate:"required"` // Unix time to stay synced with local commits.
}

CommitRecord models the commits table.

func Commit

func Commit(e Executor, username, alias, hash string) (*CommitRecord, error)

Commit returns the commit record.

type CommitSummary

type CommitSummary struct {
	Hash               string
	Message            string
	Current            bool
	Timestamp          int64
	DateString         string
	ForkedFromUsername *string // The owner of the file that this commit was forked from.

}

CommitSummary summarizes a commit.

func CommitList

func CommitList(e Executor, username, alias string, timezone *string) ([]CommitSummary, error)

CommitList gets a summary of all commits for a file.

type CommitView

type CommitView struct {
	CommitSummary
	Path    string
	Content []byte
}

CommitView is used for an individual commit view.

func UncompressCommit

func UncompressCommit(e Executor, username, alias, hash string, timezone *string) (*CommitView, error)

UncompressCommit gets a commit and uncompresses its contents.

type Executor

type Executor interface {
	Exec(string, ...interface{}) (sql.Result, error)
	Query(string, ...interface{}) (*sql.Rows, error)
	QueryRow(string, ...interface{}) *sql.Row
}

Executor is an interface for executing SQL.

type FileContent

type FileContent struct {
	Username   string
	UserID     int64
	Alias      string
	Connection Executor
}

FileContent implements file.Getter. It pulls content from temp_files and commits.

func (*FileContent) DirtyContent

func (fc *FileContent) DirtyContent() ([]byte, error)

DirtyContent returns content from the users temp file. Returns nil when UserID is not set - this is so that only file owners can see their temp.

func (*FileContent) Revision

func (fc *FileContent) Revision(hash string) ([]byte, error)

Revision returns the compressed content at hash.

type FileRecord

type FileRecord struct {
	ID              int64
	UserID          int64  `validate:"required"`
	Alias           string `validate:"required"` // Friendly name for a file: bashrc
	Path            string `validate:"required"` // Where the file lives: ~/.bashrc
	CurrentCommitID *int64 // The commit that the file is at.
}

FileRecord models the files table. It stores the contents of a file at the current revision hash.

Both aliases and paths must be unique for each user.

func File

func File(e Executor, username string, alias string) (*FileRecord, error)

File retrieves a file record.

func (*FileRecord) Update

func (f *FileRecord) Update(e Executor, newAlias, newPath string) error

Update updates the alias or path if they are different.

type FileSearchResult

type FileSearchResult struct {
	Username        string
	Alias           string
	Path            string
	UpdatedAtString string
	UpdatedAt       time.Time
}

FileSearchResult is the result of a file search.

func FileFeed added in v1.0.4

func FileFeed(e Executor, n int, timezone *string) ([]FileSearchResult, error)

FileFeed returns n of the most recently updated files.

type FileSummary

type FileSummary struct {
	Alias      string
	Path       string
	NumCommits int
	UpdatedAt  string
}

FileSummary summarizes a file.

func FilesByUsername

func FilesByUsername(e Executor, username string, timezone *string) ([]FileSummary, error)

FilesByUsername returns all of a users files.

type FileTransaction

type FileTransaction struct {
	FileExists      bool
	FileID          int64
	CurrentCommitID int64
	Hash            string
	Path            string
	Staged          *TempFileRecord
	// contains filtered or unexported fields
}

FileTransaction implements dotfile interfaces. This should be created with one of the exported functions not a literal.

func NewFileTransaction

func NewFileTransaction(tx *sql.Tx, userID int64, alias string) (*FileTransaction, error)

NewFileTransaction loads file information into a file transaction. Exported fields will be zero valued when the file doesn't exist.

func StageFile

func StageFile(tx *sql.Tx, userID int64, alias string) (*FileTransaction, error)

StageFile returns a file transaction loaded with a users temp file. Returns an error when the temp file does not exist.

func (*FileTransaction) DirtyContent

func (ft *FileTransaction) DirtyContent() ([]byte, error)

DirtyContent returns the bytes from the users temp file. Returns an error if the temp file is not set.

func (*FileTransaction) HasCommit

func (ft *FileTransaction) HasCommit(hash string) (exists bool, err error)

HasCommit returns whether the file has a commit with hash.

func (*FileTransaction) InsertCommit

func (ft *FileTransaction) InsertCommit(buff *bytes.Buffer, c *dotfile.Commit) (int64, error)

InsertCommit saves a new commit without changing the files current revision.

func (*FileTransaction) Revision

func (ft *FileTransaction) Revision(hash string) ([]byte, error)

Revision returns the compressed content at hash.

func (*FileTransaction) SaveCommit

func (ft *FileTransaction) SaveCommit(buff *bytes.Buffer, c *dotfile.Commit) error

SaveCommit saves a commit to the database. Sets the files current revision to the new commit.

func (*FileTransaction) SaveFile

func (ft *FileTransaction) SaveFile(userID int64, alias, path string) error

SaveFile saves a new file that does yet have any commits. Callers should call SaveCommit in the same transaction.

func (*FileTransaction) SetRevision

func (ft *FileTransaction) SetRevision(hash string) error

SetRevision sets the file to the commit at hash.

type FileView

type FileView struct {
	FileRecord
	Content []byte
	Hash    string
}

FileView contains a file record and its uncompressed content.

func UncompressFile

func UncompressFile(e Executor, username string, alias string) (*FileView, error)

UncompressFile gets a file and uncompresses its current commit.

type HTMLTable

type HTMLTable struct {
	Columns  []string
	Rows     []interface{}
	Controls *PageControls
}

HTMLTable contains methods for generating HTML output from rows and columns.

func SearchFiles

func SearchFiles(e Executor, controls *PageControls, timezone *string) (*HTMLTable, error)

SearchFiles looks for files by their alias or path.

func (*HTMLTable) Header

func (h *HTMLTable) Header() template.HTML

Header returns table headers tags with links for setting order.

func (*HTMLTable) Pages

func (h *HTMLTable) Pages() template.HTML

Pages returns a series of <a> tags that link to the first, last, and surrounding pages.

func (*HTMLTable) Query

func (h *HTMLTable) Query() string

Query returns the current query, 'q'.

func (*HTMLTable) TotalRows

func (h *HTMLTable) TotalRows() int

TotalRows returns the total amount of rows available.

type PageControls

type PageControls struct {
	Values url.Values
	// contains filtered or unexported fields
}

PageControls maps url queries to query parameters.

func (*PageControls) Set

func (p *PageControls) Set() error

Set sets private attributes from Values. This must be called before other methods.

query: 'q' page: 'p' order: 'o' order by: 'ob' limit: 'l'

type ReservedUsernameRecord

type ReservedUsernameRecord struct {
	Username  string
	CreatedAt time.Time
}

ReservedUsernameRecord models the reserved_usernames table. It stores usernames that are not allowed to be registered.

type SessionRecord

type SessionRecord struct {
	ID        int64
	Session   string `validate:"required"`
	UserID    int64  `validate:"required"`
	IP        string
	CreatedAt time.Time
	DeletedAt *time.Time
}

SessionRecord models the sessions table. It tracks a user's active sessions.

func UserLogin

func UserLogin(e Executor, username, password, ip string) (*SessionRecord, error)

UserLogin checks a username / password. If the credentials are valid, returns a new session.

type TempFileRecord

type TempFileRecord struct {
	ID        int64
	UserID    int64  `validate:"required"`
	Alias     string `validate:"required"`
	Path      string `validate:"required"`
	Content   []byte `validate:"required"`
	CreatedAt time.Time
}

TempFileRecord models the temp_files table. It represents a changed/new file that has not yet been committed. Similar to an untracked or dirty file on the filesystem. This allows users to stage a file and view the result before saving. A User can have a single TempFile.

func TempFile

func TempFile(e Executor, userID int64, alias string) (*TempFileRecord, error)

TempFile finds a user's temp file. Users can only have one temp file at a time so alias can be empty. When alias is present, ensures that temp file exists with alias.

func (*TempFileRecord) Create

func (f *TempFileRecord) Create(e Executor) error

Create inserts or replaces a user's previous temp file. Strips carriage returns from content.

type UserRecord

type UserRecord struct {
	ID                 int64
	Username           string `validate:"alphanum"`
	Email              string `validate:"omitempty,email"` // Not required; users may opt in to enable account recovery.
	EmailConfirmed     bool
	PasswordHash       []byte
	CLIToken           string `validate:"required"` // Allows CLI to write to server.
	PasswordResetToken *string
	Theme              string
	Timezone           string
	CreatedAt          string
}

UserRecord models the user table.

func CreateUser

func CreateUser(e Executor, username, email, password string) (*UserRecord, error)

CreateUser inserts a new user into the users table.

type UserSession

type UserSession struct {
	Session       string
	IP            string
	UserID        int64
	Username      string
	Email         *string
	CLIToken      string
	Timezone      *string
	Theme         UserTheme
	UserCreatedAt string
}

UserSession is a model for joining the users and sessions tables.

func Session

func Session(e Executor, session string) (*UserSession, error)

Session finds a user with session.

type UserTheme

type UserTheme string

UserTheme is a users theme preference.

const (
	UserThemeLight UserTheme = "Light"
	UserThemeDark  UserTheme = "Dark"
)

Valid Values for UserTheme.

Jump to

Keyboard shortcuts

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