database

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: MIT Imports: 10 Imported by: 0

README

database Directory

The database directory provides the core database interaction functionality for the project. It includes utilities for database connection, query execution, and ORM-like functionality for mapping database rows to Go structures.

Files

1. database.go

This file implements advanced database query execution. It features functions for running custom SQL queries and mapping the resulting rows into Go structures.

2. instance.go

Defines the logic for initializing and managing the database instance, including:

  • Initializing a connection to the database using credentials and settings from the configuration (config.Config).
  • Closing the database connection when it's no longer needed.
  • Validating the database connection via ping and retrieving metadata such as the database version.

This file uses pgxpool for connection pooling and relies on structured logging with the github.com/humanjuan/acacia package.

3. queries.go

Contains pre-defined SQL queries and data structures for mapping query results. It includes:

  • SQL query strings for operations like user login and fetching countries.
  • Data models which are used to map database rows to Go structs, using db struct tags for field mapping.

This file centralizes queries for reusability, reducing redundancy in the codebase.

4. token_repository.go

Provides functionality for handling refresh tokens in the database. This involves:

  • Storing refresh tokens securely in the database.
  • Validating and retrieving tokens based on their value.
  • Revoking tokens for a specific user when needed.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Queries = map[string]string{
	"login": `SELECT id, site_id, username, password_hash, role, status, is_global, created_at, updated_at FROM auth.users WHERE lower(username) = lower($1)`,

	"get_external_identity": `SELECT id, user_id, provider, external_id, email, metadata, created_at, updated_at 
                               FROM auth.external_identities 
                               WHERE lower(provider) = lower($1) AND external_id = $2`,
	"get_user_by_email": `SELECT id, site_id, username, password_hash, status, is_global, created_at, updated_at 
                          FROM auth.users 
                          WHERE lower(username) = lower($1)`,
	"link_external_identity": `INSERT INTO auth.external_identities (user_id, provider, external_id, email, metadata, created_at) 
                               VALUES ($1, lower($2), $3, $4, $5, NOW()) 
                               ON CONFLICT (provider, external_id) DO UPDATE SET 
                                   email = EXCLUDED.email, 
                                   metadata = EXCLUDED.metadata, 
                                   updated_at = NOW()`,
	"register_auth_event": `INSERT INTO audit.auth_events (user_id, site_id, event, ip_address, user_agent) VALUES ($1, $2, $3, $4, $5)`,

	"get_all_sites":      `SELECT id, key, host, status, created_at FROM core.sites ORDER BY created_at DESC`,
	"get_site_by_key":    `SELECT id, key, host, status, created_at FROM core.sites WHERE key = $1`,
	"create_site":        `INSERT INTO core.sites (key, host) VALUES ($1, $2)`,
	"delete_site":        `DELETE FROM core.sites WHERE key = $1`,
	"update_site_status": `UPDATE core.sites SET status = $1 WHERE key = $2`,
	"get_site_by_host":   `SELECT id FROM core.sites WHERE lower(host) = lower($1)`,

	"get_all_users":     `SELECT u.id, u.site_id, s.key as site_key, u.username, u.password_hash, u.role, u.status, u.is_global, u.created_at, u.updated_at, (u.is_external OR EXISTS(SELECT 1 FROM auth.external_identities ei WHERE ei.user_id = u.id)) as is_external FROM auth.users u LEFT JOIN core.sites s ON u.site_id = s.id ORDER BY u.created_at DESC`,
	"get_users_by_site": `SELECT DISTINCT u.id, u.site_id, s.key as site_key, u.username, u.password_hash, u.role, u.status, u.is_global, u.created_at, u.updated_at, (u.is_external OR EXISTS(SELECT 1 FROM auth.external_identities ei WHERE ei.user_id = u.id)) as is_external FROM auth.users u LEFT JOIN core.sites s ON u.site_id = s.id LEFT JOIN auth.user_allowed_sites uas ON u.id = uas.user_id WHERE u.site_id = $1 OR uas.site_id = $1 ORDER BY u.username ASC`,
	"create_user":       `INSERT INTO auth.users (site_id, username, password_hash, role, is_global, is_external) VALUES ($1, $2, $3, $4, $5, $6)`,
	"update_user_role":  `UPDATE auth.users SET role = $1, updated_at = NOW() WHERE lower(username) = lower($2)`,
	"delete_user":       `DELETE FROM auth.users WHERE lower(username) = lower($1)`,

	"store_refresh_token":     `INSERT INTO auth.refresh_tokens (token, user_id, issued_at, expires_at, revoked) VALUES ($1, $2, NOW(), $3, false)`,
	"get_refresh_token":       `SELECT id, token, user_id, revoked, expires_at FROM auth.refresh_tokens WHERE token = $1`,
	"revoke_user_tokens":      `UPDATE auth.refresh_tokens SET revoked = true WHERE user_id = $1`,
	"revoke_refresh_token_id": `UPDATE auth.refresh_tokens SET revoked = true WHERE id = $1`,

	"get_db_version":          `SELECT version()`,
	"get_user_role":           `SELECT role FROM auth.users WHERE lower(username) = lower($1)`,
	"get_user_by_username":    `SELECT id, site_id, username, role, status, is_global, theme, permissions, created_at, updated_at FROM auth.users WHERE lower(username) = lower($1)`,
	"get_user_theme":          `SELECT theme FROM auth.users WHERE lower(username) = lower($1)`,
	"update_user_theme":       `UPDATE auth.users SET theme = $1, updated_at = NOW() WHERE lower(username) = lower($2)`,
	"get_user_permissions":    `SELECT permissions FROM auth.users WHERE lower(username) = lower($1)`,
	"update_user_permissions": `UPDATE auth.users SET permissions = $1, updated_at = NOW() WHERE lower(username) = lower($2)`,
	"update_user_status":      `UPDATE auth.users SET status = $1, updated_at = NOW() WHERE lower(username) = lower($2)`,

	"count_total_users":  `SELECT count(*) FROM auth.users`,
	"count_active_sites": `SELECT count(*) FROM core.sites WHERE status = 'active'`,

	"assign_site_to_admin":   `INSERT INTO auth.admin_sites (user_id, site_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
	"revoke_site_from_admin": `DELETE FROM auth.admin_sites WHERE user_id = $1 AND site_id = $2`,
	"get_admin_sites":        `SELECT s.id, s.key, s.host, s.status, s.created_at FROM core.sites s JOIN auth.admin_sites asit ON s.id = asit.site_id WHERE asit.user_id = $1`,

	"get_api_keys":     `SELECT id, user_id, name, scopes, expires_at, last_used_at, created_at FROM auth.api_keys WHERE user_id = $1 ORDER BY created_at DESC`,
	"create_api_key":   `INSERT INTO auth.api_keys (user_id, name, key_hash, scopes, expires_at) VALUES ($1, $2, $3, $4, $5)`,
	"delete_api_key":   `DELETE FROM auth.api_keys WHERE id = $1`,
	"get_all_api_keys": `SELECT ak.id, ak.user_id, u.username, ak.name, ak.scopes, ak.expires_at, ak.last_used_at, ak.created_at FROM auth.api_keys ak JOIN auth.users u ON ak.user_id = u.id ORDER BY ak.created_at DESC`,

	"get_active_sessions": `SELECT rt.id, rt.user_id, u.username, rt.issued_at, rt.expires_at, rt.ip_address::TEXT, rt.user_agent FROM auth.refresh_tokens rt JOIN auth.users u ON rt.user_id = u.id WHERE rt.revoked = false AND rt.expires_at > NOW() ORDER BY rt.issued_at DESC`,
	"get_user_sessions":   `SELECT id, user_id, issued_at, expires_at, ip_address::TEXT, user_agent FROM auth.refresh_tokens WHERE user_id = $1 AND revoked = false AND expires_at > NOW() ORDER BY issued_at DESC`,

	"get_auth_providers":        `SELECT slug, name, enabled, client_id, client_secret, redirect_url, tenant_id, metadata::TEXT, updated_at FROM auth.providers ORDER BY name ASC`,
	"update_auth_provider":      `UPDATE auth.providers SET client_id = $1, client_secret = $2, redirect_url = $3, tenant_id = $4, updated_at = NOW() WHERE slug = $5`,
	"update_provider_status":    `UPDATE auth.providers SET enabled = $1, updated_at = NOW() WHERE slug = $2`,
	"get_auth_provider_by_slug": `SELECT slug, name, enabled, client_id, client_secret, redirect_url, tenant_id, metadata::TEXT, updated_at FROM auth.providers WHERE slug = $1`,

	"get_user_allowed_sites":        `SELECT s.id, s.key, s.host, s.status, s.created_at FROM core.sites s JOIN auth.user_allowed_sites uas ON s.id = uas.site_id WHERE uas.user_id = $1`,
	"add_allowed_site_to_user":      `INSERT INTO auth.user_allowed_sites (user_id, site_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
	"remove_allowed_site_from_user": `DELETE FROM auth.user_allowed_sites WHERE user_id = $1 AND site_id = $2`,
	"is_site_allowed_for_user":      `SELECT EXISTS(SELECT 1 FROM auth.user_allowed_sites WHERE user_id = $1 AND site_id = $2)`,
	"update_user_global_status":     `UPDATE auth.users SET is_global = $1, updated_at = NOW() WHERE lower(username) = lower($2)`,
}

Functions

This section is empty.

Types

type APIKey added in v1.6.0

type APIKey struct {
	ID         string     `db:"id"`
	UserID     string     `db:"user_id"`
	Username   string     `db:"username"`
	Name       string     `db:"name"`
	Scopes     []byte     `db:"scopes"`
	ExpiresAt  *time.Time `db:"expires_at"`
	LastUsedAt *time.Time `db:"last_used_at"`
	CreatedAt  *time.Time `db:"created_at"`
}

type AuthProvider added in v1.6.0

type AuthProvider struct {
	Slug         string     `db:"slug"`
	Name         string     `db:"name"`
	Enabled      bool       `db:"enabled"`
	ClientID     *string    `db:"client_id"`
	ClientSecret *string    `db:"client_secret"`
	RedirectURL  *string    `db:"redirect_url"`
	TenantID     *string    `db:"tenant_id"`
	Metadata     *string    `db:"metadata"`
	UpdatedAt    *time.Time `db:"updated_at"`
}

type AuthSession added in v1.6.0

type AuthSession struct {
	ID        int64      `db:"id"`
	UserID    string     `db:"user_id"`
	Username  string     `db:"username"`
	IPAddress string     `db:"ip_address"`
	UserAgent string     `db:"user_agent"`
	IssuedAt  *time.Time `db:"issued_at"`
	ExpiresAt *time.Time `db:"expires_at"`
}

type DBInstance

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

func NewDBInstance

func NewDBInstance() *DBInstance

func (*DBInstance) AddAllowedSiteToUser added in v1.6.0

func (dbi *DBInstance) AddAllowedSiteToUser(userID, siteID string) error

func (*DBInstance) AssignSiteToAdmin added in v1.6.0

func (dbi *DBInstance) AssignSiteToAdmin(userID, siteID string) error

func (*DBInstance) Close

func (dbi *DBInstance) Close()

func (*DBInstance) CreateAPIKey added in v1.6.0

func (dbi *DBInstance) CreateAPIKey(userID, name, keyHash string, scopes []byte, expiresAt *time.Time) error

func (*DBInstance) CreateSite added in v1.3.0

func (dbi *DBInstance) CreateSite(key, host string) error

func (*DBInstance) CreateUser added in v1.3.0

func (dbi *DBInstance) CreateUser(siteID *string, username, passwordHash, role string, isGlobal, isExternal bool) error

func (*DBInstance) DeleteAPIKey added in v1.6.0

func (dbi *DBInstance) DeleteAPIKey(id string) error

func (*DBInstance) DeleteSite added in v1.3.0

func (dbi *DBInstance) DeleteSite(key string) error

func (*DBInstance) DeleteUser added in v1.3.0

func (dbi *DBInstance) DeleteUser(username string) error

func (*DBInstance) Exec added in v1.6.0

func (dbi *DBInstance) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)

func (*DBInstance) GetAPIKeysByUser added in v1.6.0

func (dbi *DBInstance) GetAPIKeysByUser(userID string) ([]APIKey, error)

func (*DBInstance) GetActiveSessions added in v1.6.0

func (dbi *DBInstance) GetActiveSessions() ([]AuthSession, error)

func (*DBInstance) GetAdminSites added in v1.6.0

func (dbi *DBInstance) GetAdminSites(userID string) ([]Site, error)

func (*DBInstance) GetAllAPIKeys added in v1.6.0

func (dbi *DBInstance) GetAllAPIKeys() ([]APIKey, error)

func (*DBInstance) GetAllSites added in v1.3.0

func (dbi *DBInstance) GetAllSites() ([]Site, error)

func (*DBInstance) GetAllUsers added in v1.3.0

func (dbi *DBInstance) GetAllUsers() ([]User, error)

func (*DBInstance) GetAuthProviderBySlug added in v1.6.0

func (dbi *DBInstance) GetAuthProviderBySlug(slug string) (*AuthProvider, error)

func (*DBInstance) GetAuthProviders added in v1.6.0

func (dbi *DBInstance) GetAuthProviders() ([]AuthProvider, error)

func (*DBInstance) GetExternalIdentity added in v1.3.0

func (dbi *DBInstance) GetExternalIdentity(provider, externalID string) (*ExternalIdentity, error)

func (*DBInstance) GetExternalSessionBySessionID added in v1.6.0

func (dbi *DBInstance) GetExternalSessionBySessionID(sessionID int64) (*ExternalSession, error)

GetExternalSessionBySessionID returns the external session associated with a Golyn session id (if any)

func (*DBInstance) GetPool added in v1.3.0

func (dbi *DBInstance) GetPool() *pgxpool.Pool

func (*DBInstance) GetRefreshToken

func (dbi *DBInstance) GetRefreshToken(tokenValue string) (*Token, error)

func (*DBInstance) GetSiteByKey added in v1.3.0

func (dbi *DBInstance) GetSiteByKey(key string) (*Site, error)

func (*DBInstance) GetUserAllowedSites added in v1.6.0

func (dbi *DBInstance) GetUserAllowedSites(userID string) ([]Site, error)

func (*DBInstance) GetUserByEmail added in v1.3.0

func (dbi *DBInstance) GetUserByEmail(email string) (*User, error)

func (*DBInstance) GetUserByUsername added in v1.5.0

func (dbi *DBInstance) GetUserByUsername(username string) (*User, error)

func (*DBInstance) GetUserPermissions added in v1.4.0

func (dbi *DBInstance) GetUserPermissions(username string) ([]byte, error)

func (*DBInstance) GetUserSessions added in v1.6.0

func (dbi *DBInstance) GetUserSessions(userID string) ([]AuthSession, error)

func (*DBInstance) GetUsersBySite added in v1.3.0

func (dbi *DBInstance) GetUsersBySite(siteID string) ([]User, error)

func (*DBInstance) InitDB

func (dbi *DBInstance) InitDB(config *loaders.Database, log *acacia.Log) error

func (*DBInstance) IsSiteAllowedForUser added in v1.6.0

func (dbi *DBInstance) IsSiteAllowedForUser(userID, siteID string) (bool, error)

func (*DBInstance) LinkExternalIdentity added in v1.3.0

func (dbi *DBInstance) LinkExternalIdentity(userID, provider, externalID, email string, metadata []byte) error

func (*DBInstance) Query added in v1.6.0

func (dbi *DBInstance) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)

func (*DBInstance) QueryRow added in v1.6.0

func (dbi *DBInstance) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row

func (*DBInstance) RegisterAuthEvent added in v1.3.0

func (dbi *DBInstance) RegisterAuthEvent(userID, siteID *string, event, ip, userAgent string) error

func (*DBInstance) RemoveAllowedSiteFromUser added in v1.6.0

func (dbi *DBInstance) RemoveAllowedSiteFromUser(userID, siteID string) error

func (*DBInstance) RevokeAllUserRefreshTokens added in v1.3.0

func (dbi *DBInstance) RevokeAllUserRefreshTokens(userID string) error

func (*DBInstance) RevokeRefreshTokenByID added in v1.3.0

func (dbi *DBInstance) RevokeRefreshTokenByID(id int64) error

func (*DBInstance) RevokeSiteFromAdmin added in v1.6.0

func (dbi *DBInstance) RevokeSiteFromAdmin(userID, siteID string) error

func (*DBInstance) Select

func (dbi *DBInstance) Select(query string, result interface{}, args ...interface{}) error

func (*DBInstance) StoreExternalSession added in v1.6.0

func (dbi *DBInstance) StoreExternalSession(sessionID int64, provider, providerUserID, accessTokenEnc, refreshTokenEnc, idTokenEnc string, expiresAt *time.Time) error

StoreExternalSession saves or updates an external session bound to a Golyn session (refresh_token id)

func (*DBInstance) StoreRefreshToken

func (dbi *DBInstance) StoreRefreshToken(refreshToken, userID string, expiresAt time.Time, ip, ua string) (int64, error)

func (*DBInstance) UpdateAuthProvider added in v1.6.0

func (dbi *DBInstance) UpdateAuthProvider(slug, clientID, clientSecret, redirectURL, tenantID string) error

func (*DBInstance) UpdateAuthProviderStatus added in v1.6.0

func (dbi *DBInstance) UpdateAuthProviderStatus(slug string, enabled bool) error

func (*DBInstance) UpdateSiteStatus added in v1.4.0

func (dbi *DBInstance) UpdateSiteStatus(key, status string) error

func (*DBInstance) UpdateUserGlobalStatus added in v1.6.0

func (dbi *DBInstance) UpdateUserGlobalStatus(username string, isGlobal bool) error

func (*DBInstance) UpdateUserPermissions added in v1.4.0

func (dbi *DBInstance) UpdateUserPermissions(username string, permissions []byte) error

func (*DBInstance) UpdateUserRole added in v1.3.0

func (dbi *DBInstance) UpdateUserRole(username, role string) error

func (*DBInstance) UpdateUserStatus added in v1.4.0

func (dbi *DBInstance) UpdateUserStatus(username, status string) error

type ExternalIdentity added in v1.3.0

type ExternalIdentity struct {
	Id         string     `db:"id"`
	UserId     string     `db:"user_id"`
	Provider   string     `db:"provider"`
	ExternalId string     `db:"external_id"`
	Email      string     `db:"email"`
	Metadata   []byte     `db:"metadata"`
	CreatedAt  *time.Time `db:"created_at"`
	UpdatedAt  *time.Time `db:"updated_at"`
}

type ExternalSession added in v1.6.0

type ExternalSession struct {
	ID             string     `db:"id"`
	SessionID      int64      `db:"session_id"`
	Provider       string     `db:"provider"`
	ProviderUserID string     `db:"provider_user_id"`
	AccessToken    string     `db:"access_token"`
	RefreshToken   string     `db:"refresh_token"`
	IDToken        string     `db:"id_token"`
	ExpiresAt      *time.Time `db:"expires_at"`
	CreatedAt      *time.Time `db:"created_at"`
	UpdatedAt      *time.Time `db:"updated_at"`
}

type LoginUser

type LoginUser struct {
	Username string `json:"username"`
	Name     string `json:"name"`
	Password string `json:"password"`
}

type Site added in v1.3.0

type Site struct {
	Id        string     `db:"id"`
	Key       string     `db:"key"`
	Host      string     `db:"host"`
	Status    string     `db:"status"`
	CreatedAt *time.Time `db:"created_at"`
}

type Token

type Token struct {
	ID        int64
	UserID    string
	Token     string
	IssuedAt  time.Time
	ExpiresAt time.Time
	Revoked   bool
	IPAddress string
	UserAgent string
}

type User

type User struct {
	Id           string     `db:"id"`
	SiteID       *string    `db:"site_id"`
	SiteKey      *string    `db:"site_key"`
	Username     string     `db:"username"`
	PasswordHash string     `db:"password_hash"`
	Role         string     `db:"role"`
	Status       string     `db:"status"`
	IsGlobal     bool       `db:"is_global"`
	IsExternal   bool       `db:"is_external"`
	Theme        []byte     `db:"theme"`
	Permissions  []byte     `db:"permissions"`
	CreatedAt    *time.Time `db:"created_at"`
	UpdatedAt    *time.Time `db:"updated_at"`
}

Jump to

Keyboard shortcuts

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