auth

package
v0.0.0-...-51d4900 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2025 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EventLogin         = "login"
	EventLoginFailed   = "login_failed"
	EventPasswordReset = "password_reset"
	EventMFAEnabled    = "mfa_enabled"
	EventMFADisabled   = "mfa_disabled"
	EventAccountLocked = "account_locked"
	EventOAuthLogin    = "oauth_login"
)

Security event types

View Source
const (
	SessionFlagNormal         = 0
	SessionFlagSuspicious     = 1 << 0
	SessionFlagCompromised    = 1 << 1
	SessionFlagLocationChange = 1 << 2
	SessionFlagDeviceChange   = 1 << 3
)

Session security flags

Variables

View Source
var (
	ErrLDAPNotConfigured = errors.New("LDAP not configured")
	ErrLDAPConnection    = errors.New("LDAP connection failed")
	ErrLDAPAuth          = errors.New("LDAP authentication failed")
	ErrLDAPUserNotFound  = errors.New("LDAP user not found")
)
View Source
var (
	ErrOAuthProviderNotConfigured = errors.New("oauth provider not configured")
	ErrInvalidOAuthState          = errors.New("invalid oauth state")
	ErrOAuthCodeExchange          = errors.New("oauth code exchange failed")
	ErrOAuthUserInfo              = errors.New("failed to get oauth user info")
)
View Source
var (
	ErrOIDCNotConfigured   = errors.New("OIDC not configured")
	ErrInvalidOIDCToken    = errors.New("invalid OIDC token")
	ErrOIDCDiscoveryFailed = errors.New("OIDC discovery failed")
)
View Source
var (
	ErrSAMLNotConfigured    = errors.New("SAML not configured")
	ErrInvalidSAMLResponse  = errors.New("invalid SAML response")
	ErrSAMLSignatureInvalid = errors.New("SAML signature validation failed")
)
View Source
var (
	ErrInvalidCredentials = errors.New("invalid credentials")
	ErrUserExists         = errors.New("user already exists")
	ErrUserNotFound       = errors.New("user not found")
	ErrEmailNotVerified   = errors.New("email not verified")
	ErrAccountLocked      = errors.New("account is locked")
)
View Source
var DefaultRateLimitConfig = RateLimitConfig{
	MaxAttempts:     5,
	WindowDuration:  15 * time.Minute,
	LockoutDuration: 30 * time.Minute,
}

Functions

func CleanupExpiredData

func CleanupExpiredData(db *gorm.DB) error

CleanupExpiredData removes expired data from authentication tables

func MigrateAuthTables

func MigrateAuthTables(db *gorm.DB) error

MigrateAuthTables runs all authentication-related database migrations

func RepairDatabaseIntegrity

func RepairDatabaseIntegrity(db *gorm.DB) error

RepairDatabaseIntegrity attempts to fix common database integrity issues

func ValidateDatabaseIntegrity

func ValidateDatabaseIntegrity(db *gorm.DB) []string

ValidateDatabaseIntegrity checks for common database integrity issues

Types

type AccountLockout

type AccountLockout struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	UserID         uuid.UUID  `json:"user_id" gorm:"type:uuid;not null;index"`
	IPAddress      string     `json:"ip_address" gorm:"size:45;index"`
	Reason         string     `json:"reason" gorm:"size:255"`
	FailedAttempts int        `json:"failed_attempts" gorm:"default:0"`
	LockedUntil    *time.Time `json:"locked_until"`
	IsActive       bool       `json:"is_active" gorm:"default:true"`
}

Account lockout functionality

func (AccountLockout) TableName

func (AccountLockout) TableName() string

type AuditEvent

type AuditEvent string

Enhanced audit logging

const (
	AuditEventLogin              AuditEvent = "login"
	AuditEventLoginFailed        AuditEvent = "login_failed"
	AuditEventLogout             AuditEvent = "logout"
	AuditEventRegister           AuditEvent = "register"
	AuditEventPasswordChange     AuditEvent = "password_change"
	AuditEventPasswordReset      AuditEvent = "password_reset"
	AuditEventMFASetup           AuditEvent = "mfa_setup"
	AuditEventMFADisable         AuditEvent = "mfa_disable"
	AuditEventMFAFailed          AuditEvent = "mfa_failed"
	AuditEventOAuthLink          AuditEvent = "oauth_link"
	AuditEventOAuthUnlink        AuditEvent = "oauth_unlink"
	AuditEventSessionRevoked     AuditEvent = "session_revoked"
	AuditEventSuspiciousActivity AuditEvent = "suspicious_activity"
	AuditEventAccountLocked      AuditEvent = "account_locked"
	AuditEventAccountUnlocked    AuditEvent = "account_unlocked"
	AuditEventEmailVerified      AuditEvent = "email_verified"
	AuditEventProfileUpdated     AuditEvent = "profile_updated"
)

type AuditLog

type AuditLog struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	UserID     *uuid.UUID `json:"user_id" gorm:"type:uuid;index"`
	Event      string     `json:"event" gorm:"not null;size:50;index"`
	IPAddress  string     `json:"ip_address" gorm:"size:45;index"`
	UserAgent  string     `json:"user_agent" gorm:"size:255"`
	Details    string     `json:"details" gorm:"type:text"`
	Success    bool       `json:"success" gorm:"index"`
	RiskLevel  string     `json:"risk_level" gorm:"size:20;index"`
	SessionID  *uuid.UUID `json:"session_id" gorm:"type:uuid;index"`
	Location   string     `json:"location" gorm:"size:255"`
	DeviceInfo string     `json:"device_info" gorm:"size:255"`
}

func (AuditLog) TableName

func (AuditLog) TableName() string

type AuditService

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

func NewAuditService

func NewAuditService(db *gorm.DB) *AuditService

func (*AuditService) CleanupOldAuditLogs

func (a *AuditService) CleanupOldAuditLogs(retentionDays int) error

Cleanup expired audit logs (should be run periodically)

func (*AuditService) GetHighRiskEvents

func (a *AuditService) GetHighRiskEvents(limit int) ([]AuditLog, error)

func (*AuditService) GetSecurityEventsAudit

func (a *AuditService) GetSecurityEventsAudit(userID uuid.UUID, limit int) ([]AuditLog, error)

func (*AuditService) GetSecurityMetrics

func (a *AuditService) GetSecurityMetrics() (*SecurityMetrics, error)

func (*AuditService) GetUserAuditLogs

func (a *AuditService) GetUserAuditLogs(userID uuid.UUID, limit int, offset int) ([]AuditLog, error)

func (*AuditService) LogEvent

func (a *AuditService) LogEvent(userID *uuid.UUID, event AuditEvent, ipAddress, userAgent, details string, success bool) error

func (*AuditService) LogEventWithSession

func (a *AuditService) LogEventWithSession(userID *uuid.UUID, sessionID *uuid.UUID, event AuditEvent, ipAddress, userAgent, details string, success bool) error

type AuthResponse

type AuthResponse struct {
	User         *models.User `json:"user"`
	AccessToken  string       `json:"access_token"`
	RefreshToken string       `json:"refresh_token"`
	ExpiresIn    int64        `json:"expires_in"`
}

type AuthService

type AuthService interface {
	Login(ctx context.Context, req LoginRequest) (*AuthResponse, error)
	Register(ctx context.Context, req RegisterRequest) (*models.User, error)
	RefreshToken(ctx context.Context, refreshToken string) (*AuthResponse, error)
	Logout(ctx context.Context, userID uuid.UUID) error
	VerifyToken(ctx context.Context, token string) (*models.User, error)
	RequestPasswordReset(ctx context.Context, req PasswordResetRequest) error
	ResetPassword(ctx context.Context, req PasswordResetConfirmRequest) error
	VerifyEmail(ctx context.Context, token string) error
	ResendVerificationEmail(ctx context.Context, userID uuid.UUID) error
	// Legacy methods for backward compatibility
	GetUserByID(userID uuid.UUID) (*models.User, error)
	GetUserByEmail(email string) (*models.User, error)
	GetUserByUsername(username string) (*models.User, error)
	UpdateUser(user *models.User) error
	ValidateToken(tokenString string) (*models.User, error)
}

func NewAuthService

func NewAuthService(db *gorm.DB, jwtManager *JWTManager, cfg *config.Config) AuthService

type BackupCode

type BackupCode struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	UserID uuid.UUID  `json:"user_id" gorm:"type:uuid;not null;index"`
	Code   string     `json:"code" gorm:"not null;size:255"`
	Used   bool       `json:"used" gorm:"default:false"`
	UsedAt *time.Time `json:"used_at"`

	// Relationships
	User models.User `json:"user,omitempty" gorm:"foreignKey:UserID"`
}

func (*BackupCode) TableName

func (b *BackupCode) TableName() string

type Claims

type Claims struct {
	UserID   uuid.UUID `json:"user_id"`
	Username string    `json:"username"`
	Email    string    `json:"email"`
	// Roles granted to the user from external identity or group mapping
	Roles   []string `json:"roles,omitempty"`
	IsAdmin bool     `json:"is_admin"`
	jwt.RegisteredClaims
}

type DatabaseStats

type DatabaseStats struct {
	TotalUsers           int64 `json:"total_users"`
	ActiveUsers          int64 `json:"active_users"`
	VerifiedUsers        int64 `json:"verified_users"`
	MFAEnabledUsers      int64 `json:"mfa_enabled_users"`
	ActiveSessions       int64 `json:"active_sessions"`
	TotalSessions        int64 `json:"total_sessions"`
	OAuthAccounts        int64 `json:"oauth_accounts"`
	RecentLogins24h      int64 `json:"recent_logins_24h"`
	FailedLogins24h      int64 `json:"failed_logins_24h"`
	SecurityEvents24h    int64 `json:"security_events_24h"`
	PendingVerifications int64 `json:"pending_verifications"`
}

GetDatabaseStats returns statistics about authentication tables

func GetDatabaseStats

func GetDatabaseStats(db *gorm.DB) (*DatabaseStats, error)

type EmailService

type EmailService interface {
	SendPasswordResetEmail(to, token string) error
	SendEmailVerification(to, token string) error
	SendMFASetupEmail(to string, backupCodes []string) error
}

Email service interface for sending password reset emails

func NewSMTPEmailService

func NewSMTPEmailService(cfg *config.Config) EmailService

type EmailTemplate

type EmailTemplate struct {
	Subject  string
	HTMLBody string
	TextBody string
}

Enhanced email service with templates

type EmailVerificationService

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

func NewEmailVerificationService

func NewEmailVerificationService(db *gorm.DB, emailService EmailService) *EmailVerificationService

func (*EmailVerificationService) CleanupExpiredTokens

func (s *EmailVerificationService) CleanupExpiredTokens() error

func (*EmailVerificationService) CreateVerificationToken

func (s *EmailVerificationService) CreateVerificationToken(userID uuid.UUID) (*EmailVerificationToken, error)

func (*EmailVerificationService) GetVerificationStatus

func (s *EmailVerificationService) GetVerificationStatus(userID uuid.UUID) (bool, *EmailVerificationToken, error)

Helper method to get verification status and token info

func (*EmailVerificationService) IsEmailVerified

func (s *EmailVerificationService) IsEmailVerified(userID uuid.UUID) (bool, error)

func (*EmailVerificationService) RevokeUserTokens

func (s *EmailVerificationService) RevokeUserTokens(userID uuid.UUID) error

func (*EmailVerificationService) SendVerificationEmail

func (s *EmailVerificationService) SendVerificationEmail(userID uuid.UUID) error

func (*EmailVerificationService) VerifyEmail

func (s *EmailVerificationService) VerifyEmail(token string) error

type EmailVerificationToken

type EmailVerificationToken struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	UserID    uuid.UUID  `json:"user_id" gorm:"type:uuid;not null;index"`
	Token     string     `json:"-" gorm:"not null;uniqueIndex;size:255"`
	ExpiresAt time.Time  `json:"expires_at" gorm:"not null"`
	Used      bool       `json:"used" gorm:"default:false"`
	UsedAt    *time.Time `json:"used_at"`

	// Relationships
	User models.User `json:"user,omitempty" gorm:"foreignKey:UserID"`
}

func (EmailVerificationToken) TableName

func (EmailVerificationToken) TableName() string

type GitHubProvider

type GitHubProvider struct {
	ClientID     string
	ClientSecret string
}

GitHub OAuth Provider

func (*GitHubProvider) ExchangeCode

func (p *GitHubProvider) ExchangeCode(code, redirectURI string) (*OAuthToken, error)

func (*GitHubProvider) GetAuthURL

func (p *GitHubProvider) GetAuthURL(state, redirectURI string) string

func (*GitHubProvider) GetProviderName

func (p *GitHubProvider) GetProviderName() string

func (*GitHubProvider) GetUserInfo

func (p *GitHubProvider) GetUserInfo(token *OAuthToken) (*OAuthUserInfo, error)

type GitLabProvider

type GitLabProvider struct {
	ClientID     string
	ClientSecret string
	BaseURL      string // For self-hosted GitLab instances
}

GitLab OAuth Provider

func (*GitLabProvider) ExchangeCode

func (p *GitLabProvider) ExchangeCode(code, redirectURI string) (*OAuthToken, error)

func (*GitLabProvider) GetAuthURL

func (p *GitLabProvider) GetAuthURL(state, redirectURI string) string

func (*GitLabProvider) GetProviderName

func (p *GitLabProvider) GetProviderName() string

func (*GitLabProvider) GetUserInfo

func (p *GitLabProvider) GetUserInfo(token *OAuthToken) (*OAuthUserInfo, error)

type GoogleProvider

type GoogleProvider struct {
	ClientID     string
	ClientSecret string
}

Google OAuth Provider

func (*GoogleProvider) ExchangeCode

func (p *GoogleProvider) ExchangeCode(code, redirectURI string) (*OAuthToken, error)

func (*GoogleProvider) GetAuthURL

func (p *GoogleProvider) GetAuthURL(state, redirectURI string) string

func (*GoogleProvider) GetProviderName

func (p *GoogleProvider) GetProviderName() string

func (*GoogleProvider) GetUserInfo

func (p *GoogleProvider) GetUserInfo(token *OAuthToken) (*OAuthUserInfo, error)

type JITProvisioningConfig

type JITProvisioningConfig struct {
	Enabled             bool              `json:"enabled" mapstructure:"enabled"`
	DefaultRole         string            `json:"default_role" mapstructure:"default_role"`
	AttributeMapping    map[string]string `json:"attribute_mapping" mapstructure:"attribute_mapping"`
	GroupMapping        map[string]string `json:"group_mapping" mapstructure:"group_mapping"`
	CreateOrganizations bool              `json:"create_organizations" mapstructure:"create_organizations"`
}

Just-in-Time (JIT) user provisioning JITProvisioningConfig holds just-in-time provisioning settings for OIDC users

type JWTManager

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

func NewJWTManager

func NewJWTManager(cfg config.JWT) *JWTManager

func (*JWTManager) GenerateToken

func (j *JWTManager) GenerateToken(user *models.User) (string, error)

func (*JWTManager) ValidateToken

func (j *JWTManager) ValidateToken(tokenString string) (*Claims, error)

type LDAPConnection

type LDAPConnection interface {
	Bind(username, password string) error
	Search(baseDN, filter string, attributes []string) ([]LDAPSearchResult, error)
	Close() error
}

LDAP Connection interface for testing

type LDAPSearchResult

type LDAPSearchResult struct {
	DN         string
	Attributes map[string][]string
}

type LDAPService

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

func NewLDAPService

func NewLDAPService(db *gorm.DB, jwtManager *JWTManager, cfg *config.Config, authSvc AuthService) (*LDAPService, error)

func (*LDAPService) Authenticate

func (s *LDAPService) Authenticate(username, password string) (*AuthResponse, error)

func (*LDAPService) SyncUsers

func (s *LDAPService) SyncUsers() error

LDAP user synchronization

func (*LDAPService) TestConnection

func (s *LDAPService) TestConnection() error

Test LDAP connection

type LDAPUserInfo

type LDAPUserInfo struct {
	DN          string
	Username    string
	Email       string
	FirstName   string
	LastName    string
	DisplayName string
	Groups      []string
	Attributes  map[string][]string
}

LDAP User Information

type LoggingSMSProvider

type LoggingSMSProvider struct{}

LoggingSMSProvider logs SMS messages when no real provider is configured

func (*LoggingSMSProvider) SendSMS

func (p *LoggingSMSProvider) SendSMS(phoneNumber, message string) error

type LoginAttempt

type LoginAttempt struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	UserID     *uuid.UUID `json:"user_id,omitempty" gorm:"type:uuid;index"`
	Email      string     `json:"email" gorm:"not null;size:255;index"`
	IPAddress  string     `json:"ip_address" gorm:"not null;size:45;index"`
	Success    bool       `json:"success" gorm:"not null;index"`
	UserAgent  string     `json:"user_agent" gorm:"size:255"`
	FailReason string     `json:"fail_reason" gorm:"size:255"`
}

func (LoginAttempt) TableName

func (LoginAttempt) TableName() string

type LoginRequest

type LoginRequest struct {
	Email    string `json:"email" binding:"required,email"`
	Password string `json:"password" binding:"required,min=6"`
	MFACode  string `json:"mfa_code,omitempty"`
}

type MFAService

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

func NewMFAService

func NewMFAService(db *gorm.DB) *MFAService

func NewMFAServiceWithEmail

func NewMFAServiceWithEmail(db *gorm.DB, emailService EmailService) *MFAService

func (*MFAService) CompleteWebAuthnRegistration

func (s *MFAService) CompleteWebAuthnRegistration(userID uuid.UUID, credentialName string, publicKeyBytes []byte, credentialID string) error

func (*MFAService) DeleteWebAuthnCredential

func (s *MFAService) DeleteWebAuthnCredential(userID uuid.UUID, credentialID string) error

func (*MFAService) DisableMFA

func (s *MFAService) DisableMFA(userID uuid.UUID) error

func (*MFAService) GetWebAuthnCredentials

func (s *MFAService) GetWebAuthnCredentials(userID uuid.UUID) ([]WebAuthnCredential, error)

func (*MFAService) InitiateWebAuthnRegistration

func (s *MFAService) InitiateWebAuthnRegistration(userID uuid.UUID, credentialName string) (*WebAuthnRegistrationResponse, error)

func (*MFAService) RegenerateBackupCodes

func (s *MFAService) RegenerateBackupCodes(userID uuid.UUID) ([]string, error)

func (*MFAService) SendSMSCode

func (s *MFAService) SendSMSCode(userID uuid.UUID, phoneNumber string) error

SMS MFA methods

func (*MFAService) SetupTOTP

func (s *MFAService) SetupTOTP(userID uuid.UUID, issuer, accountName string) (*MFASetupResponse, error)

func (*MFAService) VerifyMFACode

func (s *MFAService) VerifyMFACode(userID uuid.UUID, code string) (bool, error)

VerifyMFACode verifies any type of MFA code for login

func (*MFAService) VerifyTOTP

func (s *MFAService) VerifyTOTP(userID uuid.UUID, secret, code string) (bool, error)

type MFASetupRequest

type MFASetupRequest struct {
	UserID uuid.UUID `json:"user_id"`
}

type MFASetupResponse

type MFASetupResponse struct {
	Secret      string   `json:"secret"`
	QRCodeURL   string   `json:"qr_code_url"`
	BackupCodes []string `json:"backup_codes"`
}

type MFAVerifyRequest

type MFAVerifyRequest struct {
	UserID uuid.UUID `json:"user_id"`
	Code   string    `json:"code"`
}

type MicrosoftProvider

type MicrosoftProvider struct {
	ClientID     string
	ClientSecret string
	TenantID     string
}

Microsoft OAuth Provider

func (*MicrosoftProvider) ExchangeCode

func (p *MicrosoftProvider) ExchangeCode(code, redirectURI string) (*OAuthToken, error)

func (*MicrosoftProvider) GetAuthURL

func (p *MicrosoftProvider) GetAuthURL(state, redirectURI string) string

func (*MicrosoftProvider) GetProviderName

func (p *MicrosoftProvider) GetProviderName() string

func (*MicrosoftProvider) GetUserInfo

func (p *MicrosoftProvider) GetUserInfo(token *OAuthToken) (*OAuthUserInfo, error)

type MockEmailService

type MockEmailService struct{}

Mock email service for development

func (*MockEmailService) SendEmailVerification

func (s *MockEmailService) SendEmailVerification(to, token string) error

func (*MockEmailService) SendMFASetupEmail

func (s *MockEmailService) SendMFASetupEmail(to string, backupCodes []string) error

func (*MockEmailService) SendPasswordResetEmail

func (s *MockEmailService) SendPasswordResetEmail(to, token string) error

type MockLDAPConnection

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

Mock LDAP connection for development/testing

func NewMockLDAPConnection

func NewMockLDAPConnection() *MockLDAPConnection

func (*MockLDAPConnection) Bind

func (m *MockLDAPConnection) Bind(username, password string) error

func (*MockLDAPConnection) Close

func (m *MockLDAPConnection) Close() error

func (*MockLDAPConnection) Search

func (m *MockLDAPConnection) Search(baseDN, filter string, attributes []string) ([]LDAPSearchResult, error)

type MockLDAPUser

type MockLDAPUser struct {
	DN          string
	Password    string
	Email       string
	FirstName   string
	LastName    string
	DisplayName string
	Groups      []string
}

type OAuthAccount

type OAuthAccount struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	UserID       uuid.UUID  `json:"user_id" gorm:"type:uuid;not null;index"`
	Provider     string     `json:"provider" gorm:"not null;size:50"`
	ProviderID   string     `json:"provider_id" gorm:"not null;size:255"`
	Email        string     `json:"email" gorm:"size:255"`
	Username     string     `json:"username" gorm:"size:255"`
	AccessToken  string     `json:"-" gorm:"type:text"`
	RefreshToken string     `json:"-" gorm:"type:text"`
	ExpiresAt    *time.Time `json:"expires_at"`

	// Relationships
	User models.User `json:"user,omitempty" gorm:"foreignKey:UserID"`
}

Enhanced OAuth service with account linking

func (*OAuthAccount) TableName

func (o *OAuthAccount) TableName() string

type OAuthProvider

type OAuthProvider interface {
	GetAuthURL(state string, redirectURI string) string
	ExchangeCode(code, redirectURI string) (*OAuthToken, error)
	GetUserInfo(token *OAuthToken) (*OAuthUserInfo, error)
	GetProviderName() string
}

type OAuthService

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

func NewOAuthService

func NewOAuthService(db *gorm.DB, jwtManager *JWTManager, cfg *config.Config, authSvc AuthService) *OAuthService

func (*OAuthService) CleanupExpiredStates

func (s *OAuthService) CleanupExpiredStates() error

func (*OAuthService) GenerateState

func (s *OAuthService) GenerateState() (string, error)

func (*OAuthService) GetLinkedAccounts

func (s *OAuthService) GetLinkedAccounts(userID uuid.UUID) ([]OAuthAccount, error)

func (*OAuthService) GetProvider

func (s *OAuthService) GetProvider(name string) (OAuthProvider, error)

func (*OAuthService) HandleCallback

func (s *OAuthService) HandleCallback(ctx context.Context, providerName, code, state, redirectURI string) (*AuthResponse, error)

func (*OAuthService) InitiateOAuth

func (s *OAuthService) InitiateOAuth(provider, redirectURI string) (string, string, error)

func (*OAuthService) LinkAccount

func (s *OAuthService) LinkAccount(userID uuid.UUID, provider string, userInfo *OAuthUserInfo, token *OAuthToken) error

OAuth account linking methods

func (*OAuthService) StoreState

func (s *OAuthService) StoreState(state, provider string) error

func (*OAuthService) UnlinkAccount

func (s *OAuthService) UnlinkAccount(userID uuid.UUID, provider string) error

func (*OAuthService) ValidateState

func (s *OAuthService) ValidateState(state, provider string) error

type OAuthState

type OAuthState struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	State     string    `json:"state" gorm:"not null;uniqueIndex;size:255"`
	Provider  string    `json:"provider" gorm:"not null;size:50"`
	ExpiresAt time.Time `json:"expires_at" gorm:"not null"`
	Used      bool      `json:"used" gorm:"default:false"`
}

OAuth state management for security

func (*OAuthState) TableName

func (o *OAuthState) TableName() string

type OAuthToken

type OAuthToken struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	RefreshToken string `json:"refresh_token,omitempty"`
	ExpiresIn    int    `json:"expires_in,omitempty"`
	Scope        string `json:"scope,omitempty"`
}

type OAuthUserInfo

type OAuthUserInfo struct {
	ID       string `json:"id"`
	Username string `json:"username"`
	Email    string `json:"email"`
	Name     string `json:"name"`
	Avatar   string `json:"avatar"`
}

type OIDCClaims

type OIDCClaims struct {
	Sub               string   `json:"sub"`
	Name              string   `json:"name"`
	GivenName         string   `json:"given_name"`
	FamilyName        string   `json:"family_name"`
	PreferredUsername string   `json:"preferred_username"`
	Email             string   `json:"email"`
	EmailVerified     bool     `json:"email_verified"`
	Picture           string   `json:"picture"`
	Groups            []string `json:"groups"`
	Roles             []string `json:"roles"`
}

OIDC Claims

type OIDCDiscoveryDocument

type OIDCDiscoveryDocument struct {
	Issuer                 string   `json:"issuer"`
	AuthorizationEndpoint  string   `json:"authorization_endpoint"`
	TokenEndpoint          string   `json:"token_endpoint"`
	UserinfoEndpoint       string   `json:"userinfo_endpoint"`
	JwksURI                string   `json:"jwks_uri"`
	ScopesSupported        []string `json:"scopes_supported"`
	ResponseTypesSupported []string `json:"response_types_supported"`
}

OIDC Discovery Document

type OIDCProvider

type OIDCProvider struct {
	Name         string
	ClientID     string
	ClientSecret string
	IssuerURL    string
	RedirectURI  string
	Scopes       []string
	// contains filtered or unexported fields
}

type OIDCService

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

func NewOIDCService

func NewOIDCService(db *gorm.DB, jwtManager *JWTManager, cfg *config.Config, authSvc AuthService) (*OIDCService, error)

func (*OIDCService) GenerateAuthURL

func (s *OIDCService) GenerateAuthURL(providerName, state string) (string, error)

func (*OIDCService) GetProvider

func (s *OIDCService) GetProvider(name string) (*OIDCProvider, error)

func (*OIDCService) HandleCallback

func (s *OIDCService) HandleCallback(ctx context.Context, providerName, code, state string) (*AuthResponse, error)

func (*OIDCService) ProvisionUser

func (s *OIDCService) ProvisionUser(claims *OIDCClaims, config *JITProvisioningConfig) (*models.User, error)

type OIDCTokenResponse

type OIDCTokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int    `json:"expires_in"`
	IDToken      string `json:"id_token"`
	Scope        string `json:"scope"`
}

OIDC Token Response

type PasswordResetConfirmRequest

type PasswordResetConfirmRequest struct {
	Token    string `json:"token" binding:"required"`
	Password string `json:"password" binding:"required,min=12"`
}

type PasswordResetRequest

type PasswordResetRequest struct {
	Email string `json:"email" binding:"required,email"`
}

type PasswordResetService

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

func NewPasswordResetService

func NewPasswordResetService(db *gorm.DB) *PasswordResetService

func (*PasswordResetService) CleanupExpiredTokens

func (s *PasswordResetService) CleanupExpiredTokens() error

func (*PasswordResetService) CreateResetToken

func (s *PasswordResetService) CreateResetToken(userID uuid.UUID) (*PasswordResetToken, error)

func (*PasswordResetService) RevokeUserTokens

func (s *PasswordResetService) RevokeUserTokens(userID uuid.UUID) error

func (*PasswordResetService) UseResetToken

func (s *PasswordResetService) UseResetToken(token string, newPassword string) error

func (*PasswordResetService) ValidateResetToken

func (s *PasswordResetService) ValidateResetToken(token string) (*PasswordResetToken, error)

type PasswordResetToken

type PasswordResetToken struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	UserID    uuid.UUID  `json:"user_id" gorm:"type:uuid;not null;index"`
	Token     string     `json:"-" gorm:"not null;uniqueIndex;size:255"`
	ExpiresAt time.Time  `json:"expires_at" gorm:"not null"`
	Used      bool       `json:"used" gorm:"default:false"`
	UsedAt    *time.Time `json:"used_at"`

	// Relationships
	User models.User `json:"user,omitempty" gorm:"foreignKey:UserID"`
}

func (PasswordResetToken) TableName

func (PasswordResetToken) TableName() string

type RateLimitConfig

type RateLimitConfig struct {
	MaxAttempts     int           // Maximum failed attempts
	WindowDuration  time.Duration // Time window for rate limiting
	LockoutDuration time.Duration // How long to lock account
}

Rate limiting configuration

type RateLimiter

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

Rate Limiting

func NewRateLimiter

func NewRateLimiter(limit int, window time.Duration) *RateLimiter

func (*RateLimiter) Cleanup

func (rl *RateLimiter) Cleanup()

func (*RateLimiter) IsAllowed

func (rl *RateLimiter) IsAllowed(key string) bool

type RegisterRequest

type RegisterRequest struct {
	Username string `json:"username" binding:"required,min=3,max=50"`
	Email    string `json:"email" binding:"required,email"`
	Password string `json:"password" binding:"required,min=12"`
	FullName string `json:"full_name" binding:"required,min=1,max=255"`
}

type SAMLRequest

type SAMLRequest struct {
	XMLName      xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:protocol AuthnRequest"`
	ID           string   `xml:"ID,attr"`
	Version      string   `xml:"Version,attr"`
	IssueInstant string   `xml:"IssueInstant,attr"`
	Issuer       struct {
		Value string `xml:",chardata"`
	} `xml:"urn:oasis:names:tc:SAML:2.0:assertion Issuer"`
}

type SAMLResponse

type SAMLResponse struct {
	XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:protocol Response"`
	ID      string   `xml:"ID,attr"`
	Status  struct {
		StatusCode struct {
			Value string `xml:"Value,attr"`
		} `xml:"urn:oasis:names:tc:SAML:2.0:protocol StatusCode"`
	} `xml:"urn:oasis:names:tc:SAML:2.0:protocol Status"`
	Assertion struct {
		Subject struct {
			NameID struct {
				Value string `xml:",chardata"`
			} `xml:"urn:oasis:names:tc:SAML:2.0:assertion NameID"`
		} `xml:"urn:oasis:names:tc:SAML:2.0:assertion Subject"`
		AttributeStatement struct {
			Attributes []struct {
				Name   string `xml:"Name,attr"`
				Values []struct {
					Value string `xml:",chardata"`
				} `xml:"urn:oasis:names:tc:SAML:2.0:assertion AttributeValue"`
			} `xml:"urn:oasis:names:tc:SAML:2.0:assertion Attribute"`
		} `xml:"urn:oasis:names:tc:SAML:2.0:assertion AttributeStatement"`
	} `xml:"urn:oasis:names:tc:SAML:2.0:assertion Assertion"`
}

SAML Response structures

type SAMLService

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

func NewSAMLService

func NewSAMLService(db *gorm.DB, jwtManager *JWTManager, cfg *config.Config, authSvc AuthService) (*SAMLService, error)

func (*SAMLService) GenerateAuthRequest

func (s *SAMLService) GenerateAuthRequest(relayState string) (string, error)

func (*SAMLService) GenerateMetadata

func (s *SAMLService) GenerateMetadata() (string, error)

SAML metadata generation

func (*SAMLService) ProcessResponse

func (s *SAMLService) ProcessResponse(samlResponse string, relayState string) (*AuthResponse, error)

type SAMLUserInfo

type SAMLUserInfo struct {
	ID       string
	Email    string
	Username string
	Name     string
	Groups   []string
}

type SMSProvider

type SMSProvider interface {
	SendSMS(phoneNumber, message string) error
}

SMS MFA (placeholder implementation)

type SMSService

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

func NewSMSService

func NewSMSService(provider SMSProvider) *SMSService

func (*SMSService) SendMFACode

func (s *SMSService) SendMFACode(phoneNumber string) (string, error)

type SMSVerificationCode

type SMSVerificationCode struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	UserID    uuid.UUID  `json:"user_id" gorm:"type:uuid;not null;index"`
	Code      string     `json:"code" gorm:"not null;size:10"`
	ExpiresAt time.Time  `json:"expires_at" gorm:"not null"`
	Used      bool       `json:"used" gorm:"default:false"`
	UsedAt    *time.Time `json:"used_at"`

	// Relationships
	User models.User `json:"user,omitempty" gorm:"foreignKey:UserID"`
}

func (*SMSVerificationCode) TableName

func (s *SMSVerificationCode) TableName() string

type SMTPEmailService

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

func (*SMTPEmailService) SendEmailVerification

func (s *SMTPEmailService) SendEmailVerification(to, token string) error

func (*SMTPEmailService) SendMFASetupEmail

func (s *SMTPEmailService) SendMFASetupEmail(to string, backupCodes []string) error

func (*SMTPEmailService) SendPasswordResetEmail

func (s *SMTPEmailService) SendPasswordResetEmail(to, token string) error

type SecurityEvent

type SecurityEvent struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	UserID    *uuid.UUID `json:"user_id,omitempty" gorm:"type:uuid;index"`
	EventType string     `json:"event_type" gorm:"not null;size:50;index"`
	IPAddress string     `json:"ip_address" gorm:"size:45;index"`
	UserAgent string     `json:"user_agent" gorm:"size:255"`
	Details   string     `json:"details" gorm:"type:text"`
	Severity  string     `json:"severity" gorm:"size:20;default:'info'"` // info, warning, critical
}

func (SecurityEvent) TableName

func (SecurityEvent) TableName() string

type SecurityMetrics

type SecurityMetrics struct {
	FailedLogins24h       int64 `json:"failed_logins_24h"`
	SuspiciousActivity24h int64 `json:"suspicious_activity_24h"`
	AccountLockouts24h    int64 `json:"account_lockouts_24h"`
	ActiveSessions        int64 `json:"active_sessions"`
	UnusualLocations24h   int64 `json:"unusual_locations_24h"`
}

Security metrics

type SecurityService

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

func NewSecurityService

func NewSecurityService(db *gorm.DB) *SecurityService

func (*SecurityService) CheckGeneralRateLimit

func (s *SecurityService) CheckGeneralRateLimit(ipAddress string) bool

func (*SecurityService) CheckLoginRateLimit

func (s *SecurityService) CheckLoginRateLimit(ipAddress string) bool

Enhanced rate limiting methods

func (*SecurityService) CheckMFARateLimit

func (s *SecurityService) CheckMFARateLimit(ipAddress string) bool

func (*SecurityService) CheckPasswordResetRateLimit

func (s *SecurityService) CheckPasswordResetRateLimit(ipAddress string) bool

func (*SecurityService) CheckRateLimit

func (s *SecurityService) CheckRateLimit(email, ipAddress string, config RateLimitConfig) error

func (*SecurityService) CheckRegistrationRateLimit

func (s *SecurityService) CheckRegistrationRateLimit(ipAddress string) bool

func (*SecurityService) CleanupOldEvents

func (s *SecurityService) CleanupOldEvents(daysToKeep int) error

func (*SecurityService) GetSecurityEvents

func (s *SecurityService) GetSecurityEvents(userID uuid.UUID, limit int) ([]SecurityEvent, error)

func (*SecurityService) GetSuspiciousActivity

func (s *SecurityService) GetSuspiciousActivity(hoursBack int) ([]SecurityEvent, error)

func (*SecurityService) IsAccountLocked

func (s *SecurityService) IsAccountLocked(email string, config RateLimitConfig) (bool, time.Time)

func (*SecurityService) RecordLoginAttempt

func (s *SecurityService) RecordLoginAttempt(userID *uuid.UUID, email, ipAddress, userAgent string, success bool, failReason string) error

func (*SecurityService) RecordSecurityEvent

func (s *SecurityService) RecordSecurityEvent(userID *uuid.UUID, eventType, ipAddress, userAgent, details, severity string) error

func (*SecurityService) RunPeriodicCleanup

func (s *SecurityService) RunPeriodicCleanup()

Periodic cleanup function for security service

func (*SecurityService) ValidateIPAddress

func (s *SecurityService) ValidateIPAddress(ipStr string) error

func (*SecurityService) ValidatePasswordStrength

func (s *SecurityService) ValidatePasswordStrength(password string) []string

Password strength validation

type Session

type Session struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	UserID        uuid.UUID `json:"user_id" gorm:"type:uuid;not null;index"`
	RefreshToken  string    `json:"-" gorm:"not null;uniqueIndex;size:255"`
	ExpiresAt     time.Time `json:"expires_at" gorm:"not null"`
	IPAddress     string    `json:"ip_address" gorm:"size:45"`
	UserAgent     string    `json:"user_agent" gorm:"size:255"`
	IsActive      bool      `json:"is_active" gorm:"default:true"`
	LastUsedAt    time.Time `json:"last_used_at"`
	DeviceName    string    `json:"device_name" gorm:"size:255"`
	LocationInfo  string    `json:"location_info" gorm:"size:255"`
	IsRemembered  bool      `json:"is_remembered" gorm:"default:false"`
	SecurityFlags int       `json:"security_flags" gorm:"default:0"`
}

func (Session) TableName

func (Session) TableName() string

type SessionConfig

type SessionConfig struct {
	MaxSessions          int           `json:"max_sessions"`
	DefaultExpiration    time.Duration `json:"default_expiration"`
	RememberMeExpiration time.Duration `json:"remember_me_expiration"`
	IdleTimeout          time.Duration `json:"idle_timeout"`
	RequireSecureHeaders bool          `json:"require_secure_headers"`
	EnableGeoTracking    bool          `json:"enable_geo_tracking"`
	EnableDeviceTracking bool          `json:"enable_device_tracking"`
	AutoCleanupInterval  time.Duration `json:"auto_cleanup_interval"`
}

type SessionService

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

func NewSessionService

func NewSessionService(db *gorm.DB) *SessionService

func NewSessionServiceWithConfig

func NewSessionServiceWithConfig(db *gorm.DB, config *SessionConfig) *SessionService

func (*SessionService) CleanupExpiredSessions

func (s *SessionService) CleanupExpiredSessions() error

func (*SessionService) CreateSession

func (s *SessionService) CreateSession(userID uuid.UUID, ipAddress, userAgent string, rememberMe bool) (*Session, error)

func (*SessionService) DetectSuspiciousActivity

func (s *SessionService) DetectSuspiciousActivity(userID uuid.UUID, ipAddress string) (bool, error)

Detect suspicious activity

func (*SessionService) FlagSession

func (s *SessionService) FlagSession(sessionID uuid.UUID, flag int) error

func (*SessionService) ForceLogoutAllDevices

func (s *SessionService) ForceLogoutAllDevices(userID uuid.UUID) error

Force logout from all devices

func (*SessionService) GetDetailedUserSessions

func (s *SessionService) GetDetailedUserSessions(userID uuid.UUID) ([]Session, error)

Get detailed session information for security dashboard

func (*SessionService) GetFlaggedSessions

func (s *SessionService) GetFlaggedSessions(userID uuid.UUID) ([]Session, error)

func (*SessionService) GetSessionStats

func (s *SessionService) GetSessionStats() (*SessionStats, error)

func (*SessionService) GetUserSessions

func (s *SessionService) GetUserSessions(userID uuid.UUID) ([]Session, error)

func (*SessionService) LimitUserSessions

func (s *SessionService) LimitUserSessions(userID uuid.UUID, maxSessions int) error

func (*SessionService) RefreshSession

func (s *SessionService) RefreshSession(refreshToken string) (*Session, error)

func (*SessionService) RevokeSession

func (s *SessionService) RevokeSession(refreshToken string) error

func (*SessionService) RevokeUserSessions

func (s *SessionService) RevokeUserSessions(userID uuid.UUID) error

func (*SessionService) RunPeriodicCleanup

func (s *SessionService) RunPeriodicCleanup() error

Automatic session cleanup (should be run periodically)

func (*SessionService) UpdateSessionActivity

func (s *SessionService) UpdateSessionActivity(refreshToken, ipAddress string) error

Update session activity (called on each API request)

func (*SessionService) ValidateRefreshToken

func (s *SessionService) ValidateRefreshToken(refreshToken string) (*Session, error)

func (*SessionService) ValidateSessionWithIdleCheck

func (s *SessionService) ValidateSessionWithIdleCheck(refreshToken string) (*Session, error)

Enhanced session validation with idle timeout

type SessionStats

type SessionStats struct {
	TotalSessions  int64     `json:"total_sessions"`
	ActiveSessions int64     `json:"active_sessions"`
	LastCleanup    time.Time `json:"last_cleanup"`
}

Session management for rate limiting and security

type TemplatedEmailService

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

func NewTemplatedEmailService

func NewTemplatedEmailService(smtpService EmailService) *TemplatedEmailService

func (*TemplatedEmailService) SendEmailVerification

func (s *TemplatedEmailService) SendEmailVerification(to, token string) error

func (*TemplatedEmailService) SendMFASetupEmail

func (s *TemplatedEmailService) SendMFASetupEmail(to string, backupCodes []string) error

func (*TemplatedEmailService) SendPasswordResetEmail

func (s *TemplatedEmailService) SendPasswordResetEmail(to, token string) error

type TokenBlacklist

type TokenBlacklist struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	TokenHash     string    `json:"-" gorm:"uniqueIndex;not null;size:64"`
	UserID        uuid.UUID `json:"user_id" gorm:"type:uuid;index"`
	ExpiresAt     time.Time `json:"expires_at" gorm:"not null"`
	Reason        string    `json:"reason" gorm:"size:255"`
	BlacklistedBy uuid.UUID `json:"blacklisted_by" gorm:"type:uuid"`
}

TokenBlacklist represents a blacklisted token

func (TokenBlacklist) TableName

func (TokenBlacklist) TableName() string

type TokenBlacklistService

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

TokenBlacklistService handles token blacklisting for secure logout

func NewTokenBlacklistService

func NewTokenBlacklistService(db *gorm.DB) *TokenBlacklistService

func (*TokenBlacklistService) BlacklistToken

func (s *TokenBlacklistService) BlacklistToken(token string, expiresAt time.Time) error

BlacklistToken adds a token to the blacklist

func (*TokenBlacklistService) BlacklistTokenWithDetails

func (s *TokenBlacklistService) BlacklistTokenWithDetails(token string, userID, blacklistedBy uuid.UUID, expiresAt time.Time, reason string) error

BlacklistTokenWithDetails adds a token to the blacklist with additional details

func (*TokenBlacklistService) BlacklistUserTokens

func (s *TokenBlacklistService) BlacklistUserTokens(userID uuid.UUID) error

BlacklistUserTokens blacklists all active tokens for a user (used during logout)

func (*TokenBlacklistService) CleanupExpiredBlacklist

func (s *TokenBlacklistService) CleanupExpiredBlacklist() error

CleanupExpiredBlacklist removes expired blacklist entries

func (*TokenBlacklistService) GetBlacklistStats

func (s *TokenBlacklistService) GetBlacklistStats() (map[string]interface{}, error)

GetBlacklistStats returns statistics about the blacklist

func (*TokenBlacklistService) GetBlacklistedTokensForUser

func (s *TokenBlacklistService) GetBlacklistedTokensForUser(userID uuid.UUID) ([]TokenBlacklist, error)

GetBlacklistedTokensForUser returns blacklisted tokens for a specific user

func (*TokenBlacklistService) IsTokenBlacklisted

func (s *TokenBlacklistService) IsTokenBlacklisted(token string) (bool, error)

IsTokenBlacklisted checks if a token is in the blacklist

func (*TokenBlacklistService) RemoveFromBlacklist

func (s *TokenBlacklistService) RemoveFromBlacklist(token string) error

RemoveFromBlacklist removes a token from the blacklist (for token restoration)

func (*TokenBlacklistService) RunPeriodicCleanup

func (s *TokenBlacklistService) RunPeriodicCleanup() error

RunPeriodicCleanup should be called periodically to clean expired entries

type WebAuthnCredential

type WebAuthnCredential struct {
	ID        uuid.UUID      `json:"id" gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	UserID       uuid.UUID  `json:"user_id" gorm:"type:uuid;not null;index"`
	CredentialID string     `json:"credential_id" gorm:"not null;uniqueIndex;size:255"`
	PublicKey    []byte     `json:"public_key" gorm:"not null"`
	Name         string     `json:"name" gorm:"not null;size:255"`
	SignCount    uint32     `json:"sign_count" gorm:"default:0"`
	LastUsedAt   *time.Time `json:"last_used_at"`

	// Relationships
	User models.User `json:"user,omitempty" gorm:"foreignKey:UserID"`
}

func (*WebAuthnCredential) TableName

func (w *WebAuthnCredential) TableName() string

type WebAuthnLoginRequest

type WebAuthnLoginRequest struct {
	UserID uuid.UUID `json:"user_id"`
}

type WebAuthnLoginResponse

type WebAuthnLoginResponse struct {
	Options string `json:"options"` // JSON string of WebAuthn assertion options
}

type WebAuthnRegistrationRequest

type WebAuthnRegistrationRequest struct {
	UserID uuid.UUID `json:"user_id"`
	Name   string    `json:"name"`
}

WebAuthn methods (basic implementation)

type WebAuthnRegistrationResponse

type WebAuthnRegistrationResponse struct {
	Options string `json:"options"` // JSON string of WebAuthn creation options
}

Jump to

Keyboard shortcuts

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