database

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DB *gorm.DB

Functions

func CleanupOldData

func CleanupOldData() error

CleanupOldData removes old data based on retention policies

func Close

func Close() error

Close closes the database connection

func GetAllModels

func GetAllModels() []interface{}

GetAllModels returns all models for auto-migration

func GetDatabaseStats

func GetDatabaseStats() (map[string]interface{}, error)

GetDatabaseStats returns database statistics

func GetSystemSetting

func GetSystemSetting(key string) (string, error)

GetSystemSetting gets a system setting by key

func Initialize

func Initialize() error

Initialize sets up the database connection and runs migrations

func IsMultiUserMode

func IsMultiUserMode() bool

Helper functions IsMultiUserMode checks if multi-user mode is enabled

func MigrateToMultiUser

func MigrateToMultiUser() error

MigrateToMultiUser handles the migration from single-user to multi-user mode

func SetSystemSetting

func SetSystemSetting(key, value string, updatedBy *uuid.UUID) error

SetSystemSetting sets a system setting

Types

type APIKey

type APIKey struct {
	ID        uuid.UUID  `gorm:"type:uuid;primaryKey" json:"id"`
	UserID    uuid.UUID  `gorm:"type:uuid;not null;index" json:"user_id"`
	Name      string     `gorm:"not null" json:"name"`
	KeyHash   string     `gorm:"not null;index" json:"-"`            // Never return actual key
	KeyPrefix string     `gorm:"size:16;not null" json:"key_prefix"` // First 16 chars for display
	IsActive  bool       `gorm:"default:true" json:"is_active"`
	LastUsed  *time.Time `json:"last_used,omitempty"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	CreatedAt time.Time  `json:"created_at"`

	// Association
	User User `gorm:"foreignKey:UserID" json:"-"`
}

APIKey represents an API key for a user

func (*APIKey) BeforeCreate

func (a *APIKey) BeforeCreate(tx *gorm.DB) error

type APIKeyService

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

APIKeyService provides API key-related database operations

func NewAPIKeyService

func NewAPIKeyService(db *gorm.DB) *APIKeyService

NewAPIKeyService creates a new API key service

func (*APIKeyService) CleanupExpiredAPIKeys

func (s *APIKeyService) CleanupExpiredAPIKeys() error

CleanupExpiredAPIKeys removes expired API keys

func (*APIKeyService) CreateAPIKeyFromValue

func (s *APIKeyService) CreateAPIKeyFromValue(userID uuid.UUID, name string, apiKey string, expiresAt *time.Time) (*APIKey, error)

CreateAPIKeyFromValue creates an API key record from an existing key value (for migrations)

func (*APIKeyService) DeactivateAPIKey

func (s *APIKeyService) DeactivateAPIKey(keyID uuid.UUID, userID uuid.UUID) error

DeactivateAPIKey deactivates an API key

func (*APIKeyService) DeleteAPIKey

func (s *APIKeyService) DeleteAPIKey(keyID uuid.UUID, userID uuid.UUID) error

DeleteAPIKey permanently deletes an API key

func (*APIKeyService) GenerateAPIKey

func (s *APIKeyService) GenerateAPIKey(userID uuid.UUID, name string, expiresAt *time.Time) (*APIKey, string, error)

GenerateAPIKey creates a new API key for a user

func (*APIKeyService) GetAPIKeyByID

func (s *APIKeyService) GetAPIKeyByID(keyID uuid.UUID, userID uuid.UUID) (*APIKey, error)

GetAPIKeyByID retrieves an API key by ID (for the owner)

func (*APIKeyService) GetAPIKeyStats

func (s *APIKeyService) GetAPIKeyStats() (map[string]interface{}, error)

GetAPIKeyStats returns API key statistics

func (*APIKeyService) GetActiveUserAPIKeys

func (s *APIKeyService) GetActiveUserAPIKeys(userID uuid.UUID) ([]APIKey, error)

GetActiveUserAPIKeys retrieves all active API keys for a user

func (*APIKeyService) GetUserAPIKeys

func (s *APIKeyService) GetUserAPIKeys(userID uuid.UUID) ([]APIKey, error)

GetUserAPIKeys retrieves all API keys for a user

func (*APIKeyService) UpdateAPIKeyName

func (s *APIKeyService) UpdateAPIKeyName(keyID uuid.UUID, userID uuid.UUID, newName string) error

UpdateAPIKeyName updates the name of an API key

func (*APIKeyService) ValidateAPIKey

func (s *APIKeyService) ValidateAPIKey(apiKey string) (*User, error)

ValidateAPIKey validates an API key and returns the associated user

func (*APIKeyService) ValidateAPIKeyConstantTime

func (s *APIKeyService) ValidateAPIKeyConstantTime(providedKey string) (*User, error)

ValidateAPIKeyConstantTime validates an API key with constant time comparison

type DatabaseConfig

type DatabaseConfig struct {
	Type     string // "sqlite" or "postgres"
	Host     string
	Port     int
	User     string
	Password string
	DBName   string
	SSLMode  string
	DataDir  string // For SQLite
}

DatabaseConfig holds database configuration

func GetDatabaseConfig

func GetDatabaseConfig() *DatabaseConfig

GetDatabaseConfig reads database configuration from environment variables

type Document

type Document struct {
	ID           uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	UserID       uuid.UUID `gorm:"type:uuid;not null;index" json:"user_id"`
	DocumentName string    `gorm:"not null" json:"document_name"`
	LocalPath    string    `gorm:"size:1000" json:"local_path,omitempty"`
	RemotePath   string    `gorm:"size:1000" json:"remote_path,omitempty"`
	DocumentType string    `gorm:"size:50" json:"document_type,omitempty"`
	FileSize     int64     `json:"file_size,omitempty"`
	Status       string    `gorm:"size:50;default:uploaded" json:"status"`
	UploadDate   time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"upload_date"`

	// Association
	User User `gorm:"foreignKey:UserID" json:"-"`
}

Document represents a document uploaded/downloaded by a user

func (*Document) BeforeCreate

func (d *Document) BeforeCreate(tx *gorm.DB) error

type FolderCache

type FolderCache struct {
	ID          uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	UserID      uuid.UUID `gorm:"type:uuid;not null;index" json:"user_id"`
	FolderPath  string    `gorm:"size:1000;not null" json:"folder_path"`
	FolderData  string    `gorm:"type:text" json:"folder_data"` // JSON data
	LastUpdated time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"last_updated"`

	// Association
	User User `gorm:"foreignKey:UserID" json:"-"`
}

FolderCache represents cached folder data for a user

func (*FolderCache) BeforeCreate

func (f *FolderCache) BeforeCreate(tx *gorm.DB) error

func (FolderCache) TableName

func (FolderCache) TableName() string

Add unique constraint for user_id + folder_path

type LoginAttempt

type LoginAttempt struct {
	ID          uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	IPAddress   string    `gorm:"size:45;not null;index" json:"ip_address"`
	Username    string    `gorm:"index" json:"username,omitempty"`
	Success     bool      `gorm:"default:false" json:"success"`
	AttemptedAt time.Time `gorm:"default:CURRENT_TIMESTAMP;index" json:"attempted_at"`
	UserAgent   string    `gorm:"type:text" json:"user_agent,omitempty"`
}

LoginAttempt represents a login attempt for rate limiting

func (*LoginAttempt) BeforeCreate

func (l *LoginAttempt) BeforeCreate(tx *gorm.DB) error

type SystemSetting

type SystemSetting struct {
	Key         string     `gorm:"primaryKey" json:"key"`
	Value       string     `gorm:"type:text" json:"value"`
	Description string     `gorm:"type:text" json:"description,omitempty"`
	UpdatedAt   time.Time  `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
	UpdatedBy   *uuid.UUID `gorm:"type:uuid" json:"updated_by,omitempty"`

	// Association
	UpdatedByUser *User `gorm:"foreignKey:UpdatedBy" json:"-"`
}

SystemSetting represents system-wide configuration

type User

type User struct {
	ID       uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	Username string    `gorm:"uniqueIndex;not null" json:"username"`
	Email    string    `gorm:"uniqueIndex;not null" json:"email"`
	Password string    `gorm:"not null" json:"-"` // Never return password in JSON
	IsAdmin  bool      `gorm:"default:false" json:"is_admin"`
	IsActive bool      `gorm:"default:true" json:"is_active"`

	// User-specific settings
	RmapiHost            string  `gorm:"column:rmapi_host" json:"rmapi_host,omitempty"`
	DefaultRmdir         string  `gorm:"column:default_rmdir;default:/" json:"default_rmdir"`
	FolderRefreshPercent int     `gorm:"column:folder_refresh_percent;default:0" json:"folder_refresh_percent"`
	CoverpageSetting     string  `gorm:"column:coverpage_setting" json:"coverpage_setting"`
	PageResolution       string  `gorm:"column:page_resolution" json:"page_resolution,omitempty"`
	PageDPI              float64 `gorm:"column:page_dpi" json:"page_dpi,omitempty"`

	// Password reset
	ResetToken        string    `gorm:"index" json:"-"`
	ResetTokenExpires time.Time `json:"-"`

	// OIDC integration
	OIDCSubject *string `gorm:"uniqueIndex" json:"oidc_subject,omitempty"`

	// Timestamps
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	LastLogin *time.Time `json:"last_login,omitempty"`

	// Associations
	APIKeys      []APIKey      `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
	Sessions     []UserSession `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
	FoldersCache []FolderCache `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
	Documents    []Document    `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
}

User represents a user account in the system

func CreateDefaultAdminUser

func CreateDefaultAdminUser(username, email, password string) (*User, error)

CreateDefaultAdminUser creates a default admin user if none exists

func GetCurrentUser

func GetCurrentUser(userID uuid.UUID) (*User, error)

GetCurrentUser gets the current user from the database by ID

func GetUserByEmail

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

GetUserByEmail gets a user by email

func GetUserByUsername

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

GetUserByUsername gets a user by username

func (*User) BeforeCreate

func (u *User) BeforeCreate(tx *gorm.DB) error

BeforeCreate sets UUID and randomized folder refresh minute if not already set

type UserService

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

UserService provides user-related database operations

func NewUserService

func NewUserService(db *gorm.DB) *UserService

NewUserService creates a new user service

func (*UserService) ActivateUser

func (s *UserService) ActivateUser(userID uuid.UUID) error

ActivateUser reactivates a user

func (*UserService) AuthenticateUser

func (s *UserService) AuthenticateUser(username, password string) (*User, error)

AuthenticateUser validates user credentials and returns user if valid

func (*UserService) CleanupExpiredResetTokens

func (s *UserService) CleanupExpiredResetTokens() error

CleanupExpiredResetTokens removes expired reset tokens

func (*UserService) CleanupExpiredSessions

func (s *UserService) CleanupExpiredSessions() error

CleanupExpiredSessions removes expired sessions

func (*UserService) CreateUser

func (s *UserService) CreateUser(username, email, password string, isAdmin bool) (*User, error)

CreateUser creates a new user with hashed password

func (*UserService) DeactivateUser

func (s *UserService) DeactivateUser(userID uuid.UUID) error

DeactivateUser deactivates a user instead of deleting

func (*UserService) DeleteUser

func (s *UserService) DeleteUser(userID uuid.UUID) error

DeleteUser permanently deletes a user and all associated data

func (*UserService) GeneratePasswordResetToken

func (s *UserService) GeneratePasswordResetToken(email string) (string, error)

GeneratePasswordResetToken generates a reset token for password recovery

func (*UserService) GetAllUsers

func (s *UserService) GetAllUsers() ([]User, error)

GetAllUsers retrieves all users (for admin)

func (*UserService) GetUserByID

func (s *UserService) GetUserByID(userID uuid.UUID) (*User, error)

GetUserByID retrieves a user by ID

func (*UserService) GetUserStats

func (s *UserService) GetUserStats(userID uuid.UUID) (map[string]interface{}, error)

GetUserStats returns user statistics

func (*UserService) SetUserAdmin

func (s *UserService) SetUserAdmin(userID uuid.UUID, isAdmin bool) error

SetUserAdmin sets or removes admin privileges

func (*UserService) UpdateUserPassword

func (s *UserService) UpdateUserPassword(userID uuid.UUID, newPassword string) error

UpdateUserPassword updates a user's password

func (*UserService) UpdateUserSettings

func (s *UserService) UpdateUserSettings(userID uuid.UUID, settings map[string]interface{}) error

UpdateUserSettings updates user-specific settings

func (*UserService) ValidatePasswordResetToken

func (s *UserService) ValidatePasswordResetToken(token string) (*User, error)

ValidatePasswordResetToken validates a reset token and returns the user

type UserSession

type UserSession struct {
	ID        uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	UserID    uuid.UUID `gorm:"type:uuid;not null;index" json:"user_id"`
	TokenHash string    `gorm:"not null;index" json:"-"`
	ExpiresAt time.Time `gorm:"not null" json:"expires_at"`
	CreatedAt time.Time `json:"created_at"`
	LastUsed  time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"last_used"`
	UserAgent string    `gorm:"type:text" json:"user_agent,omitempty"`
	IPAddress string    `gorm:"size:45" json:"ip_address,omitempty"`

	// Association
	User User `gorm:"foreignKey:UserID" json:"-"`
}

UserSession represents a user's login session

func (*UserSession) BeforeCreate

func (s *UserSession) BeforeCreate(tx *gorm.DB) error

Jump to

Keyboard shortcuts

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