store

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUsernameConflict is returned when a username already exists
	ErrUsernameConflict = errors.New("username already exists")

	// ErrRecordNotFound wraps GORM's not found error for consistency
	ErrRecordNotFound = errors.New("record not found")

	// ErrAuthCodeAlreadyUsed is returned by MarkAuthorizationCodeUsed when the
	// code was already consumed by a concurrent request (0 rows updated).
	ErrAuthCodeAlreadyUsed = errors.New("authorization code already used")
)

Functions

func GetDialector

func GetDialector(driver, dsn string) (gorm.Dialector, error)

GetDialector returns a GORM dialector for the given driver name and DSN

func RegisterDriver

func RegisterDriver(name string, factory DriverFactory)

RegisterDriver allows registering custom database drivers

Types

type AuditLogFilters

type AuditLogFilters struct {
	EventType    models.EventType     `json:"event_type,omitempty"`
	ActorUserID  string               `json:"actor_user_id,omitempty"`
	ResourceType models.ResourceType  `json:"resource_type,omitempty"`
	ResourceID   string               `json:"resource_id,omitempty"`
	Severity     models.EventSeverity `json:"severity,omitempty"`
	Success      *bool                `json:"success,omitempty"`
	StartTime    time.Time            `json:"start_time,omitzero"`
	EndTime      time.Time            `json:"end_time,omitzero"`
	ActorIP      string               `json:"actor_ip,omitempty"`
	Search       string               `json:"search,omitempty"` // Search in action, resource_name, actor_username
}

AuditLogFilters contains filter criteria for querying audit logs

type AuditLogStats

type AuditLogStats struct {
	TotalEvents      int64                          `json:"total_events"`
	EventsByType     map[models.EventType]int64     `json:"events_by_type"`
	EventsBySeverity map[models.EventSeverity]int64 `json:"events_by_severity"`
	SuccessCount     int64                          `json:"success_count"`
	FailureCount     int64                          `json:"failure_count"`
}

AuditLogStats contains statistics about audit logs

type DriverFactory

type DriverFactory func(dsn string) gorm.Dialector

DriverFactory is a function that creates a gorm.Dialector

type PaginationParams

type PaginationParams struct {
	Page     int    // Current page number (1-indexed)
	PageSize int    // Number of items per page
	Search   string // Search keyword
}

PaginationParams contains parameters for paginated queries

func NewPaginationParams

func NewPaginationParams(page, pageSize int, search string) PaginationParams

NewPaginationParams creates a new PaginationParams with default values

type PaginationResult

type PaginationResult struct {
	Total       int64 // Total number of records
	TotalPages  int   // Total number of pages
	CurrentPage int   // Current page number
	PageSize    int   // Number of items per page
	HasPrev     bool  // Whether there is a previous page
	HasNext     bool  // Whether there is a next page
	PrevPage    int   // Previous page number
	NextPage    int   // Next page number
}

PaginationResult contains pagination metadata

func CalculatePagination

func CalculatePagination(total int64, currentPage, pageSize int) PaginationResult

CalculatePagination calculates pagination metadata

type Store

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

func New

func New(ctx context.Context, driver, dsn string, cfg *config.Config) (*Store, error)

func (*Store) Close

func (s *Store) Close(ctx context.Context) error

Close gracefully closes the database connection with timeout support

func (*Store) CountActiveTokensByCategory

func (s *Store) CountActiveTokensByCategory(category string) (int64, error)

CountActiveTokensByCategory counts active, non-expired tokens by category

func (*Store) CountActiveTokensByClientID

func (s *Store) CountActiveTokensByClientID(clientID string) (int64, error)

CountActiveTokensByClientID counts active tokens for a specific client

func (*Store) CountPendingDeviceCodes

func (s *Store) CountPendingDeviceCodes() (int64, error)

CountPendingDeviceCodes counts pending (not yet authorized) device codes

func (*Store) CountTotalDeviceCodes

func (s *Store) CountTotalDeviceCodes() (int64, error)

CountTotalDeviceCodes counts all non-expired device codes

func (*Store) CreateAccessToken

func (s *Store) CreateAccessToken(token *models.AccessToken) error

Access Token operations

func (*Store) CreateAuditLog

func (s *Store) CreateAuditLog(log *models.AuditLog) error

CreateAuditLog creates a single audit log entry

func (*Store) CreateAuditLogBatch

func (s *Store) CreateAuditLogBatch(logs []*models.AuditLog) error

CreateAuditLogBatch creates multiple audit log entries in a single transaction

func (*Store) CreateAuthorizationCode

func (s *Store) CreateAuthorizationCode(code *models.AuthorizationCode) error

CreateAuthorizationCode persists a new authorization code

func (*Store) CreateClient

func (s *Store) CreateClient(client *models.OAuthApplication) error

func (*Store) CreateDeviceCode

func (s *Store) CreateDeviceCode(dc *models.DeviceCode) error

CreateDeviceCode creates a new device code

func (*Store) CreateOAuthConnection

func (s *Store) CreateOAuthConnection(conn *models.OAuthConnection) error

CreateOAuthConnection creates a new OAuth connection

func (*Store) CreateUser

func (s *Store) CreateUser(user *models.User) error

CreateUser creates a new user

func (*Store) DB

func (s *Store) DB() *gorm.DB

DB returns the underlying GORM database connection (for transactions)

func (*Store) DeleteClient

func (s *Store) DeleteClient(clientID string) error

func (*Store) DeleteDeviceCodeByID

func (s *Store) DeleteDeviceCodeByID(id int64) error

DeleteDeviceCodeByID deletes device code by ID (primary key)

func (*Store) DeleteExpiredDeviceCodes

func (s *Store) DeleteExpiredDeviceCodes() error

func (*Store) DeleteExpiredTokens

func (s *Store) DeleteExpiredTokens() error

func (*Store) DeleteOAuthConnection

func (s *Store) DeleteOAuthConnection(id string) error

DeleteOAuthConnection deletes an OAuth connection by ID

func (*Store) DeleteOldAuditLogs

func (s *Store) DeleteOldAuditLogs(olderThan time.Time) (int64, error)

DeleteOldAuditLogs deletes audit logs older than the specified time

func (*Store) DeleteUser

func (s *Store) DeleteUser(id string) error

DeleteUser deletes a user by ID

func (*Store) GetAccessToken

func (s *Store) GetAccessToken(token string) (*models.AccessToken, error)

func (*Store) GetAccessTokenByID

func (s *Store) GetAccessTokenByID(tokenID string) (*models.AccessToken, error)

func (*Store) GetAuditLogStats

func (s *Store) GetAuditLogStats(startTime, endTime time.Time) (AuditLogStats, error)

GetAuditLogStats returns statistics about audit logs in a given time range

func (*Store) GetAuditLogsPaginated

func (s *Store) GetAuditLogsPaginated(
	params PaginationParams,
	filters AuditLogFilters,
) ([]models.AuditLog, PaginationResult, error)

GetAuditLogsPaginated retrieves audit logs with pagination and filtering

func (*Store) GetAuthorizationCodeByHash

func (s *Store) GetAuthorizationCodeByHash(hash string) (*models.AuthorizationCode, error)

GetAuthorizationCodeByHash retrieves an authorization code by its SHA-256 hash

func (*Store) GetClient

func (s *Store) GetClient(clientID string) (*models.OAuthApplication, error)

OAuth Client operations

func (*Store) GetClientAuthorizations

func (s *Store) GetClientAuthorizations(clientID string) ([]models.UserAuthorization, error)

GetClientAuthorizations returns all active consent records for a client, ordered by grant date

func (*Store) GetClientByIntID

func (s *Store) GetClientByIntID(id int64) (*models.OAuthApplication, error)

GetClientByIntID retrieves an OAuth application by its integer primary key

func (*Store) GetClientsByIDs

func (s *Store) GetClientsByIDs(clientIDs []string) (map[string]*models.OAuthApplication, error)

func (*Store) GetDeviceCodeByUserCode

func (s *Store) GetDeviceCodeByUserCode(userCode string) (*models.DeviceCode, error)

GetDeviceCodeByUserCode retrieves a device code by user code

func (*Store) GetDeviceCodesByID

func (s *Store) GetDeviceCodesByID(deviceCodeID string) ([]*models.DeviceCode, error)

GetDeviceCodesByID retrieves all device codes with matching ID suffix Used for hash verification during token exchange

func (*Store) GetOAuthConnection

func (s *Store) GetOAuthConnection(
	provider, providerUserID string,
) (*models.OAuthConnection, error)

GetOAuthConnection finds an OAuth connection by provider and provider user ID

func (*Store) GetOAuthConnectionByUserAndProvider

func (s *Store) GetOAuthConnectionByUserAndProvider(
	userID, provider string,
) (*models.OAuthConnection, error)

GetOAuthConnectionByUserAndProvider finds an OAuth connection by user ID and provider

func (*Store) GetOAuthConnectionsByUserID

func (s *Store) GetOAuthConnectionsByUserID(userID string) ([]models.OAuthConnection, error)

GetOAuthConnectionsByUserID returns all OAuth connections for a user

func (*Store) GetTokensByCategoryAndStatus

func (s *Store) GetTokensByCategoryAndStatus(
	userID, category, status string,
) ([]models.AccessToken, error)

GetTokensByCategoryAndStatus returns tokens filtered by category and status

func (*Store) GetTokensByUserID

func (s *Store) GetTokensByUserID(userID string) ([]models.AccessToken, error)

func (*Store) GetTokensByUserIDPaginated

func (s *Store) GetTokensByUserIDPaginated(
	userID string,
	params PaginationParams,
) ([]models.AccessToken, PaginationResult, error)

GetTokensByUserIDPaginated returns paginated tokens for a user with search support

func (*Store) GetUserAuthorization

func (s *Store) GetUserAuthorization(
	userID string,
	applicationID int64,
) (*models.UserAuthorization, error)

GetUserAuthorization retrieves the active consent record for a (user, application) pair

func (*Store) GetUserAuthorizationByUUID

func (s *Store) GetUserAuthorizationByUUID(
	authUUID, userID string,
) (*models.UserAuthorization, error)

GetUserAuthorizationByUUID retrieves an authorization by its public UUID, scoped to the owner

func (*Store) GetUserByEmail

func (s *Store) GetUserByEmail(email string) (*models.User, error)

GetUserByEmail finds a user by email address

func (*Store) GetUserByExternalID

func (s *Store) GetUserByExternalID(externalID, authSource string) (*models.User, error)

GetUserByExternalID finds a user by their external ID and auth source

func (*Store) GetUserByID

func (s *Store) GetUserByID(id string) (*models.User, error)

func (*Store) GetUserByUsername

func (s *Store) GetUserByUsername(username string) (*models.User, error)

User operations

func (*Store) GetUsersByIDs

func (s *Store) GetUsersByIDs(userIDs []string) (map[string]*models.User, error)

GetUsersByIDs batch loads users by IDs using WHERE IN to prevent N+1 queries

func (*Store) Health

func (s *Store) Health() error

Health checks the database connection

func (*Store) ListClients

func (s *Store) ListClients() ([]models.OAuthApplication, error)

func (*Store) ListClientsPaginated

func (s *Store) ListClientsPaginated(
	params PaginationParams,
) ([]models.OAuthApplication, PaginationResult, error)

ListClientsPaginated returns paginated OAuth clients with search support

func (*Store) ListUserAuthorizations

func (s *Store) ListUserAuthorizations(userID string) ([]models.UserAuthorization, error)

ListUserAuthorizations returns all active authorizations for a user, newest first

func (*Store) MarkAuthorizationCodeUsed

func (s *Store) MarkAuthorizationCodeUsed(id uint) error

MarkAuthorizationCodeUsed atomically sets UsedAt only when the code has not yet been consumed. The WHERE clause includes "used_at IS NULL" so that a concurrent request that races past the application-level IsUsed() check will update 0 rows and receive ErrAuthCodeAlreadyUsed, preventing double issuance.

func (*Store) RevokeAllActiveTokensByClientID

func (s *Store) RevokeAllActiveTokensByClientID(clientID string) (int64, error)

RevokeAllActiveTokensByClientID revokes every active token for a client and returns the count

func (*Store) RevokeAllUserAuthorizationsByClientID

func (s *Store) RevokeAllUserAuthorizationsByClientID(clientID string) error

RevokeAllUserAuthorizationsByClientID invalidates all active consent records for a client

func (*Store) RevokeToken

func (s *Store) RevokeToken(tokenID string) error

func (*Store) RevokeTokensByAuthorizationID

func (s *Store) RevokeTokensByAuthorizationID(authorizationID uint) error

RevokeTokensByAuthorizationID revokes all active tokens linked to a specific UserAuthorization

func (*Store) RevokeTokensByClientID

func (s *Store) RevokeTokensByClientID(clientID string) error

func (*Store) RevokeTokensByUserID

func (s *Store) RevokeTokensByUserID(userID string) error

func (*Store) RevokeUserAuthorization

func (s *Store) RevokeUserAuthorization(
	authUUID, userID string,
) (*models.UserAuthorization, error)

RevokeUserAuthorization marks an authorization as revoked and returns the record

func (*Store) UpdateClient

func (s *Store) UpdateClient(client *models.OAuthApplication) error

func (*Store) UpdateDeviceCode

func (s *Store) UpdateDeviceCode(dc *models.DeviceCode) error

UpdateDeviceCode updates a device code

func (*Store) UpdateOAuthConnection

func (s *Store) UpdateOAuthConnection(conn *models.OAuthConnection) error

UpdateOAuthConnection updates an existing OAuth connection

func (*Store) UpdateTokenStatus

func (s *Store) UpdateTokenStatus(tokenID, status string) error

UpdateTokenStatus updates the status of a token

func (*Store) UpdateUser

func (s *Store) UpdateUser(user *models.User) error

UpdateUser updates an existing user

func (*Store) UpsertExternalUser

func (s *Store) UpsertExternalUser(
	username, externalID, authSource, email, fullName string,
) (*models.User, error)

UpsertExternalUser creates or updates a user from external authentication

func (*Store) UpsertUserAuthorization

func (s *Store) UpsertUserAuthorization(auth *models.UserAuthorization) error

UpsertUserAuthorization creates a new consent record or re-activates and updates an existing one. Uses a single atomic INSERT ... ON CONFLICT DO UPDATE to avoid the race condition that arises from a non-atomic SELECT-then-INSERT/UPDATE pattern.

Jump to

Keyboard shortcuts

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