auth

package
v0.1.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2025 License: GPL-3.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MinPasswordLength is the minimum required password length
	MinPasswordLength = 8
	// MaxPasswordLength is the maximum allowed password length (bcrypt limit is 72)
	MaxPasswordLength = 72
	// DefaultBcryptCost is the default cost for bcrypt hashing
	DefaultBcryptCost = 12
)

Variables

View Source
var (
	// ErrInvalidAPIKey is returned when API key is invalid
	ErrInvalidAPIKey = errors.New("invalid API key")
	// ErrAPIKeyExpired is returned when API key has expired
	ErrAPIKeyExpired = errors.New("API key has expired")
	// ErrAPIKeyRevoked is returned when API key has been revoked
	ErrAPIKeyRevoked = errors.New("API key has been revoked")
)
View Source
var (
	// ErrNotAdmin is returned when a non-dashboard-admin tries to impersonate
	ErrNotAdmin = errors.New("only dashboard admins can impersonate users")
	// ErrSelfImpersonation is returned when trying to impersonate yourself
	ErrSelfImpersonation = errors.New("cannot impersonate yourself")
	// ErrNoActiveImpersonation is returned when trying to stop non-existent impersonation
	ErrNoActiveImpersonation = errors.New("no active impersonation session found")
)
View Source
var (
	// ErrInvitationNotFound is returned when an invitation token is not found
	ErrInvitationNotFound = errors.New("invitation not found")
	// ErrInvitationExpired is returned when an invitation token has expired
	ErrInvitationExpired = errors.New("invitation has expired")
	// ErrInvitationAlreadyAccepted is returned when an invitation has already been accepted
	ErrInvitationAlreadyAccepted = errors.New("invitation has already been accepted")
)
View Source
var (
	// ErrInvalidToken is returned when a token is invalid
	ErrInvalidToken = errors.New("invalid token")
	// ErrExpiredToken is returned when a token has expired
	ErrExpiredToken = errors.New("token has expired")
	// ErrInvalidSignature is returned when token signature is invalid
	ErrInvalidSignature = errors.New("invalid token signature")
)
View Source
var (
	// ErrMagicLinkNotFound is returned when a magic link is not found
	ErrMagicLinkNotFound = errors.New("magic link not found")
	// ErrMagicLinkExpired is returned when a magic link has expired
	ErrMagicLinkExpired = errors.New("magic link has expired")
	// ErrMagicLinkUsed is returned when a magic link has already been used
	ErrMagicLinkUsed = errors.New("magic link has already been used")
)
View Source
var (
	// ErrInvalidProvider is returned when an OAuth provider is not supported
	ErrInvalidProvider = errors.New("invalid OAuth provider")
	// ErrInvalidState is returned when OAuth state doesn't match
	ErrInvalidState = errors.New("invalid OAuth state")
)
View Source
var (
	// ErrWeakPassword is returned when a password doesn't meet minimum requirements
	ErrWeakPassword = errors.New("password does not meet minimum requirements")
	// ErrPasswordTooLong is returned when password exceeds maximum length
	ErrPasswordTooLong = errors.New("password exceeds maximum length")
)
View Source
var (
	// ErrPasswordResetTokenNotFound is returned when a password reset token is not found
	ErrPasswordResetTokenNotFound = errors.New("password reset token not found")
	// ErrPasswordResetTokenExpired is returned when a password reset token has expired
	ErrPasswordResetTokenExpired = errors.New("password reset token has expired")
	// ErrPasswordResetTokenUsed is returned when a password reset token has already been used
	ErrPasswordResetTokenUsed = errors.New("password reset token has already been used")
)
View Source
var (
	// ErrSessionNotFound is returned when a session is not found
	ErrSessionNotFound = errors.New("session not found")
	// ErrSessionExpired is returned when a session has expired
	ErrSessionExpired = errors.New("session has expired")
)
View Source
var (
	// ErrUserNotFound is returned when a user is not found
	ErrUserNotFound = errors.New("user not found")
	// ErrUserAlreadyExists is returned when trying to create a user with existing email
	ErrUserAlreadyExists = errors.New("user with this email already exists")
	// ErrInvalidCredentials is returned when login credentials are invalid
	ErrInvalidCredentials = errors.New("invalid email or password")
)
View Source
var (
	// ErrSettingNotFound is returned when a system setting is not found
	ErrSettingNotFound = errors.New("system setting not found")
)
View Source
var (
	// ErrTokenBlacklisted is returned when a token is found in the blacklist
	ErrTokenBlacklisted = errors.New("token has been revoked")
)

Functions

func GenerateBackupCodes

func GenerateBackupCodes(count int) ([]string, []string, error)

GenerateBackupCodes generates a set of backup codes for 2FA recovery Returns both the plain codes (to show to user) and hashed codes (to store)

func GenerateMagicLinkToken

func GenerateMagicLinkToken() (string, error)

GenerateMagicLinkToken generates a secure random token for magic links

func GeneratePasswordResetToken

func GeneratePasswordResetToken() (string, error)

GeneratePasswordResetToken generates a secure random token for password resets

func GenerateState

func GenerateState() (string, error)

GenerateState generates a random state parameter for CSRF protection

func GenerateTOTPSecret

func GenerateTOTPSecret(issuer, accountName string) (string, string, error)

GenerateTOTPSecret generates a new TOTP secret and QR code URL

func VerifyBackupCode

func VerifyBackupCode(code, hashedCode string) (bool, error)

VerifyBackupCode verifies a backup code against its hash

func VerifyTOTPCode

func VerifyTOTPCode(code, secret string) (bool, error)

VerifyTOTPCode verifies a TOTP code against a secret

Types

type APIKey

type APIKey struct {
	ID                 uuid.UUID  `json:"id"`
	Name               string     `json:"name"`
	Description        *string    `json:"description,omitempty"`
	KeyHash            string     `json:"-"` // Never expose the hash
	KeyPrefix          string     `json:"key_prefix"`
	UserID             *uuid.UUID `json:"user_id,omitempty"`
	Scopes             []string   `json:"scopes"`
	RateLimitPerMinute int        `json:"rate_limit_per_minute"`
	LastUsedAt         *time.Time `json:"last_used_at,omitempty"`
	ExpiresAt          *time.Time `json:"expires_at,omitempty"`
	RevokedAt          *time.Time `json:"revoked_at,omitempty"`
	CreatedAt          time.Time  `json:"created_at"`
	UpdatedAt          time.Time  `json:"updated_at"`
}

APIKey represents an API key

type APIKeyService

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

APIKeyService handles API key operations

func NewAPIKeyService

func NewAPIKeyService(db *pgxpool.Pool) *APIKeyService

NewAPIKeyService creates a new API key service

func (*APIKeyService) DeleteAPIKey

func (s *APIKeyService) DeleteAPIKey(ctx context.Context, id uuid.UUID) error

DeleteAPIKey permanently deletes an API key

func (*APIKeyService) GenerateAPIKey

func (s *APIKeyService) GenerateAPIKey(ctx context.Context, name string, description *string, userID *uuid.UUID, scopes []string, rateLimitPerMinute int, expiresAt *time.Time) (*APIKeyWithPlaintext, error)

GenerateAPIKey generates a new API key with format: fbk_<random_string>

func (*APIKeyService) ListAPIKeys

func (s *APIKeyService) ListAPIKeys(ctx context.Context, userID *uuid.UUID) ([]APIKey, error)

ListAPIKeys lists all API keys (optionally filtered by user)

func (*APIKeyService) RevokeAPIKey

func (s *APIKeyService) RevokeAPIKey(ctx context.Context, id uuid.UUID) error

RevokeAPIKey revokes an API key

func (*APIKeyService) UpdateAPIKey

func (s *APIKeyService) UpdateAPIKey(ctx context.Context, id uuid.UUID, name *string, description *string, scopes []string, rateLimitPerMinute *int) error

UpdateAPIKey updates an API key's metadata

func (*APIKeyService) ValidateAPIKey

func (s *APIKeyService) ValidateAPIKey(ctx context.Context, plaintextKey string) (*APIKey, error)

ValidateAPIKey validates an API key and returns the associated API key info

type APIKeyWithPlaintext

type APIKeyWithPlaintext struct {
	APIKey
	PlaintextKey string `json:"key"` // Full key, only shown once
}

APIKeyWithPlaintext includes the plaintext key (only returned once during creation)

type CreateUserRequest

type CreateUserRequest struct {
	Email        string `json:"email"`
	Password     string `json:"password"`
	Role         string `json:"role,omitempty"`
	UserMetadata any    `json:"user_metadata,omitempty"` // User-editable metadata
	AppMetadata  any    `json:"app_metadata,omitempty"`  // Application/admin-only metadata
}

CreateUserRequest represents a request to create a new user

type DashboardAuthService

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

DashboardAuthService handles authentication for dashboard administrators

func NewDashboardAuthService

func NewDashboardAuthService(db *pgxpool.Pool, jwtManager *JWTManager) *DashboardAuthService

NewDashboardAuthService creates a new dashboard authentication service

func (*DashboardAuthService) ChangePassword

func (s *DashboardAuthService) ChangePassword(ctx context.Context, userID uuid.UUID, currentPassword, newPassword string, ipAddress net.IP, userAgent string) error

ChangePassword changes a dashboard user's password

func (*DashboardAuthService) CreateUser

func (s *DashboardAuthService) CreateUser(ctx context.Context, email, password, fullName string) (*DashboardUser, error)

CreateUser creates a new dashboard user with email and password

func (*DashboardAuthService) DeleteAccount

func (s *DashboardAuthService) DeleteAccount(ctx context.Context, userID uuid.UUID, password string, ipAddress net.IP, userAgent string) error

DeleteAccount soft-deletes a dashboard user account

func (*DashboardAuthService) DisableTOTP

func (s *DashboardAuthService) DisableTOTP(ctx context.Context, userID uuid.UUID, password string, ipAddress net.IP, userAgent string) error

DisableTOTP disables 2FA for a user

func (*DashboardAuthService) EnableTOTP

func (s *DashboardAuthService) EnableTOTP(ctx context.Context, userID uuid.UUID, code string, ipAddress net.IP, userAgent string) ([]string, error)

EnableTOTP enables 2FA after verifying the TOTP code

func (*DashboardAuthService) GetDB

func (s *DashboardAuthService) GetDB() *pgxpool.Pool

GetDB returns the database connection pool

func (*DashboardAuthService) GetUserByID

func (s *DashboardAuthService) GetUserByID(ctx context.Context, userID uuid.UUID) (*DashboardUser, error)

GetUserByID fetches a dashboard user by ID

func (*DashboardAuthService) HasExistingUsers

func (s *DashboardAuthService) HasExistingUsers(ctx context.Context) (bool, error)

HasExistingUsers checks if any dashboard users exist

func (*DashboardAuthService) Login

func (s *DashboardAuthService) Login(ctx context.Context, email, password string, ipAddress net.IP, userAgent string) (*DashboardUser, *LoginResponse, error)

Login authenticates a dashboard user with email and password

func (*DashboardAuthService) SetupTOTP

func (s *DashboardAuthService) SetupTOTP(ctx context.Context, userID uuid.UUID, email string) (string, string, error)

SetupTOTP generates a new TOTP secret for 2FA

func (*DashboardAuthService) UpdateProfile

func (s *DashboardAuthService) UpdateProfile(ctx context.Context, userID uuid.UUID, fullName string, avatarURL *string) error

UpdateProfile updates a dashboard user's profile information

func (*DashboardAuthService) VerifyTOTP

func (s *DashboardAuthService) VerifyTOTP(ctx context.Context, userID uuid.UUID, code string) error

VerifyTOTP verifies a TOTP code during login

type DashboardSession

type DashboardSession struct {
	ID             uuid.UUID `json:"id"`
	UserID         uuid.UUID `json:"user_id"`
	TokenHash      string    `json:"-"`
	IPAddress      *net.IP   `json:"ip_address,omitempty"`
	UserAgent      *string   `json:"user_agent,omitempty"`
	ExpiresAt      time.Time `json:"expires_at"`
	CreatedAt      time.Time `json:"created_at"`
	LastActivityAt time.Time `json:"last_activity_at"`
}

DashboardSession represents an active dashboard session

type DashboardUser

type DashboardUser struct {
	ID            uuid.UUID  `json:"id"`
	Email         string     `json:"email"`
	EmailVerified bool       `json:"email_verified"`
	FullName      *string    `json:"full_name,omitempty"`
	AvatarURL     *string    `json:"avatar_url,omitempty"`
	TOTPEnabled   bool       `json:"totp_enabled"`
	IsActive      bool       `json:"is_active"`
	IsLocked      bool       `json:"is_locked"`
	LastLoginAt   *time.Time `json:"last_login_at,omitempty"`
	CreatedAt     time.Time  `json:"created_at"`
	UpdatedAt     time.Time  `json:"updated_at"`
}

DashboardUser represents a dashboard/platform administrator user

type EmailSender

type EmailSender interface {
	SendMagicLink(ctx context.Context, to, token, link string) error
	SendPasswordReset(ctx context.Context, to, token, link string) error
}

EmailSender defines the interface for sending emails

type EnrichedUser

type EnrichedUser struct {
	ID             string                 `json:"id"`
	Email          string                 `json:"email"`
	EmailVerified  bool                   `json:"email_verified"`
	Role           string                 `json:"role"`
	Provider       string                 `json:"provider"` // "email", "invite_pending", "magic_link"
	ActiveSessions int                    `json:"active_sessions"`
	LastSignIn     *time.Time             `json:"last_sign_in"`
	UserMetadata   map[string]interface{} `json:"user_metadata"`
	AppMetadata    map[string]interface{} `json:"app_metadata"`
	CreatedAt      time.Time              `json:"created_at"`
	UpdatedAt      time.Time              `json:"updated_at"`
}

EnrichedUser represents a user with additional metadata for admin view

type ImpersonationRepository

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

ImpersonationRepository handles database operations for impersonation sessions

func NewImpersonationRepository

func NewImpersonationRepository(db *database.Connection) *ImpersonationRepository

NewImpersonationRepository creates a new impersonation repository

func (*ImpersonationRepository) Create

Create creates a new impersonation session

func (*ImpersonationRepository) EndSession

func (r *ImpersonationRepository) EndSession(ctx context.Context, sessionID string) error

EndSession marks an impersonation session as ended

func (*ImpersonationRepository) GetActiveByAdmin

func (r *ImpersonationRepository) GetActiveByAdmin(ctx context.Context, adminUserID string) (*ImpersonationSession, error)

GetActiveByAdmin gets the active impersonation session for an admin

func (*ImpersonationRepository) ListByAdmin

func (r *ImpersonationRepository) ListByAdmin(ctx context.Context, adminUserID string, limit, offset int) ([]*ImpersonationSession, error)

ListByAdmin lists all impersonation sessions for an admin (audit trail)

type ImpersonationService

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

ImpersonationService provides business logic for admin impersonation

func NewImpersonationService

func NewImpersonationService(
	repo *ImpersonationRepository,
	userRepo *UserRepository,
	jwtManager *JWTManager,
) *ImpersonationService

NewImpersonationService creates a new impersonation service

func (*ImpersonationService) GetActiveSession

func (s *ImpersonationService) GetActiveSession(ctx context.Context, adminUserID string) (*ImpersonationSession, error)

GetActiveSession gets the active impersonation session for an admin

func (*ImpersonationService) ListSessions

func (s *ImpersonationService) ListSessions(ctx context.Context, adminUserID string, limit, offset int) ([]*ImpersonationSession, error)

ListSessions lists impersonation sessions for audit purposes

func (*ImpersonationService) StartAnonImpersonation

func (s *ImpersonationService) StartAnonImpersonation(
	ctx context.Context,
	adminUserID string,
	reason string,
	ipAddress string,
	userAgent string,
) (*StartImpersonationResponse, error)

StartAnonImpersonation starts an impersonation session as an anonymous user

func (*ImpersonationService) StartImpersonation

func (s *ImpersonationService) StartImpersonation(
	ctx context.Context,
	adminUserID string,
	req StartImpersonationRequest,
) (*StartImpersonationResponse, error)

StartImpersonation starts an impersonation session for a specific user

func (*ImpersonationService) StartServiceImpersonation

func (s *ImpersonationService) StartServiceImpersonation(
	ctx context.Context,
	adminUserID string,
	reason string,
	ipAddress string,
	userAgent string,
) (*StartImpersonationResponse, error)

StartServiceImpersonation starts an impersonation session with service role

func (*ImpersonationService) StopImpersonation

func (s *ImpersonationService) StopImpersonation(ctx context.Context, adminUserID string) error

StopImpersonation stops the active impersonation session for an admin

type ImpersonationSession

type ImpersonationSession struct {
	ID                string            `json:"id" db:"id"`
	AdminUserID       string            `json:"admin_user_id" db:"admin_user_id"`
	TargetUserID      *string           `json:"target_user_id,omitempty" db:"target_user_id"`
	ImpersonationType ImpersonationType `json:"impersonation_type" db:"impersonation_type"`
	TargetRole        *string           `json:"target_role,omitempty" db:"target_role"`
	Reason            string            `json:"reason,omitempty" db:"reason"`
	StartedAt         time.Time         `json:"started_at" db:"started_at"`
	EndedAt           *time.Time        `json:"ended_at,omitempty" db:"ended_at"`
	IPAddress         string            `json:"ip_address,omitempty" db:"ip_address"`
	UserAgent         string            `json:"user_agent,omitempty" db:"user_agent"`
	IsActive          bool              `json:"is_active" db:"is_active"`
}

ImpersonationSession represents an admin impersonation session

type ImpersonationType

type ImpersonationType string

ImpersonationType represents the type of impersonation

const (
	ImpersonationTypeUser    ImpersonationType = "user"
	ImpersonationTypeAnon    ImpersonationType = "anon"
	ImpersonationTypeService ImpersonationType = "service"
)

type InvitationService

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

InvitationService handles user invitation operations

func NewInvitationService

func NewInvitationService(db *database.Connection) *InvitationService

NewInvitationService creates a new invitation service

func (*InvitationService) AcceptInvitation

func (s *InvitationService) AcceptInvitation(ctx context.Context, token string) error

AcceptInvitation marks an invitation as accepted

func (*InvitationService) CleanupExpiredInvitations

func (s *InvitationService) CleanupExpiredInvitations(ctx context.Context) (int64, error)

CleanupExpiredInvitations removes expired invitation tokens

func (*InvitationService) CreateInvitation

func (s *InvitationService) CreateInvitation(ctx context.Context, email, role string, invitedBy *uuid.UUID, expiryDuration time.Duration) (*InvitationToken, error)

CreateInvitation creates a new invitation token

func (*InvitationService) GenerateToken

func (s *InvitationService) GenerateToken() (string, error)

GenerateToken generates a cryptographically secure random token

func (*InvitationService) GetInvitationByEmail

func (s *InvitationService) GetInvitationByEmail(ctx context.Context, email string) ([]InvitationToken, error)

GetInvitationByEmail retrieves pending invitations for an email

func (*InvitationService) ListInvitations

func (s *InvitationService) ListInvitations(ctx context.Context, includeAccepted, includeExpired bool) ([]InvitationToken, error)

ListInvitations retrieves all invitations (for admin panel)

func (*InvitationService) RevokeInvitation

func (s *InvitationService) RevokeInvitation(ctx context.Context, token string) error

RevokeInvitation revokes (deletes) an invitation token

func (*InvitationService) ValidateToken

func (s *InvitationService) ValidateToken(ctx context.Context, token string) (*InvitationToken, error)

ValidateToken validates an invitation token and returns the invitation

type InvitationToken

type InvitationToken struct {
	ID         uuid.UUID  `json:"id"`
	Email      string     `json:"email"`
	Token      string     `json:"token"`
	Role       string     `json:"role"`
	InvitedBy  *uuid.UUID `json:"invited_by,omitempty"`
	ExpiresAt  time.Time  `json:"expires_at"`
	Accepted   bool       `json:"accepted"`
	AcceptedAt *time.Time `json:"accepted_at,omitempty"`
	CreatedAt  time.Time  `json:"created_at"`
}

InvitationToken represents an invitation for a new user

type InviteUserRequest

type InviteUserRequest struct {
	Email    string `json:"email"`
	Role     string `json:"role"`
	Password string `json:"password,omitempty"` // Optional: if provided, use this instead of generating
}

InviteUserRequest represents a request to invite a new user

type InviteUserResponse

type InviteUserResponse struct {
	User              *User  `json:"user"`
	TemporaryPassword string `json:"temporary_password,omitempty"` // Only if SMTP disabled
	EmailSent         bool   `json:"email_sent"`
	Message           string `json:"message"`
}

InviteUserResponse represents the response after inviting a user

type JWTManager

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

JWTManager handles JWT token operations

func NewJWTManager

func NewJWTManager(secretKey string, accessTTL, refreshTTL time.Duration) *JWTManager

NewJWTManager creates a new JWT manager

func (*JWTManager) ExtractUserID

func (m *JWTManager) ExtractUserID(tokenString string) (string, error)

ExtractUserID extracts the user ID from a token

func (*JWTManager) GenerateAccessToken

func (m *JWTManager) GenerateAccessToken(userID, email, role string, userMetadata, appMetadata any) (string, *TokenClaims, error)

GenerateAccessToken generates a new access token

func (*JWTManager) GenerateAnonymousAccessToken

func (m *JWTManager) GenerateAnonymousAccessToken(userID string) (string, error)

GenerateAnonymousAccessToken generates an access token for an anonymous user

func (*JWTManager) GenerateAnonymousRefreshToken

func (m *JWTManager) GenerateAnonymousRefreshToken(userID string) (string, error)

GenerateAnonymousRefreshToken generates a refresh token for an anonymous user

func (*JWTManager) GenerateRefreshToken

func (m *JWTManager) GenerateRefreshToken(userID, email, sessionID string, userMetadata, appMetadata any) (string, *TokenClaims, error)

GenerateRefreshToken generates a new refresh token

func (*JWTManager) GenerateTokenPair

func (m *JWTManager) GenerateTokenPair(userID, email, role string, userMetadata, appMetadata any) (accessToken, refreshToken string, sessionID string, err error)

GenerateTokenPair generates both access and refresh tokens

func (*JWTManager) GetTokenExpiry

func (m *JWTManager) GetTokenExpiry(tokenString string) (time.Time, error)

GetTokenExpiry returns when a token expires

func (*JWTManager) RefreshAccessToken

func (m *JWTManager) RefreshAccessToken(refreshTokenString string) (string, error)

RefreshAccessToken generates a new access token from a refresh token

func (*JWTManager) ValidateAccessToken

func (m *JWTManager) ValidateAccessToken(tokenString string) (*TokenClaims, error)

ValidateAccessToken validates an access token specifically

func (*JWTManager) ValidateRefreshToken

func (m *JWTManager) ValidateRefreshToken(tokenString string) (*TokenClaims, error)

ValidateRefreshToken validates a refresh token specifically

func (*JWTManager) ValidateToken

func (m *JWTManager) ValidateToken(tokenString string) (*TokenClaims, error)

ValidateToken validates and parses a JWT token

type LoginResponse

type LoginResponse struct {
	AccessToken  string
	RefreshToken string
	ExpiresIn    int64
}

LoginResponse contains the tokens returned from login

type MagicLink struct {
	ID        string     `json:"id" db:"id"`
	Email     string     `json:"email" db:"email"`
	Token     string     `json:"token" db:"token"`
	ExpiresAt time.Time  `json:"expires_at" db:"expires_at"`
	UsedAt    *time.Time `json:"used_at,omitempty" db:"used_at"`
	CreatedAt time.Time  `json:"created_at" db:"created_at"`
}

MagicLink represents a passwordless authentication link

type MagicLinkRepository

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

MagicLinkRepository handles database operations for magic links

func NewMagicLinkRepository

func NewMagicLinkRepository(db *database.Connection) *MagicLinkRepository

NewMagicLinkRepository creates a new magic link repository

func (*MagicLinkRepository) Create

func (r *MagicLinkRepository) Create(ctx context.Context, email string, expiryDuration time.Duration) (*MagicLink, error)

Create creates a new magic link

func (*MagicLinkRepository) DeleteByEmail

func (r *MagicLinkRepository) DeleteByEmail(ctx context.Context, email string) error

DeleteByEmail deletes all magic links for an email

func (*MagicLinkRepository) DeleteExpired

func (r *MagicLinkRepository) DeleteExpired(ctx context.Context) (int64, error)

DeleteExpired deletes all expired magic links

func (*MagicLinkRepository) GetByToken

func (r *MagicLinkRepository) GetByToken(ctx context.Context, token string) (*MagicLink, error)

GetByToken retrieves a magic link by token

func (*MagicLinkRepository) MarkAsUsed

func (r *MagicLinkRepository) MarkAsUsed(ctx context.Context, id string) error

MarkAsUsed marks a magic link as used

func (*MagicLinkRepository) Validate

func (r *MagicLinkRepository) Validate(ctx context.Context, token string) (*MagicLink, error)

Validate validates a magic link token

type MagicLinkService

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

MagicLinkService provides magic link functionality

func NewMagicLinkService

func NewMagicLinkService(
	repo *MagicLinkRepository,
	userRepo *UserRepository,
	emailSender EmailSender,
	linkDuration time.Duration,
	baseURL string,
) *MagicLinkService

NewMagicLinkService creates a new magic link service

func (s *MagicLinkService) SendMagicLink(ctx context.Context, email string) error

SendMagicLink sends a magic link to the specified email

func (s *MagicLinkService) VerifyMagicLink(ctx context.Context, token string) (string, error)

VerifyMagicLink verifies a magic link and returns the email

type OAuthConfig

type OAuthConfig struct {
	ClientID     string
	ClientSecret string
	RedirectURL  string
	Scopes       []string
}

OAuthConfig holds OAuth provider configuration

type OAuthManager

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

OAuthManager handles OAuth authentication flows

func NewOAuthManager

func NewOAuthManager() *OAuthManager

NewOAuthManager creates a new OAuth manager

func (*OAuthManager) ExchangeCode

func (m *OAuthManager) ExchangeCode(ctx context.Context, provider OAuthProvider, code string) (*oauth2.Token, error)

ExchangeCode exchanges an authorization code for tokens

func (*OAuthManager) GetAuthURL

func (m *OAuthManager) GetAuthURL(provider OAuthProvider, state string) (string, error)

GetAuthURL returns the OAuth authorization URL

func (*OAuthManager) GetEndpoint

func (m *OAuthManager) GetEndpoint(provider OAuthProvider) oauth2.Endpoint

GetEndpoint returns the OAuth2 endpoint for a provider

func (*OAuthManager) GetUserInfo

func (m *OAuthManager) GetUserInfo(ctx context.Context, provider OAuthProvider, token *oauth2.Token) (map[string]interface{}, error)

GetUserInfo retrieves user information from the OAuth provider

func (*OAuthManager) GetUserInfoURL

func (m *OAuthManager) GetUserInfoURL(provider OAuthProvider) string

GetUserInfoURL returns the user info endpoint for a provider

func (*OAuthManager) RegisterProvider

func (m *OAuthManager) RegisterProvider(provider OAuthProvider, config OAuthConfig) error

RegisterProvider registers an OAuth provider

type OAuthProvider

type OAuthProvider string

OAuthProvider represents different OAuth providers

const (
	// ProviderGoogle represents Google OAuth
	ProviderGoogle OAuthProvider = "google"
	// ProviderGithub represents GitHub OAuth
	ProviderGithub OAuthProvider = "github"
	// ProviderMicrosoft represents Microsoft OAuth
	ProviderMicrosoft OAuthProvider = "microsoft"
	// ProviderApple represents Apple OAuth
	ProviderApple OAuthProvider = "apple"
	// ProviderFacebook represents Facebook OAuth
	ProviderFacebook OAuthProvider = "facebook"
	// ProviderTwitter represents Twitter OAuth
	ProviderTwitter OAuthProvider = "twitter"
	// ProviderLinkedIn represents LinkedIn OAuth
	ProviderLinkedIn OAuthProvider = "linkedin"
	// ProviderGitLab represents GitLab OAuth
	ProviderGitLab OAuthProvider = "gitlab"
	// ProviderBitbucket represents Bitbucket OAuth
	ProviderBitbucket OAuthProvider = "bitbucket"
)

type PasswordHasher

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

PasswordHasher handles password hashing and validation

func NewPasswordHasher

func NewPasswordHasher() *PasswordHasher

NewPasswordHasher creates a new password hasher with default settings

func NewPasswordHasherWithConfig

func NewPasswordHasherWithConfig(config PasswordHasherConfig) *PasswordHasher

NewPasswordHasherWithConfig creates a password hasher with custom configuration

func (*PasswordHasher) ComparePassword

func (h *PasswordHasher) ComparePassword(hashedPassword, plainPassword string) error

ComparePassword compares a plain password with a hashed password

func (*PasswordHasher) HashPassword

func (h *PasswordHasher) HashPassword(password string) (string, error)

HashPassword hashes a password using bcrypt

func (*PasswordHasher) NeedsRehash

func (h *PasswordHasher) NeedsRehash(hashedPassword string) bool

NeedsRehash checks if a password hash needs to be regenerated with a new cost

func (*PasswordHasher) ValidatePassword

func (h *PasswordHasher) ValidatePassword(password string) error

ValidatePassword validates a password against configured requirements

type PasswordHasherConfig

type PasswordHasherConfig struct {
	Cost          int
	MinLength     int
	RequireUpper  bool
	RequireLower  bool
	RequireDigit  bool
	RequireSymbol bool
}

PasswordHasherConfig configures password requirements

type PasswordResetEmailSender

type PasswordResetEmailSender interface {
	SendPasswordReset(ctx context.Context, to, token, link string) error
}

PasswordResetEmailSender defines the interface for sending password reset emails

type PasswordResetRepository

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

PasswordResetRepository handles database operations for password reset tokens

func NewPasswordResetRepository

func NewPasswordResetRepository(db *database.Connection) *PasswordResetRepository

NewPasswordResetRepository creates a new password reset repository

func (*PasswordResetRepository) Create

func (r *PasswordResetRepository) Create(ctx context.Context, userID string, expiryDuration time.Duration) (*PasswordResetToken, error)

Create creates a new password reset token

func (*PasswordResetRepository) DeleteByUserID

func (r *PasswordResetRepository) DeleteByUserID(ctx context.Context, userID string) error

DeleteByUserID deletes all password reset tokens for a user

func (*PasswordResetRepository) DeleteExpired

func (r *PasswordResetRepository) DeleteExpired(ctx context.Context) (int64, error)

DeleteExpired deletes all expired password reset tokens

func (*PasswordResetRepository) GetByToken

func (r *PasswordResetRepository) GetByToken(ctx context.Context, token string) (*PasswordResetToken, error)

GetByToken retrieves a password reset token by token

func (*PasswordResetRepository) MarkAsUsed

func (r *PasswordResetRepository) MarkAsUsed(ctx context.Context, id string) error

MarkAsUsed marks a password reset token as used

func (*PasswordResetRepository) Validate

Validate validates a password reset token

type PasswordResetService

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

PasswordResetService provides password reset functionality

func NewPasswordResetService

func NewPasswordResetService(
	repo *PasswordResetRepository,
	userRepo *UserRepository,
	emailSender PasswordResetEmailSender,
	tokenExpiry time.Duration,
	baseURL string,
) *PasswordResetService

NewPasswordResetService creates a new password reset service

func (*PasswordResetService) RequestPasswordReset

func (s *PasswordResetService) RequestPasswordReset(ctx context.Context, email string) error

RequestPasswordReset sends a password reset email to the specified email

func (*PasswordResetService) ResetPassword

func (s *PasswordResetService) ResetPassword(ctx context.Context, token, newPassword string) error

ResetPassword resets a user's password using a valid reset token

func (*PasswordResetService) VerifyPasswordResetToken

func (s *PasswordResetService) VerifyPasswordResetToken(ctx context.Context, token string) error

VerifyPasswordResetToken verifies if a password reset token is valid

type PasswordResetToken

type PasswordResetToken struct {
	ID        string     `json:"id" db:"id"`
	UserID    string     `json:"user_id" db:"user_id"`
	Token     string     `json:"token" db:"token"`
	ExpiresAt time.Time  `json:"expires_at" db:"expires_at"`
	UsedAt    *time.Time `json:"used_at,omitempty" db:"used_at"`
	CreatedAt time.Time  `json:"created_at" db:"created_at"`
}

PasswordResetToken represents a password reset token

type RefreshTokenRequest

type RefreshTokenRequest struct {
	RefreshToken string `json:"refresh_token"`
}

RefreshTokenRequest represents a token refresh request

type RefreshTokenResponse

type RefreshTokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"` // seconds
}

RefreshTokenResponse represents a successful token refresh

type Service

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

Service provides a high-level authentication API

func NewService

func NewService(
	db *database.Connection,
	cfg *config.AuthConfig,
	emailService EmailSender,
	baseURL string,
) *Service

NewService creates a new authentication service

func (*Service) DisableTOTP

func (s *Service) DisableTOTP(ctx context.Context, userID, password string) error

DisableTOTP disables 2FA for a user

func (*Service) EnableTOTP

func (s *Service) EnableTOTP(ctx context.Context, userID, code string) ([]string, error)

EnableTOTP enables 2FA after verifying the TOTP code

func (*Service) GenerateTokensForUser

func (s *Service) GenerateTokensForUser(ctx context.Context, userID string) (*SignInResponse, error)

GenerateTokensForUser generates JWT tokens for a user after successful 2FA verification

func (*Service) GetActiveImpersonation

func (s *Service) GetActiveImpersonation(ctx context.Context, adminUserID string) (*ImpersonationSession, error)

GetActiveImpersonation gets the active impersonation session for an admin

func (*Service) GetOAuthManager

func (s *Service) GetOAuthManager() *OAuthManager

GetOAuthManager returns the OAuth manager for configuring providers

func (*Service) GetUser

func (s *Service) GetUser(ctx context.Context, accessToken string) (*User, error)

GetUser retrieves the current user by access token

func (*Service) IsSignupEnabled

func (s *Service) IsSignupEnabled() bool

IsSignupEnabled returns whether user signup is enabled

func (*Service) IsTOTPEnabled

func (s *Service) IsTOTPEnabled(ctx context.Context, userID string) (bool, error)

IsTOTPEnabled checks if 2FA is enabled for a user

func (*Service) IsTokenRevoked

func (s *Service) IsTokenRevoked(ctx context.Context, jti string) (bool, error)

IsTokenRevoked checks if a JWT token has been revoked

func (*Service) ListImpersonationSessions

func (s *Service) ListImpersonationSessions(ctx context.Context, adminUserID string, limit, offset int) ([]*ImpersonationSession, error)

ListImpersonationSessions lists impersonation sessions for audit purposes

func (*Service) RefreshToken

func (s *Service) RefreshToken(ctx context.Context, req RefreshTokenRequest) (*RefreshTokenResponse, error)

RefreshToken generates a new access token using a refresh token

func (*Service) RequestPasswordReset

func (s *Service) RequestPasswordReset(ctx context.Context, email string) error

RequestPasswordReset sends a password reset email

func (*Service) ResetPassword

func (s *Service) ResetPassword(ctx context.Context, token, newPassword string) error

ResetPassword resets a user's password using a valid reset token

func (*Service) RevokeAllUserTokens

func (s *Service) RevokeAllUserTokens(ctx context.Context, userID, reason string) error

RevokeAllUserTokens revokes all tokens for a specific user

func (*Service) RevokeToken

func (s *Service) RevokeToken(ctx context.Context, token, reason string) error

RevokeToken revokes a specific JWT token

func (s *Service) SendMagicLink(ctx context.Context, email string) error

SendMagicLink sends a magic link to the specified email

func (*Service) SetupTOTP

func (s *Service) SetupTOTP(ctx context.Context, userID string) (string, string, error)

SetupTOTP generates a new TOTP secret for 2FA setup

func (*Service) SignIn

func (s *Service) SignIn(ctx context.Context, req SignInRequest) (*SignInResponse, error)

SignIn authenticates a user with email and password

func (*Service) SignInAnonymous

func (s *Service) SignInAnonymous(ctx context.Context) (*SignInAnonymousResponse, error)

SignInAnonymous creates JWT tokens for an anonymous user (no database record)

func (*Service) SignOut

func (s *Service) SignOut(ctx context.Context, accessToken string) error

SignOut logs out a user by invalidating their session

func (*Service) SignUp

func (s *Service) SignUp(ctx context.Context, req SignUpRequest) (*SignUpResponse, error)

SignUp registers a new user with email and password

func (*Service) StartAnonImpersonation

func (s *Service) StartAnonImpersonation(ctx context.Context, adminUserID string, reason string, ipAddress string, userAgent string) (*StartImpersonationResponse, error)

StartAnonImpersonation starts an impersonation session as anonymous user

func (*Service) StartImpersonation

func (s *Service) StartImpersonation(ctx context.Context, adminUserID string, req StartImpersonationRequest) (*StartImpersonationResponse, error)

StartImpersonation starts an admin impersonation session

func (*Service) StartServiceImpersonation

func (s *Service) StartServiceImpersonation(ctx context.Context, adminUserID string, reason string, ipAddress string, userAgent string) (*StartImpersonationResponse, error)

StartServiceImpersonation starts an impersonation session with service role

func (*Service) StopImpersonation

func (s *Service) StopImpersonation(ctx context.Context, adminUserID string) error

StopImpersonation stops the active impersonation session for an admin

func (*Service) UpdateUser

func (s *Service) UpdateUser(ctx context.Context, userID string, req UpdateUserRequest) (*User, error)

UpdateUser updates user information

func (*Service) ValidateToken

func (s *Service) ValidateToken(token string) (*TokenClaims, error)

ValidateToken validates an access token and returns the claims

func (s *Service) VerifyMagicLink(ctx context.Context, token string) (*SignInResponse, error)

VerifyMagicLink verifies a magic link and returns tokens

func (*Service) VerifyPasswordResetToken

func (s *Service) VerifyPasswordResetToken(ctx context.Context, token string) error

VerifyPasswordResetToken verifies if a password reset token is valid

func (*Service) VerifyTOTP

func (s *Service) VerifyTOTP(ctx context.Context, userID, code string) error

VerifyTOTP verifies a TOTP code during login

type Session

type Session struct {
	ID           string    `json:"id" db:"id"`
	UserID       string    `json:"user_id" db:"user_id"`
	AccessToken  string    `json:"access_token" db:"access_token"`
	RefreshToken string    `json:"refresh_token" db:"refresh_token"`
	ExpiresAt    time.Time `json:"expires_at" db:"expires_at"`
	CreatedAt    time.Time `json:"created_at" db:"created_at"`
}

Session represents a user session

type SessionRepository

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

SessionRepository handles database operations for sessions

func NewSessionRepository

func NewSessionRepository(db *database.Connection) *SessionRepository

NewSessionRepository creates a new session repository

func (*SessionRepository) Count

func (r *SessionRepository) Count(ctx context.Context) (int, error)

Count returns the total number of active sessions

func (*SessionRepository) CountByUserID

func (r *SessionRepository) CountByUserID(ctx context.Context, userID string) (int, error)

CountByUserID returns the number of active sessions for a user

func (*SessionRepository) Create

func (r *SessionRepository) Create(ctx context.Context, userID, accessToken, refreshToken string, expiresAt time.Time) (*Session, error)

Create creates a new session

func (*SessionRepository) Delete

func (r *SessionRepository) Delete(ctx context.Context, id string) error

Delete deletes a session by ID

func (*SessionRepository) DeleteByAccessToken

func (r *SessionRepository) DeleteByAccessToken(ctx context.Context, accessToken string) error

DeleteByAccessToken deletes a session by access token

func (*SessionRepository) DeleteByUserID

func (r *SessionRepository) DeleteByUserID(ctx context.Context, userID string) error

DeleteByUserID deletes all sessions for a user

func (*SessionRepository) DeleteExpired

func (r *SessionRepository) DeleteExpired(ctx context.Context) (int64, error)

DeleteExpired deletes all expired sessions

func (*SessionRepository) GetByAccessToken

func (r *SessionRepository) GetByAccessToken(ctx context.Context, accessToken string) (*Session, error)

GetByAccessToken retrieves a session by access token

func (*SessionRepository) GetByRefreshToken

func (r *SessionRepository) GetByRefreshToken(ctx context.Context, refreshToken string) (*Session, error)

GetByRefreshToken retrieves a session by refresh token

func (*SessionRepository) GetByUserID

func (r *SessionRepository) GetByUserID(ctx context.Context, userID string) ([]*Session, error)

GetByUserID retrieves all sessions for a user

func (*SessionRepository) UpdateAccessToken

func (r *SessionRepository) UpdateAccessToken(ctx context.Context, id, accessToken string) error

UpdateAccessToken updates only the access token

func (*SessionRepository) UpdateTokens

func (r *SessionRepository) UpdateTokens(ctx context.Context, id, accessToken, refreshToken string, expiresAt time.Time) error

UpdateTokens updates the tokens for a session

type SettingsCache

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

SettingsCache provides a simple in-memory cache for settings with TTL

func NewSettingsCache

func NewSettingsCache(service *SystemSettingsService, ttl time.Duration) *SettingsCache

NewSettingsCache creates a new settings cache

func (*SettingsCache) GetBool

func (c *SettingsCache) GetBool(ctx context.Context, key string, defaultValue bool) bool

GetBool retrieves a boolean setting with caching

func (*SettingsCache) GetInt

func (c *SettingsCache) GetInt(ctx context.Context, key string, defaultValue int) int

GetInt retrieves an integer setting with caching

func (*SettingsCache) Invalidate

func (c *SettingsCache) Invalidate(key string)

Invalidate removes a key from the cache

func (*SettingsCache) InvalidateAll

func (c *SettingsCache) InvalidateAll()

InvalidateAll clears the entire cache

type SetupCompleteValue

type SetupCompleteValue struct {
	Completed       bool       `json:"completed"`
	CompletedAt     time.Time  `json:"completed_at"`
	FirstAdminID    *uuid.UUID `json:"first_admin_id,omitempty"`
	FirstAdminEmail *string    `json:"first_admin_email,omitempty"`
}

SetupCompleteValue represents the value stored for setup_completed setting

type SignInAnonymousResponse

type SignInAnonymousResponse struct {
	UserID       string `json:"user_id"` // Temporary anonymous user ID
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"`   // seconds
	IsAnonymous  bool   `json:"is_anonymous"` // Always true for anonymous users
}

SignInAnonymousResponse represents an anonymous user sign-in response

type SignInRequest

type SignInRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

SignInRequest represents a login request

type SignInResponse

type SignInResponse struct {
	User         *User  `json:"user"`
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"` // seconds
}

SignInResponse represents a successful login response

type SignUpRequest

type SignUpRequest struct {
	Email        string                 `json:"email"`
	Password     string                 `json:"password"`
	UserMetadata map[string]interface{} `json:"user_metadata,omitempty"` // User-editable metadata
	AppMetadata  map[string]interface{} `json:"app_metadata,omitempty"`  // Application/admin-only metadata
}

SignUpRequest represents a user registration request

type SignUpResponse

type SignUpResponse struct {
	User         *User  `json:"user"`
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"` // seconds
}

SignUpResponse represents a successful registration response

type StartImpersonationRequest

type StartImpersonationRequest struct {
	TargetUserID string `json:"target_user_id"`
	Reason       string `json:"reason"`
	IPAddress    string `json:"-"` // Set from request context
	UserAgent    string `json:"-"` // Set from request context
}

StartImpersonationRequest represents a request to start impersonating a user

type StartImpersonationResponse

type StartImpersonationResponse struct {
	Session      *ImpersonationSession `json:"session"`
	TargetUser   *User                 `json:"target_user"`
	AccessToken  string                `json:"access_token"`
	RefreshToken string                `json:"refresh_token"`
	ExpiresIn    int64                 `json:"expires_in"`
}

StartImpersonationResponse represents the response when starting impersonation

type StateStore

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

StateStore manages OAuth state tokens for CSRF protection

func NewStateStore

func NewStateStore() *StateStore

NewStateStore creates a new state store

func (*StateStore) Cleanup

func (s *StateStore) Cleanup()

Cleanup removes expired state tokens

func (*StateStore) Set

func (s *StateStore) Set(state string)

Set stores a state token

func (*StateStore) Validate

func (s *StateStore) Validate(state string) bool

Validate checks if a state token is valid and removes it

type SystemSetting

type SystemSetting struct {
	ID          uuid.UUID              `json:"id"`
	Key         string                 `json:"key"`
	Value       map[string]interface{} `json:"value"`
	Description string                 `json:"description,omitempty"`
	CreatedAt   time.Time              `json:"created_at"`
	UpdatedAt   time.Time              `json:"updated_at"`
}

SystemSetting represents a system-wide configuration setting

type SystemSettingsService

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

SystemSettingsService handles system-wide settings

func NewSystemSettingsService

func NewSystemSettingsService(db *database.Connection) *SystemSettingsService

NewSystemSettingsService creates a new system settings service

func (*SystemSettingsService) DeleteSetting

func (s *SystemSettingsService) DeleteSetting(ctx context.Context, key string) error

DeleteSetting removes a system setting by key

func (*SystemSettingsService) GetSetting

func (s *SystemSettingsService) GetSetting(ctx context.Context, key string) (*SystemSetting, error)

GetSetting retrieves a system setting by key

func (*SystemSettingsService) GetSetupInfo

GetSetupInfo retrieves setup completion information

func (*SystemSettingsService) IsSetupComplete

func (s *SystemSettingsService) IsSetupComplete(ctx context.Context) (bool, error)

IsSetupComplete checks if the initial setup has been completed

func (*SystemSettingsService) ListSettings

func (s *SystemSettingsService) ListSettings(ctx context.Context) ([]SystemSetting, error)

ListSettings retrieves all system settings

func (*SystemSettingsService) MarkSetupComplete

func (s *SystemSettingsService) MarkSetupComplete(ctx context.Context, adminID uuid.UUID, adminEmail string) error

MarkSetupComplete marks the setup as completed

func (*SystemSettingsService) SetSetting

func (s *SystemSettingsService) SetSetting(ctx context.Context, key string, value map[string]interface{}, description string) error

SetSetting creates or updates a system setting

type TokenBlacklistEntry

type TokenBlacklistEntry struct {
	ID        string    `json:"id" db:"id"`
	TokenJTI  string    `json:"token_jti" db:"token_jti"`
	UserID    string    `json:"user_id" db:"user_id"`
	Reason    string    `json:"reason" db:"reason"`
	RevokedAt time.Time `json:"revoked_at" db:"revoked_at"`
	ExpiresAt time.Time `json:"expires_at" db:"expires_at"`
}

TokenBlacklistEntry represents a blacklisted token

type TokenBlacklistRepository

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

TokenBlacklistRepository handles database operations for token blacklist

func NewTokenBlacklistRepository

func NewTokenBlacklistRepository(db *database.Connection) *TokenBlacklistRepository

NewTokenBlacklistRepository creates a new token blacklist repository

func (*TokenBlacklistRepository) Add

func (r *TokenBlacklistRepository) Add(ctx context.Context, jti, userID, reason string, expiresAt time.Time) error

Add adds a token to the blacklist

func (*TokenBlacklistRepository) DeleteByUser

func (r *TokenBlacklistRepository) DeleteByUser(ctx context.Context, userID string) error

DeleteByUser removes all blacklist entries for a user

func (*TokenBlacklistRepository) DeleteExpired

func (r *TokenBlacklistRepository) DeleteExpired(ctx context.Context) (int64, error)

DeleteExpired removes expired tokens from the blacklist

func (*TokenBlacklistRepository) GetByJTI

GetByJTI retrieves a blacklist entry by token JTI

func (*TokenBlacklistRepository) IsBlacklisted

func (r *TokenBlacklistRepository) IsBlacklisted(ctx context.Context, jti string) (bool, error)

IsBlacklisted checks if a token JTI is in the blacklist

func (*TokenBlacklistRepository) RevokeAllUserTokens

func (r *TokenBlacklistRepository) RevokeAllUserTokens(ctx context.Context, userID, reason string) error

RevokeAllUserTokens revokes all tokens for a specific user

type TokenBlacklistService

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

TokenBlacklistService provides token blacklisting/revocation functionality

func NewTokenBlacklistService

func NewTokenBlacklistService(repo *TokenBlacklistRepository, jwtManager *JWTManager) *TokenBlacklistService

NewTokenBlacklistService creates a new token blacklist service

func (*TokenBlacklistService) CleanupExpiredTokens

func (s *TokenBlacklistService) CleanupExpiredTokens(ctx context.Context) (int64, error)

CleanupExpiredTokens removes expired tokens from the blacklist

func (*TokenBlacklistService) IsTokenRevoked

func (s *TokenBlacklistService) IsTokenRevoked(ctx context.Context, jti string) (bool, error)

IsTokenRevoked checks if a token has been revoked

func (*TokenBlacklistService) RevokeAllUserTokens

func (s *TokenBlacklistService) RevokeAllUserTokens(ctx context.Context, userID, reason string) error

RevokeAllUserTokens revokes all tokens for a user

func (*TokenBlacklistService) RevokeToken

func (s *TokenBlacklistService) RevokeToken(ctx context.Context, token, reason string) error

RevokeToken revokes a specific token

type TokenClaims

type TokenClaims struct {
	UserID       string `json:"user_id"`
	Email        string `json:"email,omitempty"` // Empty for anonymous users
	Role         string `json:"role,omitempty"`
	SessionID    string `json:"session_id,omitempty"`    // Empty for anonymous users (no session)
	TokenType    string `json:"token_type"`              // "access" or "refresh"
	IsAnonymous  bool   `json:"is_anonymous,omitempty"`  // True for anonymous users
	UserMetadata any    `json:"user_metadata,omitempty"` // User-editable metadata
	AppMetadata  any    `json:"app_metadata,omitempty"`  // Application/admin-only metadata
	jwt.RegisteredClaims
}

TokenClaims represents the JWT claims

type UpdateUserRequest

type UpdateUserRequest struct {
	Email         *string `json:"email,omitempty"`
	EmailVerified *bool   `json:"email_verified,omitempty"`
	Role          *string `json:"role,omitempty"`
	UserMetadata  any     `json:"user_metadata,omitempty"` // User-editable metadata
	AppMetadata   any     `json:"app_metadata,omitempty"`  // Application/admin-only metadata (admin only)
}

UpdateUserRequest represents a request to update a user

type User

type User struct {
	ID            string    `json:"id" db:"id"`
	Email         string    `json:"email" db:"email"`
	PasswordHash  string    `json:"-" db:"password_hash"` // Never expose in JSON
	EmailVerified bool      `json:"email_verified" db:"email_verified"`
	Role          string    `json:"role,omitempty" db:"role"`
	UserMetadata  any       `json:"user_metadata,omitempty" db:"user_metadata"` // User-editable metadata
	AppMetadata   any       `json:"app_metadata,omitempty" db:"app_metadata"`   // Application/admin-only metadata
	CreatedAt     time.Time `json:"created_at" db:"created_at"`
	UpdatedAt     time.Time `json:"updated_at" db:"updated_at"`
}

User represents a user in the system

type UserManagementService

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

UserManagementService provides admin operations for user management

func NewUserManagementService

func NewUserManagementService(
	userRepo *UserRepository,
	sessionRepo *SessionRepository,
	passwordHasher *PasswordHasher,
	emailService EmailSender,
	baseURL string,
) *UserManagementService

NewUserManagementService creates a new user management service

func (*UserManagementService) DeleteUser

func (s *UserManagementService) DeleteUser(ctx context.Context, userID string, userType string) error

DeleteUser deletes a user (cascades to sessions, tokens, etc.)

func (*UserManagementService) GetEnrichedUserByID

func (s *UserManagementService) GetEnrichedUserByID(ctx context.Context, userID string, userType string) (*EnrichedUser, error)

GetEnrichedUserByID returns a single user with enriched metadata userType can be "app" for auth.users or "dashboard" for dashboard.users

func (*UserManagementService) InviteUser

InviteUser creates a new user and either sends them an invite email or returns a temp password

func (*UserManagementService) ListEnrichedUsers

func (s *UserManagementService) ListEnrichedUsers(ctx context.Context, userType string) ([]*EnrichedUser, error)

ListEnrichedUsers returns a list of users with enriched metadata userType can be "app" for auth.users or "dashboard" for dashboard.users

func (*UserManagementService) ResetUserPassword

func (s *UserManagementService) ResetUserPassword(ctx context.Context, userID string, userType string) (string, error)

ResetUserPassword triggers a password reset for a user

func (*UserManagementService) UpdateUserRole

func (s *UserManagementService) UpdateUserRole(ctx context.Context, userID string, newRole string, userType string) (*User, error)

UpdateUserRole updates a user's role

type UserRepository

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

UserRepository handles database operations for users

func NewUserRepository

func NewUserRepository(db *database.Connection) *UserRepository

NewUserRepository creates a new user repository

func (*UserRepository) Count

func (r *UserRepository) Count(ctx context.Context) (int, error)

Count returns the total number of users

func (*UserRepository) Create

func (r *UserRepository) Create(ctx context.Context, req CreateUserRequest, passwordHash string) (*User, error)

Create creates a new user

func (*UserRepository) CreateInTable

func (r *UserRepository) CreateInTable(ctx context.Context, req CreateUserRequest, passwordHash string, userType string) (*User, error)

CreateInTable creates a new user in the specified table (auth.users or dashboard.users)

func (*UserRepository) Delete

func (r *UserRepository) Delete(ctx context.Context, id string) error

Delete deletes a user

func (*UserRepository) DeleteFromTable

func (r *UserRepository) DeleteFromTable(ctx context.Context, id string, userType string) error

DeleteFromTable deletes a user from the specified table

func (*UserRepository) GetByEmail

func (r *UserRepository) GetByEmail(ctx context.Context, email string) (*User, error)

GetByEmail retrieves a user by email

func (*UserRepository) GetByID

func (r *UserRepository) GetByID(ctx context.Context, id string) (*User, error)

GetByID retrieves a user by ID

func (*UserRepository) GetByIDFromTable

func (r *UserRepository) GetByIDFromTable(ctx context.Context, id string, userType string) (*User, error)

GetByIDFromTable retrieves a user by ID from the specified table

func (*UserRepository) List

func (r *UserRepository) List(ctx context.Context, limit, offset int) ([]*User, error)

List retrieves users with pagination

func (*UserRepository) Update

func (r *UserRepository) Update(ctx context.Context, id string, req UpdateUserRequest) (*User, error)

Update updates a user

func (*UserRepository) UpdateInTable

func (r *UserRepository) UpdateInTable(ctx context.Context, id string, req UpdateUserRequest, userType string) (*User, error)

UpdateInTable updates a user in the specified table

func (*UserRepository) UpdatePassword

func (r *UserRepository) UpdatePassword(ctx context.Context, id string, newPasswordHash string) error

UpdatePassword updates a user's password

func (*UserRepository) VerifyEmail

func (r *UserRepository) VerifyEmail(ctx context.Context, id string) error

VerifyEmail marks a user's email as verified

Jump to

Keyboard shortcuts

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