db

package
v0.0.0-...-e5d423c Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package db provides self-healing functions for database integrity.

This file implements automatic repair of catalog_template_id references in installed_applications table.

Package db provides PostgreSQL database access and management for StreamSpace.

This file implements installed application management and access control.

Purpose: - CRUD operations for installed applications - Application configuration management - Group-based access control for applications - Application enable/disable functionality

Features: - Install applications from catalog templates - Custom display names for user dashboard - Configuration storage in JSONB - Group access permissions - Enable/disable applications

Database Schema:

  • installed_applications table: Installed application instances

  • id (varchar): Primary key (UUID)

  • catalog_template_id (int): Foreign key to catalog_templates

  • name (varchar): Internal name with GUID suffix

  • display_name (varchar): Custom display name for dashboard

  • folder_path (varchar): Path to configuration folder

  • enabled (boolean): Whether application is active

  • configuration (jsonb): Application-specific settings

  • created_by (varchar): User who installed the application

  • created_at, updated_at: Timestamps

  • application_group_access table: Group permissions for applications

  • id (varchar): Primary key (UUID)

  • application_id (varchar): Foreign key to installed_applications

  • group_id (varchar): Foreign key to groups

  • access_level (varchar): Permission level (view, launch, admin)

  • created_at: When access was granted

Thread Safety: - All database operations are thread-safe via database/sql pool

Example Usage:

appDB := db.NewApplicationDB(database.DB())

// Install application
app, err := appDB.InstallApplication(ctx, &models.InstallApplicationRequest{
    CatalogTemplateID: 1,
    DisplayName:       "Firefox Browser",
})

// Grant group access
err := appDB.AddGroupAccess(ctx, appID, groupID, "launch")

// Enable/disable application
err := appDB.SetApplicationEnabled(ctx, appID, true)

Package db provides PostgreSQL database access and management for StreamSpace.

This file implements the core database connection and lifecycle management.

Purpose: - Establish and maintain PostgreSQL connection pool - Initialize database schema on startup (82+ tables) - Provide centralized database instance for all API handlers - Execute raw SQL queries and transactions - Validate database configuration for security

Features: - Connection pooling with configurable limits (25 max open, 5 max idle) - Comprehensive schema migrations (82+ tables, 200+ indexes) - Health check and ping capabilities - Graceful connection cleanup on shutdown - Configuration validation (prevents SQL injection in connection strings) - SSL/TLS warnings for production security

Database Schema:

  • 82+ tables covering users, sessions, templates, plugins, quotas, audit logs
  • 200+ indexes for query performance optimization
  • JSONB columns for flexible metadata storage
  • Foreign key constraints for referential integrity
  • Composite indexes for common query patterns

Implementation Details: - Uses database/sql with lib/pq PostgreSQL driver - Connection pool configured for optimal performance (5min max lifetime) - Schema initialization runs CREATE TABLE IF NOT EXISTS on startup - Thread-safe connection pooling handled by database/sql package - Validates hostname, port, username, database name, SSL mode

Thread Safety: - Database connections are thread-safe and managed by database/sql pool - Safe for concurrent use across multiple goroutines - Connection pool prevents resource exhaustion

Dependencies: - PostgreSQL 12+ (required) - lib/pq driver for database/sql

Example Usage:

config := db.Config{
    Host:     "localhost",
    Port:     "5432",
    User:     "streamspace",
    Password: "secretpassword",
    DBName:   "streamspace",
    SSLMode:  "require",
}

database, err := db.NewDatabase(config)
if err != nil {
    log.Fatal(err)
}
defer database.Close()

// Run migrations
if err := database.Migrate(); err != nil {
    log.Fatal(err)
}

// Use database connection
rows, err := database.DB().Query("SELECT * FROM users")

Package db provides PostgreSQL database access and management for StreamSpace.

This file implements group management and authorization data access.

Purpose: - CRUD operations for user groups - Group-based access control and permissions - Group quota and resource limit management - User-to-group membership mapping - Group hierarchy support (parent/child groups)

Features: - Group-based resource quotas - Group permissions and role-based access - User membership tracking with roles - Group search and filtering by type/parent - Quota inheritance from groups to users - Member count aggregation

Database Schema:

  • groups table: Group definitions and metadata

  • id (varchar): Primary key (UUID)

  • name (varchar): Unique group name

  • display_name (varchar): Human-readable name

  • description (text): Group purpose description

  • type (varchar): Group type (team, department, etc.)

  • parent_id (varchar): Optional parent group for hierarchy

  • created_at, updated_at: Timestamps

  • group_memberships table: User-to-group junction

  • id (varchar): Primary key

  • user_id (varchar): Foreign key to users

  • group_id (varchar): Foreign key to groups

  • role (varchar): Member role (owner, admin, member)

  • created_at: When user joined

  • group_quotas table: Resource limits per group

  • group_id: Foreign key to groups

  • max_sessions, max_cpu, max_memory, max_storage: Limits

  • used_sessions, used_cpu, used_memory, used_storage: Current usage

Quota Hierarchy:

  1. User-specific quotas (most restrictive wins)
  2. Group quotas (applied to all group members)
  3. Platform defaults (fallback)

Implementation Details: - Groups can have resource quotas that apply to all members - Most restrictive quota wins (user vs group vs platform) - Quota stored as separate table with foreign key constraint - Supports hierarchical groups with parent_id - Member counts calculated via JOIN for efficiency

Thread Safety: - All database operations are thread-safe via database/sql pool - Safe for concurrent access from multiple goroutines

Dependencies: - github.com/google/uuid for ID generation - models package for data structures

Example Usage:

groupDB := db.NewGroupDB(database.DB())

// Create group
group, err := groupDB.CreateGroup(ctx, &models.CreateGroupRequest{
    Name:        "developers",
    DisplayName: "Developers",
    Description: "Development team",
    Type:        "team",
})

// Set group quota
maxSessions := 20
err := groupDB.SetGroupQuota(ctx, groupID, &models.SetQuotaRequest{
    MaxSessions: &maxSessions,
})

// Add user to group
err := groupDB.AddGroupMember(ctx, groupID, &models.AddGroupMemberRequest{
    UserID: userID,
    Role:   "member",
})

Package db provides PostgreSQL database access for StreamSpace.

This file implements session management operations for multi-platform support. Sessions are the source of truth in the database, updated by controller status events.

Package db provides PostgreSQL database access and management for StreamSpace.

This file defines team-related data structures for team management and collaboration.

Purpose: - Define team membership data structures - Define team role permission structures - Support team-based organization and collaboration

Features: - Team membership tracking with roles - Role-based permission system - Team hierarchy support

Data Structures:

  • TeamMembership: Represents a user's membership in a team
  • TeamPermission: Defines permissions for team roles
  • TeamRoleInfo: Aggregates role information with permissions

Team Roles:

  • owner: Full control (manage team, members, sessions, quotas)
  • admin: Administrative access (manage members, sessions)
  • member: Standard access (create sessions, view team data)
  • viewer: Read-only access (view sessions and quotas)

Implementation Details: - This file contains only type definitions - Actual database operations are in groups.go (teams are a type of group) - Team roles and permissions stored in team_role_permissions table - Initialized with default permissions during database migration

Example Usage:

membership := &TeamMembership{
    TeamID:          "team-abc",
    TeamName:        "frontend-team",
    TeamDisplayName: "Frontend Team",
    TeamType:        "team",
    Role:            "member",
    JoinedAt:        time.Now(),
}

Package db provides PostgreSQL database access and management for StreamSpace.

This file implements user management and authentication data access.

Purpose: - CRUD operations for user accounts - Password hashing and verification with bcrypt - User authentication and authorization - User quota and resource limit management - User preferences and settings storage - Group membership management

Features: - Secure password hashing with bcrypt (cost factor 10) - User search and filtering by username/email/role/provider - Quota enforcement integration with quota system - User group membership tracking - OAuth provider linking (OIDC, SAML) - MFA (TOTP) configuration storage support - Last login tracking for auditing

Database Schema:

  • users table: Core user account data

  • id (varchar): Primary key (UUID)

  • username (varchar): Unique username

  • email (varchar): Unique email address

  • password_hash (varchar): bcrypt hashed password (local auth only)

  • role (varchar): User role (user, admin, superadmin)

  • provider (varchar): Auth provider (local, saml, oidc)

  • active (boolean): Account active status

  • created_at, updated_at: Timestamps

  • last_login: Last successful authentication

  • user_quotas table: Resource limits per user

  • user_id: Foreign key to users

  • max_sessions, max_cpu, max_memory, max_storage: Limits

  • used_sessions, used_cpu, used_memory, used_storage: Current usage

Implementation Details: - Passwords never stored in plaintext (bcrypt with cost 10) - User lookups indexed by username and email for performance - Quota stored as separate table with foreign key constraint - Group membership managed via group_memberships junction table - Default quota created automatically on user creation - Supports multiple authentication providers (local, SAML, OIDC)

Thread Safety: - All database operations are thread-safe via database/sql pool - Safe for concurrent access from multiple goroutines - bcrypt operations are CPU-intensive but safe for concurrent use

Dependencies: - golang.org/x/crypto/bcrypt for password hashing - github.com/google/uuid for ID generation - models package for data structures

Example Usage:

userDB := db.NewUserDB(database.DB())

// Create user with password
user, err := userDB.CreateUser(ctx, &models.CreateUserRequest{
    Username: "alice",
    Email:    "alice@example.com",
    Password: "securepassword",
    FullName: "Alice Smith",
    Role:     "user",
    Provider: "local",
})

// Authenticate user
user, err := userDB.VerifyPassword(ctx, "alice", "securepassword")

// Update user quota
maxSessions := 10
err := userDB.SetUserQuota(ctx, userID, &models.SetQuotaRequest{
    MaxSessions: &maxSessions,
})

// Get or create SAML user (SSO)
user, err := userDB.GetOrCreateSAMLUser(ctx, "bob", "bob@company.com", "Bob Jones", "saml-provider")

Index

Constants

This section is empty.

Variables

View Source
var ErrUserNotFound = fmt.Errorf("user not found")

ErrUserNotFound is returned when a user is not found

Functions

This section is empty.

Types

type ApplicationDB

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

ApplicationDB handles database operations for installed applications

func NewApplicationDB

func NewApplicationDB(db *sql.DB) *ApplicationDB

NewApplicationDB creates a new ApplicationDB instance

func (*ApplicationDB) AddGroupAccess

func (a *ApplicationDB) AddGroupAccess(ctx context.Context, appID, groupID, accessLevel string) error

AddGroupAccess grants a group access to an application

func (*ApplicationDB) DeleteApplication

func (a *ApplicationDB) DeleteApplication(ctx context.Context, appID string) error

DeleteApplication deletes an installed application

func (*ApplicationDB) GetApplication

func (a *ApplicationDB) GetApplication(ctx context.Context, appID string) (*models.InstalledApplication, error)

GetApplication retrieves an installed application by ID

func (*ApplicationDB) GetApplicationGroups

func (a *ApplicationDB) GetApplicationGroups(ctx context.Context, appID string) ([]*models.ApplicationGroupAccess, error)

GetApplicationGroups retrieves all groups with access to an application

func (*ApplicationDB) GetApplicationTemplateConfig

func (a *ApplicationDB) GetApplicationTemplateConfig(ctx context.Context, appID string) (map[string]interface{}, error)

GetApplicationTemplateConfig retrieves the template's configurable options

func (*ApplicationDB) GetUserAccessibleApplications

func (a *ApplicationDB) GetUserAccessibleApplications(ctx context.Context, userID string) ([]*models.InstalledApplication, error)

GetUserAccessibleApplications retrieves applications accessible to a user (via their groups, as creator, or public)

func (*ApplicationDB) HasGroupAccess

func (a *ApplicationDB) HasGroupAccess(ctx context.Context, appID, groupID string) (bool, error)

HasGroupAccess checks if a group has access to an application

func (a *ApplicationDB) HealApplicationCatalogLinks(ctx context.Context) (int, error)

HealApplicationCatalogLinks repairs installed_applications with NULL catalog_template_id.

This function: 1. Finds all applications with catalog_template_id = NULL 2. Attempts to match them to catalog_templates by name prefix 3. Updates the database with the correct template ID

This is a self-healing mechanism for the architectural issue where applications lose their template link. It should run on API startup.

Returns the number of applications healed and any error encountered.

func (*ApplicationDB) InstallApplication

InstallApplication installs a new application from the catalog

func (*ApplicationDB) ListApplications

func (a *ApplicationDB) ListApplications(ctx context.Context, enabledOnly bool) ([]*models.InstalledApplication, error)

ListApplications retrieves all installed applications with optional filtering

func (*ApplicationDB) RemoveGroupAccess

func (a *ApplicationDB) RemoveGroupAccess(ctx context.Context, appID, groupID string) error

RemoveGroupAccess removes a group's access to an application

func (*ApplicationDB) SetApplicationEnabled

func (a *ApplicationDB) SetApplicationEnabled(ctx context.Context, appID string, enabled bool) error

SetApplicationEnabled enables or disables an application

func (*ApplicationDB) UpdateApplication

func (a *ApplicationDB) UpdateApplication(ctx context.Context, appID string, req *models.UpdateApplicationRequest) error

UpdateApplication updates an installed application

func (*ApplicationDB) UpdateGroupAccessLevel

func (a *ApplicationDB) UpdateGroupAccessLevel(ctx context.Context, appID, groupID, accessLevel string) error

UpdateGroupAccessLevel updates a group's access level for an application

type Config

type Config struct {
	Host     string
	Port     string
	User     string
	Password string
	DBName   string
	SSLMode  string
}

Config holds database configuration

type Database

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

Database represents the database connection

func NewDatabase

func NewDatabase(config Config) (*Database, error)

NewDatabase creates a new database connection with connection pooling

func NewDatabaseForTesting

func NewDatabaseForTesting(db *sql.DB) *Database

NewDatabaseForTesting creates a Database from an existing sql.DB connection. This constructor is intended ONLY FOR TESTING to enable dependency injection with mock databases (e.g., sqlmock).

DO NOT use this in production code. Use NewDatabase() instead.

Example usage in tests:

db, mock, err := sqlmock.New()
database := db.NewDatabaseForTesting(db)
handler := &AuditHandler{database: database}
// ... setup mock expectations and run tests

func (*Database) Close

func (d *Database) Close() error

Close closes the database connection

func (*Database) DB

func (d *Database) DB() *sql.DB

DB returns the underlying sql.DB

func (*Database) Migrate

func (d *Database) Migrate() error

Migrate runs database migrations

type GroupDB

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

GroupDB handles database operations for groups

func NewGroupDB

func NewGroupDB(db *sql.DB) *GroupDB

NewGroupDB creates a new GroupDB instance

func (*GroupDB) AddGroupMember

func (g *GroupDB) AddGroupMember(ctx context.Context, groupID string, req *models.AddGroupMemberRequest) error

AddGroupMember adds a user to a group

func (*GroupDB) CreateGroup

func (g *GroupDB) CreateGroup(ctx context.Context, req *models.CreateGroupRequest) (*models.Group, error)

CreateGroup creates a new group

func (*GroupDB) DeleteGroup

func (g *GroupDB) DeleteGroup(ctx context.Context, groupID string) error

DeleteGroup deletes a group

func (*GroupDB) GetGroup

func (g *GroupDB) GetGroup(ctx context.Context, groupID string) (*models.Group, error)

GetGroup retrieves a group by ID

func (*GroupDB) GetGroupByName

func (g *GroupDB) GetGroupByName(ctx context.Context, name string) (*models.Group, error)

GetGroupByName retrieves a group by name

func (*GroupDB) GetGroupMembers

func (g *GroupDB) GetGroupMembers(ctx context.Context, groupID string) ([]*models.GroupMembership, error)

GetGroupMembers retrieves all members of a group

func (*GroupDB) GetGroupQuota

func (g *GroupDB) GetGroupQuota(ctx context.Context, groupID string) (*models.GroupQuota, error)

GetGroupQuota retrieves quota for a group

func (*GroupDB) IsGroupMember

func (g *GroupDB) IsGroupMember(ctx context.Context, groupID, userID string) (bool, error)

IsGroupMember checks if a user is a member of a group

func (*GroupDB) ListGroups

func (g *GroupDB) ListGroups(ctx context.Context, groupType string, parentID *string) ([]*models.Group, error)

ListGroups retrieves all groups with optional filtering

func (*GroupDB) RemoveGroupMember

func (g *GroupDB) RemoveGroupMember(ctx context.Context, groupID, userID string) error

RemoveGroupMember removes a user from a group

func (*GroupDB) SetGroupQuota

func (g *GroupDB) SetGroupQuota(ctx context.Context, groupID string, req *models.SetQuotaRequest) error

SetGroupQuota sets or updates quota for a group

func (*GroupDB) UpdateGroup

func (g *GroupDB) UpdateGroup(ctx context.Context, groupID string, req *models.UpdateGroupRequest) error

UpdateGroup updates group information

func (*GroupDB) UpdateGroupMemberRole

func (g *GroupDB) UpdateGroupMemberRole(ctx context.Context, groupID, userID, role string) error

UpdateGroupMemberRole updates a member's role in a group

func (*GroupDB) UpdateGroupQuotaUsage

func (g *GroupDB) UpdateGroupQuotaUsage(ctx context.Context, groupID string, sessions int, cpu, memory, storage string) error

UpdateGroupQuotaUsage updates the current usage for a group's quota

type InstallApplicationParams

type InstallApplicationParams struct {
	CatalogTemplateID int
	DisplayName       string
	Description       string
	Category          string
	IconURL           string
	IconData          []byte
	IconMediaType     string
	Manifest          string
	Configuration     map[string]interface{}
}

InstallApplicationParams contains all data needed to install an application

type Session

type Session struct {
	ID                 string     `json:"id"`
	UserID             string     `json:"user_id"`
	OrgID              string     `json:"org_id"` // Organization ID for multi-tenancy
	TeamID             string     `json:"team_id,omitempty"`
	TemplateName       string     `json:"template_name"`
	State              string     `json:"state"` // running, hibernated, terminated, pending, failed
	AppType            string     `json:"app_type"`
	ActiveConnections  int        `json:"active_connections"`
	URL                string     `json:"url,omitempty"`
	Namespace          string     `json:"namespace"`
	Platform           string     `json:"platform"`
	AgentID            string     `json:"agent_id,omitempty"`   // v2.0-beta: Agent managing this session
	ClusterID          string     `json:"cluster_id,omitempty"` // v2.0-beta: Cluster where session runs
	PodName            string     `json:"pod_name,omitempty"`
	Memory             string     `json:"memory,omitempty"`
	CPU                string     `json:"cpu,omitempty"`
	PersistentHome     bool       `json:"persistent_home"`
	IdleTimeout        string     `json:"idle_timeout,omitempty"`
	MaxSessionDuration string     `json:"max_session_duration,omitempty"`
	Tags               []string   `json:"tags,omitempty"` // Session tags for filtering and organization
	CreatedAt          time.Time  `json:"created_at"`
	UpdatedAt          time.Time  `json:"updated_at"`
	LastConnection     *time.Time `json:"last_connection,omitempty"`
	LastDisconnect     *time.Time `json:"last_disconnect,omitempty"`
	LastActivity       *time.Time `json:"last_activity,omitempty"`
	StreamingProtocol  string     `json:"streaming_protocol"`       // selkies (only supported protocol)
	StreamingPort      int        `json:"streaming_port"`           // Port for streaming service
	StreamingPath      string     `json:"streaming_path,omitempty"` // URL path for HTTP-based protocols
}

Session represents a StreamSpace session in the database. This mirrors the k8s.Session structure for API compatibility.

MULTI-TENANCY: The OrgID field is CRITICAL for tenant isolation. All queries MUST filter by org_id to prevent cross-tenant access.

type SessionDB

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

SessionDB handles database operations for sessions.

func NewSessionDB

func NewSessionDB(db *sql.DB) *SessionDB

NewSessionDB creates a new SessionDB instance.

func (*SessionDB) CountSessionsByUser

func (s *SessionDB) CountSessionsByUser(ctx context.Context, userID string) (int, error)

CountSessionsByUser returns the number of active sessions for a user.

func (*SessionDB) CreateSession

func (s *SessionDB) CreateSession(ctx context.Context, session *Session) error

CreateSession creates a new session in the database. SECURITY: org_id MUST be set to prevent cross-tenant access.

func (*SessionDB) DeleteSession

func (s *SessionDB) DeleteSession(ctx context.Context, sessionID string) error

DeleteSession marks a session as deleted (internal use). WARNING: Use DeleteSessionByOrg for user-facing APIs to ensure org isolation.

func (*SessionDB) DeleteSessionByOrg

func (s *SessionDB) DeleteSessionByOrg(ctx context.Context, sessionID, orgID string) error

DeleteSessionByOrg marks a session as deleted, filtered by organization. SECURITY: Use this function for user-facing APIs to ensure org isolation.

func (*SessionDB) GetIdleSessions

func (s *SessionDB) GetIdleSessions(ctx context.Context) ([]*Session, error)

GetIdleSessions returns sessions that have been idle beyond their timeout (internal use).

func (*SessionDB) GetSession

func (s *SessionDB) GetSession(ctx context.Context, sessionID string) (*Session, error)

GetSession retrieves a session by ID (without org filter - internal use only). WARNING: Use GetSessionByOrg for user-facing APIs to ensure org isolation.

func (*SessionDB) GetSessionByOrg

func (s *SessionDB) GetSessionByOrg(ctx context.Context, sessionID, orgID string) (*Session, error)

GetSessionByOrg retrieves a session by ID, filtered by organization. SECURITY: Use this function for user-facing APIs to ensure org isolation.

func (*SessionDB) HardDeleteSession

func (s *SessionDB) HardDeleteSession(ctx context.Context, sessionID string) error

HardDeleteSession permanently removes a session from the database.

func (*SessionDB) ListSessions

func (s *SessionDB) ListSessions(ctx context.Context) ([]*Session, error)

ListSessions retrieves all sessions (internal use - no org filter). WARNING: Use ListSessionsByOrg for user-facing APIs to ensure org isolation.

func (*SessionDB) ListSessionsByOrg

func (s *SessionDB) ListSessionsByOrg(ctx context.Context, orgID string) ([]*Session, error)

ListSessionsByOrg retrieves all sessions for a specific organization. SECURITY: Use this function for user-facing APIs to ensure org isolation.

func (*SessionDB) ListSessionsByState

func (s *SessionDB) ListSessionsByState(ctx context.Context, state string) ([]*Session, error)

ListSessionsByState retrieves all sessions with a specific state (internal use).

func (*SessionDB) ListSessionsByStateAndOrg

func (s *SessionDB) ListSessionsByStateAndOrg(ctx context.Context, state, orgID string) ([]*Session, error)

ListSessionsByStateAndOrg retrieves sessions by state within an organization. SECURITY: Use this function for user-facing APIs to ensure org isolation.

func (*SessionDB) ListSessionsByTags

func (s *SessionDB) ListSessionsByTags(ctx context.Context, tags []string) ([]*Session, error)

ListSessionsByTags retrieves sessions that have ANY of the specified tags (internal use).

func (*SessionDB) ListSessionsByTagsAndOrg

func (s *SessionDB) ListSessionsByTagsAndOrg(ctx context.Context, tags []string, orgID string) ([]*Session, error)

ListSessionsByTagsAndOrg retrieves sessions by tags within an organization. SECURITY: Use this function for user-facing APIs to ensure org isolation.

func (*SessionDB) ListSessionsByUser

func (s *SessionDB) ListSessionsByUser(ctx context.Context, userID string) ([]*Session, error)

ListSessionsByUser retrieves all sessions for a specific user (internal use). WARNING: Use ListSessionsByUserAndOrg for user-facing APIs to ensure org isolation.

func (*SessionDB) ListSessionsByUserAndOrg

func (s *SessionDB) ListSessionsByUserAndOrg(ctx context.Context, userID, orgID string) ([]*Session, error)

ListSessionsByUserAndOrg retrieves all sessions for a specific user within an org. SECURITY: Use this function for user-facing APIs to ensure org isolation.

func (*SessionDB) UpdateActiveConnections

func (s *SessionDB) UpdateActiveConnections(ctx context.Context, sessionID string, count int) error

UpdateActiveConnections updates the connection count for a session.

func (*SessionDB) UpdateLastActivity

func (s *SessionDB) UpdateLastActivity(ctx context.Context, sessionID string) error

UpdateLastActivity updates the last activity timestamp.

func (*SessionDB) UpdateSessionState

func (s *SessionDB) UpdateSessionState(ctx context.Context, sessionID, state string) error

UpdateSessionState updates the state of a session (internal use). WARNING: Use UpdateSessionStateByOrg for user-facing APIs to ensure org isolation.

func (*SessionDB) UpdateSessionStateByOrg

func (s *SessionDB) UpdateSessionStateByOrg(ctx context.Context, sessionID, state, orgID string) error

UpdateSessionStateByOrg updates session state, filtered by organization. SECURITY: Use this function for user-facing APIs to ensure org isolation.

func (*SessionDB) UpdateSessionStatus

func (s *SessionDB) UpdateSessionStatus(ctx context.Context, sessionID, state, url, podName string) error

UpdateSessionStatus updates session state, URL, and pod name from controller status events.

func (*SessionDB) UpdateSessionTags

func (s *SessionDB) UpdateSessionTags(ctx context.Context, sessionID string, tags []string) error

UpdateSessionTags updates the tags for a session.

func (*SessionDB) UpdateSessionURL

func (s *SessionDB) UpdateSessionURL(ctx context.Context, sessionID, url string) error

UpdateSessionURL updates the URL of a session.

type TeamMembership

type TeamMembership struct {
	TeamID          string    `json:"teamId"`
	TeamName        string    `json:"teamName"`
	TeamDisplayName string    `json:"teamDisplayName"`
	TeamType        string    `json:"teamType"`
	Role            string    `json:"role"`
	JoinedAt        time.Time `json:"joinedAt"`
}

TeamMembership represents a user's membership in a team

type TeamPermission

type TeamPermission struct {
	ID          int       `json:"id"`
	Role        string    `json:"role"`
	Permission  string    `json:"permission"`
	Description string    `json:"description"`
	CreatedAt   time.Time `json:"createdAt"`
}

TeamPermission represents a permission for a team role

type TeamRoleInfo

type TeamRoleInfo struct {
	Role        string   `json:"role"`
	Permissions []string `json:"permissions"`
}

TeamRoleInfo represents information about a team role and its permissions

type Template

type Template struct {
	ID           int             `json:"id"`
	RepositoryID int             `json:"repository_id"`
	Name         string          `json:"name"`
	DisplayName  string          `json:"display_name"`
	Description  string          `json:"description"`
	Category     string          `json:"category"`
	AppType      string          `json:"app_type"`
	IconURL      string          `json:"icon_url"`
	Manifest     json.RawMessage `json:"manifest"` // JSONB - Template CRD spec
	Tags         []string        `json:"tags"`
	InstallCount int             `json:"install_count"`
	CreatedAt    time.Time       `json:"created_at"`
	UpdatedAt    time.Time       `json:"updated_at"`
}

Template represents a template stored in the catalog_templates table.

type TemplateDB

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

TemplateDB provides database operations for templates. v2.0-beta: Templates are stored in database (catalog_templates), not Kubernetes CRDs.

func NewTemplateDB

func NewTemplateDB(db *Database) *TemplateDB

NewTemplateDB creates a new template database instance.

func (*TemplateDB) CreateTemplate

func (t *TemplateDB) CreateTemplate(ctx context.Context, template *Template) error

CreateTemplate creates a new template in the catalog_templates table.

func (*TemplateDB) DeleteTemplate

func (t *TemplateDB) DeleteTemplate(ctx context.Context, name string) error

DeleteTemplate deletes a template from the catalog_templates table.

func (*TemplateDB) GetTemplateByID

func (t *TemplateDB) GetTemplateByID(ctx context.Context, id int) (*Template, error)

GetTemplateByID fetches a template by ID from the catalog_templates table.

func (*TemplateDB) GetTemplateByName

func (t *TemplateDB) GetTemplateByName(ctx context.Context, name string) (*Template, error)

GetTemplateByName fetches a template by name from the catalog_templates table. Returns sql.ErrNoRows if template doesn't exist.

func (*TemplateDB) IncrementInstallCount

func (t *TemplateDB) IncrementInstallCount(ctx context.Context, name string) error

IncrementInstallCount increments the install_count for a template.

func (*TemplateDB) ListTemplates

func (t *TemplateDB) ListTemplates(ctx context.Context) ([]*Template, error)

ListTemplates retrieves all templates from the catalog_templates table.

func (*TemplateDB) ListTemplatesByCategory

func (t *TemplateDB) ListTemplatesByCategory(ctx context.Context, category string) ([]*Template, error)

ListTemplatesByCategory retrieves templates filtered by category.

func (*TemplateDB) UpdateTemplate

func (t *TemplateDB) UpdateTemplate(ctx context.Context, template *Template) error

UpdateTemplate updates an existing template in the catalog_templates table.

type UserDB

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

UserDB handles database operations for users

func NewUserDB

func NewUserDB(db *sql.DB) *UserDB

NewUserDB creates a new UserDB instance

func (*UserDB) AddUserToGroup

func (u *UserDB) AddUserToGroup(ctx context.Context, userID, groupName string) error

AddUserToGroup adds a user to a group by group name

func (*UserDB) CreateUser

func (u *UserDB) CreateUser(ctx context.Context, req *models.CreateUserRequest) (*models.User, error)

CreateUser creates a new user

func (*UserDB) DB

func (u *UserDB) DB() *sql.DB

DB returns the underlying database connection

func (*UserDB) DeleteUser

func (u *UserDB) DeleteUser(ctx context.Context, userID string) error

DeleteUser deletes a user

func (*UserDB) DeleteUserQuota

func (u *UserDB) DeleteUserQuota(ctx context.Context, userID string) error

DeleteUserQuota deletes a user's quota (resets to defaults)

func (*UserDB) GetOrCreateSAMLUser

func (u *UserDB) GetOrCreateSAMLUser(ctx context.Context, username, email, fullName, provider string) (*models.User, error)

GetOrCreateSAMLUser gets or creates a user from SAML assertion

func (*UserDB) GetUser

func (u *UserDB) GetUser(ctx context.Context, userID string) (*models.User, error)

GetUser retrieves a user by ID

func (*UserDB) GetUserByEmail

func (u *UserDB) GetUserByEmail(ctx context.Context, email string) (*models.User, error)

GetUserByEmail retrieves a user by email address

func (*UserDB) GetUserByUsername

func (u *UserDB) GetUserByUsername(ctx context.Context, username string) (*models.User, error)

GetUserByUsername retrieves a user by username

func (*UserDB) GetUserGroups

func (u *UserDB) GetUserGroups(ctx context.Context, userID string) ([]string, error)

GetUserGroups retrieves all groups a user belongs to

func (*UserDB) GetUserQuota

func (u *UserDB) GetUserQuota(ctx context.Context, userID string) (*models.UserQuota, error)

GetUserQuota retrieves quota for a user

func (*UserDB) ListAllUserQuotas

func (u *UserDB) ListAllUserQuotas(ctx context.Context) ([]*models.UserQuota, error)

ListAllUserQuotas retrieves quotas for all users

func (*UserDB) ListUsers

func (u *UserDB) ListUsers(ctx context.Context, role, provider string, activeOnly bool) ([]*models.User, error)

ListUsers retrieves all users with optional filtering

func (*UserDB) SetUserQuota

func (u *UserDB) SetUserQuota(ctx context.Context, userID string, req *models.SetQuotaRequest) error

SetUserQuota sets or updates quota for a user

func (*UserDB) UpdateLastLogin

func (u *UserDB) UpdateLastLogin(ctx context.Context, userID string) error

UpdateLastLogin updates the user's last login timestamp

func (*UserDB) UpdatePassword

func (u *UserDB) UpdatePassword(ctx context.Context, userID string, newPassword string) error

UpdatePassword updates a user's password (local auth only)

func (*UserDB) UpdateQuotaUsage

func (u *UserDB) UpdateQuotaUsage(ctx context.Context, userID string, sessions int, cpu, memory, storage string) error

UpdateQuotaUsage updates the current usage for a user's quota

func (*UserDB) UpdateUser

func (u *UserDB) UpdateUser(ctx context.Context, userID string, req *models.UpdateUserRequest) error

UpdateUser updates user information

func (*UserDB) VerifyPassword

func (u *UserDB) VerifyPassword(ctx context.Context, username, password string) (*models.User, error)

VerifyPassword verifies a user's password (for local auth)

Jump to

Keyboard shortcuts

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