Documentation
¶
Overview ¶
Package goauth provides a secure, flexible authentication library for Go.
Version: 1.0.0
GoAuth is designed for:
- Web applications (browsers)
- Mobile apps (iOS, Android)
- Desktop apps (Electron, native)
- API services (service-to-service)
- Enterprise deployments (multi-tenant, RBAC)
- Startups (quick setup, sensible defaults)
- Privacy-focused applications (minimal data collection)
Features:
- Email/password authentication with Argon2id hashing
- OAuth providers (Google, Discord, Microsoft, GitHub, etc.)
- Magic links (passwordless login)
- Two-factor authentication (TOTP with backup codes)
- API keys for service clients
- Device/session management
- Role-based access control (RBAC)
- Multi-tenant support
- Webhooks for event notifications
- GDPR compliance (data export, deletion)
- Configurable privacy settings
- Docker/Kubernetes ready
Quick Start:
auth, _ := goauth.New(
goauth.WithDatabase(db),
goauth.WithSecrets(secrets),
)
r.Mount("/auth", auth.Handler())
jobs := auth.StartBackgroundJobs()
defer jobs.Stop(ctx)
Index ¶
- Constants
- Variables
- func GetClaimsFromContext(ctx context.Context) (*crypto.Claims, bool)
- func GetClientIP(r *http.Request) string
- type APIKey
- type APIKeyStore
- type AWSSSMConfig
- type AWSSecretsConfig
- type AuditExporter
- type AuditLog
- type AuditStore
- type AuthError
- type AuthService
- func (s *AuthService) APIKeyMiddleware() func(http.Handler) http.Handler
- func (s *AuthService) CheckSuspiciousLogin(ctx context.Context, user *User, r *http.Request) bool
- func (s *AuthService) ClientTypeMiddleware() func(http.Handler) http.Handler
- func (s *AuthService) Config() Config
- func (s *AuthService) Handler() http.Handler
- func (s *AuthService) HasPermission(user *User, perm Permission) bool
- func (s *AuthService) HasRole(user *User, role Role) bool
- func (s *AuthService) LastLoginIP(ctx context.Context, userID string) (string, error)
- func (s *AuthService) Logger() *zap.Logger
- func (s *AuthService) NewGracefulShutdown() *GracefulShutdown
- func (s *AuthService) NewOAuthTokenManager() *OAuthTokenManager
- func (s *AuthService) Require2FA() func(http.Handler) http.Handler
- func (s *AuthService) RequireAuth() func(http.Handler) http.Handler
- func (s *AuthService) RequireAuthMiddleware() func(http.Handler) http.Handler
- func (s *AuthService) RequirePermission(perm Permission) func(http.Handler) http.Handler
- func (s *AuthService) RequireResource(resourceType string, checker ResourceChecker) func(http.Handler) http.Handler
- func (s *AuthService) RequireRole(roles ...Role) func(http.Handler) http.Handler
- func (s *AuthService) RequireScope(scopes ...Scope) func(http.Handler) http.Handler
- func (s *AuthService) RequireVerifiedEmail() func(http.Handler) http.Handler
- func (s *AuthService) StartBackgroundJobs(opts ...JobOption) *BackgroundJobs
- func (s *AuthService) Store() Store
- func (s *AuthService) TenantMiddleware() func(http.Handler) http.Handler
- func (s *AuthService) TriggerWebhook(ctx context.Context, event WebhookEvent, data map[string]any)
- type BackgroundJobs
- type BaseOAuthProvider
- func (p *BaseOAuthProvider) AuthURL(state, redirectURL string) string
- func (p *BaseOAuthProvider) ExchangeCode(ctx context.Context, code, redirectURL string) (*OAuthTokens, error)
- func (p *BaseOAuthProvider) GetUser(ctx context.Context, accessToken string) (*OAuthUser, error)
- func (p *BaseOAuthProvider) Name() string
- type BiometricChallenge
- type BreachNotification
- type CaptchaPolicy
- type CaptchaProvider
- type CircuitBreaker
- type CircuitState
- type ClientConfig
- type ClientType
- type ComponentHealth
- type Config
- type CustomOAuthProvider
- type DataExporter
- type Device
- type DeviceStore
- type DiscordOption
- type DiscordProvider
- type EmailChangeMailer
- type EmailChangeToken
- type EmailChangedMailer
- type GitHubOption
- type GitHubProvider
- type GoogleOption
- type GoogleProvider
- type GracefulShutdown
- type HCaptchaProvider
- type HTTPClientPool
- type HealthChecker
- type HealthStatus
- type IPBlockConfig
- type IPBlocker
- type IPIntelligence
- type IPPrivacyConfig
- type IPReputation
- type JobOption
- type MagicLinkMailer
- type MagicLinkStore
- type MagicLinkToken
- type Mailer
- type MemoryBlacklist
- type Metrics
- type MicrosoftProvider
- type OAuthConnection
- type OAuthConnectionStore
- type OAuthProvider
- type OAuthRefresher
- type OAuthRevoker
- type OAuthTokenManager
- func (m *OAuthTokenManager) GetValidToken(ctx context.Context, userID, provider string) (string, error)
- func (m *OAuthTokenManager) RevokeTokens(ctx context.Context, userID, provider string) error
- func (m *OAuthTokenManager) StoreTokens(ctx context.Context, userID, provider string, tokens *OAuthTokens) error
- type OAuthTokenStore
- type OAuthTokens
- type OAuthUser
- type Option
- func ConfigFromEnv() []Option
- func WithAPIKeys(store APIKeyStore) Option
- func WithAllowPasskeysForRoles(roles ...Role) Option
- func WithAppName(name string) Option
- func WithAppURL(url string) Option
- func WithAuditRetention(d time.Duration) Option
- func WithBackupCodeCount(count int) Option
- func WithBackupCodeDigitsOnly(enabled bool) Option
- func WithBackupCodeLength(length int) Option
- func WithBlockDisposableEmails(enabled bool) Option
- func WithCallbackPath(path string) Option
- func WithCaptcha(provider CaptchaProvider) Option
- func WithCaptchaFailOpen(enabled bool) Option
- func WithCaptchaPolicy(policy CaptchaPolicy) Option
- func WithCaptchaRequired(required bool) Option
- func WithConfig(cfg Config) Option
- func WithDatabase(db interface{}) Option
- func WithDatabases(users, audit interface{}) Option
- func WithDeviceManagement(store DeviceStore) Option
- func WithDiscord(clientID, clientSecret string) Option
- func WithDisposableEmailDomains(domains []string) Option
- func WithEmailChangeTTL(ttl time.Duration) Option
- func WithEmailDomainCheck(enabled bool) Option
- func WithEmailPassword(enabled bool) Option
- func WithEmailVerification(required bool) Option
- func WithGitHub(clientID, clientSecret string) Option
- func WithGoogle(clientID, clientSecret string) Option
- func WithHCaptcha(secret string) Option
- func WithHIBP() Option
- func WithHIBPAPIURL(url string) Option
- func WithIPBlock(cfg IPBlockConfig) Option
- func WithIPBlocker(blocker IPBlocker) Option
- func WithIPIntelligence(provider IPIntelligence) Option
- func WithIPPrivacy(cfg IPPrivacyConfig) Option
- func WithIPRetention(days int) Option
- func WithLockout(maxAttempts int, duration time.Duration) Option
- func WithLogger(logger *zap.Logger) Option
- func WithMagicLinks() Option
- func WithMailer(mailer Mailer) Option
- func WithMailgun(apiKey, domain, fromEmail, fromName string) Option
- func WithMailgunEmail(apiKey, domain, fromEmail, fromName string) Option
- func WithMaxPasskeysPerUser(limit int) Option
- func WithMemoryBlacklist() Option
- func WithMemoryRateLimiter() Option
- func WithMicrosoft(clientID, clientSecret string) Option
- func WithMongoStore(client interface{}, dbName string) Option
- func WithMultiTenant(store TenantStore) Option
- func WithMySQLStore(usersDB, auditDB interface{}) Option
- func WithNotifyOnEmailChange(enabled bool) Option
- func WithNotifyOnPasswordChange(enabled bool) Option
- func WithOAuth(provider OAuthProvider) Option
- func WithOAuthEmailLinking(allow bool, allowUnverified bool) Option
- func WithOAuthSuccessHandler(...) Option
- func WithPasswordPolicy(minLength int, requireComplexity bool, historySize int) Option
- func WithPasswordReset(enabled bool) Option
- func WithPostgresStore(usersPool, auditPool interface{}) Option
- func WithProfileStore(store ProfileStore) Option
- func WithRateLimiter(limiter RateLimiter) Option
- func WithRateLimits(cfg RateLimitConfig) Option
- func WithReCaptcha(secret string) Option
- func WithReCaptchaV3(secret string, minScore float64) Option
- func WithRedis(client *redis.Client) Option
- func WithRedisBlacklist(client *redis.Client) Option
- func WithRedisRateLimiter(client *redis.Client) Option
- func WithRequire2FAForAuth(required bool) Option
- func WithRequire2FAForEmailChange(required bool) Option
- func WithRequire2FAForMagicLink(required bool) Option
- func WithRequire2FAForOAuth(required bool) Option
- func WithRequire2FAForSDK(required bool) Option
- func WithRequireVerifiedEmailForAuth(required bool) Option
- func WithResend(apiKey, fromEmail, fromName string) Option
- func WithResendEmail(apiKey, fromEmail, fromName string) Option
- func WithRolePermissions(rp map[Role][]Permission) Option
- func WithRotateRefreshTokens(enabled bool) Option
- func WithSMTP(cfg smtpmailer.Config) Option
- func WithSMTPEmail(cfg smtp.Config) Option
- func WithSQLiteStore(usersDB, auditDB interface{}) Option
- func WithSecrets(secrets Secrets) Option
- func WithSecretsFromAWSSSM(ctx context.Context, cfg AWSSSMConfig) Option
- func WithSecretsFromAWSSecretsManager(ctx context.Context, cfg AWSSecretsConfig) Option
- func WithSecretsFromEnv() Option
- func WithSecretsFromEnvFile(path string) Option
- func WithSecretsFromEnvFileWithPrefix(path, prefix string) Option
- func WithSecretsFromFiles(jwtPath, encPath, pepperPath string) Option
- func WithSecretsFromJSONFile(path string, keys map[string]string) Option
- func WithSecretsFromRawFile(path string) Option
- func WithSecretsFromVault(cfg VaultConfig) Option
- func WithSecretsFromVaultEnv() Option
- func WithSecurityMode(mode SecurityMode) Option
- func WithSecurityMonitor(monitor SecurityMonitor) Option
- func WithSendGrid(apiKey, fromEmail, fromName string) Option
- func WithSendGridEmail(apiKey, fromEmail, fromName string) Option
- func WithStore(store Store) Option
- func WithTOTP(enabled bool) Option
- func WithTOTPAccountName(name string) Option
- func WithTOTPDigits(digits int) Option
- func WithTOTPQRCode(enabled bool) Option
- func WithTOTPQRCodeSize(size int) Option
- func WithTOTPUseUsername(enabled bool) Option
- func WithTokenBlacklist(bl TokenBlacklist) Option
- func WithTokenTTL(access, refresh time.Duration) Option
- func WithTrustProxyHeaders(enabled bool) Option
- func WithTrustedProxies(proxies []string) Option
- func WithTurnstile(secret string) Option
- func WithTwitch(clientID, clientSecret string) Option
- func WithUnverifiedAccountTTL(ttl time.Duration) Option
- func WithUserAgentHashInLogs(enabled bool) Option
- func WithUsername(enabled bool) Option
- func WithUsernameAllowNumericOnly(allowed bool) Option
- func WithUsernamePattern(pattern string) Option
- func WithUsernamePolicy(minLength, maxLength int) Option
- func WithUsernameRequired(required bool) Option
- func WithUsernameReserved(reserved []string) Option
- func WithWebAuthn(config WebAuthnConfig) Option
- func WithWebAuthnStore(store WebAuthnStore) Option
- func WithWebhooks(store WebhookStore) Option
- func WithoutIPStorage() Option
- type PasswordChangeMailer
- type PasswordHistory
- type PasswordResetToken
- type Permission
- type Profile
- type ProfileProvider
- type ProfileStore
- type RateLimitConfig
- type RateLimiter
- type ReCaptchaConfig
- type ReCaptchaProvider
- type RedisBlacklist
- type RequestDeduplicator
- type RequestTracker
- type ResourceChecker
- type Role
- type SDKToken
- type Scope
- type Secrets
- func MustSecretsFromEnv() Secrets
- func SecretsFromAWSSSM(ctx context.Context, cfg AWSSSMConfig) (Secrets, error)
- func SecretsFromAWSSecretsManager(ctx context.Context, cfg AWSSecretsConfig) (Secrets, error)
- func SecretsFromEnv() (Secrets, error)
- func SecretsFromEnvFile(path string) (Secrets, error)
- func SecretsFromEnvFileWithPrefix(path, prefix string) (Secrets, error)
- func SecretsFromEnvWithPrefix(prefix string) (Secrets, error)
- func SecretsFromFiles(jwtPath, encPath, pepperPath string) (Secrets, error)
- func SecretsFromJSON(payload []byte, keys map[string]string) (Secrets, error)
- func SecretsFromJSONFile(path string, keys map[string]string) (Secrets, error)
- func SecretsFromRawFile(path string) (Secrets, error)
- func SecretsFromVault(ctx context.Context, cfg VaultConfig) (Secrets, error)
- func SecretsFromVaultEnv(ctx context.Context) (Secrets, error)
- type SecurityAlert
- type SecurityAlertMailer
- type SecurityMode
- type SecurityMonitor
- type Session
- type SessionStore
- type SlidingWindowRateLimiter
- type Store
- type StoreCleaner
- type Tenant
- type TenantSettings
- type TenantStore
- type TokenBlacklist
- type TokenStore
- type TurnstileProvider
- type TwitchProvider
- type User
- type UserDeleter
- type UserStore
- type VaultConfig
- type VerificationToken
- type WebAuthnChallenge
- type WebAuthnConfig
- type WebAuthnCredential
- type WebAuthnNameStore
- type WebAuthnStore
- type WebAuthnUsageStore
- type Webhook
- type WebhookEvent
- type WebhookPayload
- type WebhookStore
- type WelcomeMailer
Constants ¶
const ( CodeInvalidCredentials = "INVALID_CREDENTIALS" CodeAccountLocked = "ACCOUNT_LOCKED" CodeAccountNotVerified = "ACCOUNT_NOT_VERIFIED" CodeAccountSuspended = "ACCOUNT_SUSPENDED" CodeEmailExists = "EMAIL_EXISTS" CodeUsernameExists = "USERNAME_EXISTS" CodeInvalidEmail = "INVALID_EMAIL" CodeDisposableEmail = "DISPOSABLE_EMAIL" CodeInvalidUsername = "INVALID_USERNAME" CodeWeakPassword = "WEAK_PASSWORD" CodePasswordBreached = "PASSWORD_BREACHED" CodePasswordReused = "PASSWORD_REUSED" CodeInvalidToken = "INVALID_TOKEN" CodeTokenExpired = "TOKEN_EXPIRED" CodeTooManyAttempts = "TOO_MANY_ATTEMPTS" CodeVerificationRequired = "VERIFICATION_REQUIRED" Code2FARequired = "2FA_REQUIRED" CodeInvalid2FACode = "INVALID_2FA_CODE" Code2FAAlreadyEnabled = "2FA_ALREADY_ENABLED" Code2FANotEnabled = "2FA_NOT_ENABLED" CodeInvalidCaptcha = "INVALID_CAPTCHA" CodeRateLimited = "RATE_LIMITED" CodeIPBlocked = "IP_BLOCKED" CodeInternalError = "INTERNAL_ERROR" CodeBadRequest = "BAD_REQUEST" CodePasskeyLimit = "PASSKEY_LIMIT_REACHED" CodePasskeyNotAllowed = "PASSKEY_NOT_ALLOWED" CodeInvalidPasskey = "INVALID_PASSKEY" CodeMagicLinkExpired = "MAGIC_LINK_EXPIRED" CodeMagicLinkUsed = "MAGIC_LINK_USED" )
Error codes for API responses.
const ( StatusActive = "active" StatusPendingVerification = "pending_verification" StatusLocked = "locked" StatusSuspended = "suspended" StatusDeleted = "deleted" )
Account statuses
const ( EventRegister = "register" EventLoginSuccess = "login_success" EventLoginFailed = "login_failed" EventLogout = "logout" EventPasswordChanged = "password_changed" EventPasswordResetRequest = "password_reset_request" EventPasswordResetComplete = "password_reset_complete" EventEmailVerified = "email_verified" EventEmailChanged = "email_changed" Event2FAEnabled = "2fa_enabled" Event2FADisabled = "2fa_disabled" EventBackupCodesRegenerated = "backup_codes_regenerated" EventAccountLocked = "account_locked" EventAccountUnlocked = "account_unlocked" EventAPIKeyCreated = "api_key_created" EventAPIKeyRevoked = "api_key_revoked" EventDeviceRevoked = "device_revoked" EventSuspiciousActivity = "suspicious_activity" EventPasskeyRenamed = "webauthn_renamed" )
Audit event types
const ( // UserContextKey is the context key for the authenticated user. UserContextKey contextKey = "goauth_user" // ClaimsContextKey is the context key for JWT claims. ClaimsContextKey contextKey = "goauth_claims" )
Variables ¶
var ( ErrInvalidJWTSecret = errors.New("goauth: JWT secret must be exactly 32 bytes") ErrInvalidMEK = errors.New("goauth: MEK (Master Encryption Key) must be exactly 32 bytes") ErrInvalidPepper = errors.New("goauth: pepper must be exactly 32 bytes") ErrInvalidSecretLength = errors.New("goauth: secrets must be exactly 32 bytes") ErrStoreNotConfigured = errors.New("goauth: store is required but not configured") ErrMailerNotConfigured = errors.New("goauth: mailer is required for this operation but not configured") )
Configuration errors.
var ( ErrInvalidCredentials = errors.New("invalid email or password") ErrAccountLocked = errors.New("account is locked due to too many failed attempts") ErrAccountNotVerified = errors.New("email not verified") ErrAccountSuspended = errors.New("account is suspended") ErrEmailAlreadyExists = errors.New("email already registered") ErrUsernameAlreadyExists = errors.New("username already in use") ErrInvalidEmail = errors.New("invalid email address") ErrDisposableEmail = errors.New("disposable email addresses are not allowed") ErrInvalidUsername = errors.New("invalid username") ErrWeakPassword = errors.New("password does not meet security requirements") ErrPasswordBreached = errors.New("password found in data breach, please choose another") ErrPasswordReused = errors.New("cannot reuse recent passwords") ErrInvalidToken = errors.New("invalid or expired token") ErrTokenExpired = errors.New("token has expired") ErrTooManyAttempts = errors.New("too many attempts, please try again later") ErrVerificationRequired = errors.New("email verification required") Err2FARequired = errors.New("two-factor authentication required") ErrInvalid2FACode = errors.New("invalid verification code") Err2FAAlreadyEnabled = errors.New("two-factor authentication is already enabled") Err2FANotEnabled = errors.New("two-factor authentication is not enabled") ErrInvalidCaptcha = errors.New("captcha verification failed") ErrRateLimited = errors.New("rate limit exceeded, please try again later") ErrProfileNotFound = errors.New("profile not found") ErrIPBlocked = errors.New("ip temporarily blocked") ErrPasskeyLimitReached = errors.New("maximum number of passkeys reached") ErrPasskeyNotAllowed = errors.New("passkey registration not allowed for this role") ErrInvalidPasskey = errors.New("invalid passkey") ErrMagicLinkExpired = errors.New("magic link has expired") ErrMagicLinkUsed = errors.New("magic link has already been used") )
Authentication errors - these are safe to show to users.
var ( ErrInternal = errors.New("internal server error") ErrDatabaseError = errors.New("database error") ErrEncryptionError = errors.New("encryption error") ErrEmailSendError = errors.New("failed to send email") ErrCaptchaService = errors.New("captcha service error") )
Internal errors - these should be logged but not shown to users.
var ( ErrOAuthTokenExpired = newAuthError("OAUTH_TOKEN_EXPIRED", "oauth token expired", nil) ErrOAuthProviderNotFound = newAuthError("OAUTH_PROVIDER_NOT_FOUND", "oauth provider not found", nil) ErrOAuthRefreshNotSupported = newAuthError("OAUTH_REFRESH_NOT_SUPPORTED", "oauth refresh not supported", nil) )
var DefaultRolePermissions = map[Role][]Permission{ RoleUser: {PermissionRead}, RoleModerator: {PermissionRead, PermissionWrite}, RoleAdmin: {PermissionRead, PermissionWrite, PermissionDelete, PermissionAdmin}, RoleService: {PermissionRead, PermissionWrite}, }
RolePermissions maps roles to their permissions.
var ErrStoreRequired = errors.New("WithDatabase is deprecated; use stores/postgres.WithDatabase or WithStore")
ErrStoreRequired is returned when using deprecated WithDatabase without a store.
Functions ¶
func GetClaimsFromContext ¶
GetClaimsFromContext retrieves the JWT claims from the request context.
func GetClientIP ¶
GetClientIP extracts the client IP from the request without trust rules.
Types ¶
type APIKey ¶
type APIKey struct {
ID string
UserID string
Name string
KeyPrefix string // First 8 chars for identification
KeyHash []byte // SHA-256 hash of full key
Scopes []string
ExpiresAt *time.Time
LastUsed time.Time
CreatedAt time.Time
RateLimit int // Requests per minute, 0 = default
}
APIKey represents a long-lived API key for service/integration use.
type APIKeyStore ¶
type APIKeyStore interface {
CreateAPIKey(ctx context.Context, key APIKey) error
GetAPIKeyByHash(ctx context.Context, keyHash []byte) (*APIKey, error)
GetUserAPIKeys(ctx context.Context, userID string) ([]APIKey, error)
UpdateAPIKeyLastUsed(ctx context.Context, keyID string) error
RevokeAPIKey(ctx context.Context, keyID string) error
}
APIKeyStore handles API key management.
type AWSSSMConfig ¶
type AWSSSMConfig struct {
JWTParameter string
EncryptionParameter string
PepperParameter string
Region string
}
AWSSSMConfig holds AWS SSM Parameter Store configuration.
type AWSSecretsConfig ¶
type AWSSecretsConfig struct {
// SecretName is the name of the secret in AWS
SecretName string
// Region is the AWS region
Region string
// Keys maps secret keys (optional)
Keys map[string]string
}
AWSSecretsConfig holds AWS Secrets Manager configuration.
type AuditExporter ¶
type AuditExporter interface {
ExportUserAuditLogs(ctx context.Context, userID string, format string) ([]byte, error)
ExportTenantAuditLogs(ctx context.Context, tenantID string, from, to time.Time, format string) ([]byte, error)
}
AuditExporter allows exporting audit logs for compliance.
type AuditLog ¶
type AuditLog struct {
ID string
UserID string
TenantID string
EventType string
IPEncrypted []byte
IPNonce []byte
UserAgentHash []byte
Metadata map[string]any
MetadataEnc []byte
MetadataNonce []byte
ExpiresAt time.Time
CreatedAt time.Time
}
AuditLog records security events.
type AuditStore ¶
type AuditStore interface {
InsertAuditLog(ctx context.Context, log AuditLog) error
GetUserAuditLogs(ctx context.Context, userID string, limit int) ([]AuditLog, error)
}
AuditStore handles audit logging.
type AuthError ¶
type AuthError struct {
// Code is a machine-readable error code
Code string `json:"code"`
// Message is a human-readable error message safe for users
Message string `json:"message"`
// Internal is the underlying error (not included in JSON)
Internal error `json:"-"`
}
AuthError wraps an error with additional context for API responses.
type AuthService ¶
type AuthService struct {
// contains filtered or unexported fields
}
AuthService is the main entry point for the authentication library.
func (*AuthService) APIKeyMiddleware ¶
func (s *AuthService) APIKeyMiddleware() func(http.Handler) http.Handler
APIKeyMiddleware authenticates requests using API keys.
func (*AuthService) CheckSuspiciousLogin ¶
CheckSuspiciousLogin checks for suspicious login patterns.
func (*AuthService) ClientTypeMiddleware ¶
func (s *AuthService) ClientTypeMiddleware() func(http.Handler) http.Handler
ClientTypeMiddleware adds client type to context.
func (*AuthService) Config ¶
func (s *AuthService) Config() Config
Config returns the configuration.
func (*AuthService) Handler ¶
func (s *AuthService) Handler() http.Handler
Handler returns the HTTP handler with all routes.
func (*AuthService) HasPermission ¶
func (s *AuthService) HasPermission(user *User, perm Permission) bool
HasPermission checks if a user has a specific permission.
func (*AuthService) HasRole ¶
func (s *AuthService) HasRole(user *User, role Role) bool
HasRole checks if a user has a specific role.
func (*AuthService) LastLoginIP ¶
LastLoginIP returns the last stored login IP for a user when IP storage is enabled.
func (*AuthService) NewGracefulShutdown ¶
func (s *AuthService) NewGracefulShutdown() *GracefulShutdown
NewGracefulShutdown creates a new graceful shutdown handler.
func (*AuthService) NewOAuthTokenManager ¶
func (s *AuthService) NewOAuthTokenManager() *OAuthTokenManager
NewOAuthTokenManager creates a new OAuth token manager.
func (*AuthService) Require2FA ¶
func (s *AuthService) Require2FA() func(http.Handler) http.Handler
Require2FA enforces a completed second factor on protected routes.
func (*AuthService) RequireAuth ¶
func (s *AuthService) RequireAuth() func(http.Handler) http.Handler
RequireAuth returns authentication middleware.
func (*AuthService) RequireAuthMiddleware ¶
func (s *AuthService) RequireAuthMiddleware() func(http.Handler) http.Handler
RequireAuthMiddleware returns middleware that validates JWT tokens. Use this to protect your own routes with GoAuth authentication.
func (*AuthService) RequirePermission ¶
func (s *AuthService) RequirePermission(perm Permission) func(http.Handler) http.Handler
RequirePermission creates middleware that requires a specific permission.
func (*AuthService) RequireResource ¶
func (s *AuthService) RequireResource(resourceType string, checker ResourceChecker) func(http.Handler) http.Handler
RequireResource creates middleware that checks access to a specific resource.
func (*AuthService) RequireRole ¶
RequireRole creates middleware that requires the user to have a specific role.
func (*AuthService) RequireScope ¶
RequireScope creates middleware that requires specific OAuth scopes.
func (*AuthService) RequireVerifiedEmail ¶
func (s *AuthService) RequireVerifiedEmail() func(http.Handler) http.Handler
RequireVerifiedEmail enforces email verification for protected routes.
func (*AuthService) StartBackgroundJobs ¶
func (s *AuthService) StartBackgroundJobs(opts ...JobOption) *BackgroundJobs
StartBackgroundJobs starts all background workers. Call this after creating the AuthService.
func (*AuthService) TenantMiddleware ¶
func (s *AuthService) TenantMiddleware() func(http.Handler) http.Handler
TenantMiddleware extracts tenant from request and adds to context.
func (*AuthService) TriggerWebhook ¶
func (s *AuthService) TriggerWebhook(ctx context.Context, event WebhookEvent, data map[string]any)
TriggerWebhook sends an event to configured webhooks.
type BackgroundJobs ¶
type BackgroundJobs struct {
// contains filtered or unexported fields
}
BackgroundJobs manages all background tasks for the auth service.
func (*BackgroundJobs) QueueEmail ¶
func (j *BackgroundJobs) QueueEmail(jobType, to string, data map[string]string) bool
QueueEmail queues an email for async sending.
type BaseOAuthProvider ¶
type BaseOAuthProvider struct {
// contains filtered or unexported fields
}
BaseOAuthProvider provides common OAuth functionality.
func (*BaseOAuthProvider) AuthURL ¶
func (p *BaseOAuthProvider) AuthURL(state, redirectURL string) string
func (*BaseOAuthProvider) ExchangeCode ¶
func (p *BaseOAuthProvider) ExchangeCode(ctx context.Context, code, redirectURL string) (*OAuthTokens, error)
func (*BaseOAuthProvider) Name ¶
func (p *BaseOAuthProvider) Name() string
type BiometricChallenge ¶
type BiometricChallenge struct {
Challenge string `json:"challenge"`
ExpiresAt time.Time `json:"expires_at"`
}
BiometricChallenge for mobile biometric authentication.
type BreachNotification ¶
type BreachNotification struct {
BreachName string
BreachDate time.Time
DataTypes []string // "password", "email", "address", etc.
Description string
SourceURL string
}
BreachNotification handles data breach notifications.
type CaptchaPolicy ¶
type CaptchaPolicy struct {
Required bool
OnRegister bool
OnLogin bool
OnPasswordReset bool
OnMagicLink bool
}
CaptchaPolicy controls where CAPTCHA is enforced.
type CaptchaProvider ¶
type CaptchaProvider interface {
// Name returns the provider name
Name() string
// Verify checks if the CAPTCHA token is valid
Verify(ctx context.Context, token, ip string) (bool, error)
}
CaptchaProvider defines the interface for CAPTCHA verification.
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker implements the circuit breaker pattern for external services.
func NewCircuitBreaker ¶
func NewCircuitBreaker(name string, maxFailures int, resetTimeout time.Duration) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker.
func (*CircuitBreaker) Allow ¶
func (cb *CircuitBreaker) Allow() bool
Allow checks if a request should be allowed.
func (*CircuitBreaker) Failure ¶
func (cb *CircuitBreaker) Failure()
Failure records a failed request.
func (*CircuitBreaker) State ¶
func (cb *CircuitBreaker) State() CircuitState
State returns the current state of the circuit breaker.
func (*CircuitBreaker) Success ¶
func (cb *CircuitBreaker) Success()
Success records a successful request.
type CircuitState ¶
type CircuitState int
CircuitState represents the state of the circuit breaker.
const ( CircuitClosed CircuitState = iota CircuitOpen CircuitHalfOpen )
type ClientConfig ¶
type ClientConfig struct {
AccessTokenTTL time.Duration
RefreshTokenTTL time.Duration
AllowRememberMe bool
MaxDevices int
}
ClientConfig holds configuration for specific client types.
type ClientType ¶
type ClientType string
ClientType identifies the type of client making the request.
const ( ClientTypeWeb ClientType = "web" ClientTypeMobile ClientType = "mobile" ClientTypeDesktop ClientType = "desktop" ClientTypeAPI ClientType = "api" ClientTypeSDK ClientType = "sdk" )
func GetClientType ¶
func GetClientType(r *http.Request) ClientType
GetClientType detects the client type from the request.
func GetClientTypeFromContext ¶
func GetClientTypeFromContext(ctx context.Context) ClientType
GetClientTypeFromContext retrieves client type from context.
type ComponentHealth ¶
type ComponentHealth struct {
Status string `json:"status"`
Latency string `json:"latency,omitempty"`
Error string `json:"error,omitempty"`
}
ComponentHealth represents the health of a component.
type Config ¶
type Config struct {
// ==================== APP INFO ====================
AppName string
AppBaseURL string
CallbackPath string
// ==================== FEATURE TOGGLES ====================
EmailPasswordEnabled bool
EmailVerificationRequired bool
TOTPEnabled bool
PasswordResetEnabled bool
MagicLinksEnabled bool
APIKeysEnabled bool
DeviceManagementEnabled bool
// ==================== USERNAME ====================
UsernameEnabled bool
UsernameRequired bool
MinUsernameLength int
MaxUsernameLength int
UsernamePattern string
UsernameReserved []string
UsernameAllowNumericOnly bool
// ==================== TOKEN SETTINGS ====================
AccessTokenTTL time.Duration
RefreshTokenTTL time.Duration
VerificationCodeTTL time.Duration
PasswordResetTTL time.Duration
MagicLinkTTL time.Duration
EmailChangeTTL time.Duration
// ==================== 2FA/TOTP ====================
TOTPDigits int
TOTPAccountName string
TOTPUseUsername bool
TOTPQRCodeEnabled bool
TOTPQRCodeSize int
BackupCodeLength int
BackupCodeDigitsOnly bool
BackupCodeCount int
// ==================== SECURITY ====================
MaxLoginAttempts int
LockoutDuration time.Duration
MaxVerificationAttempts int
PasswordHistorySize int
MinPasswordLength int
RequirePasswordComplexity bool
RotateRefreshTokens bool
BlockDisposableEmails bool
DisposableEmailDomains []string
RequireVerifiedEmailForAuth bool
Require2FAForAuth bool
Require2FAForOAuth bool
Require2FAForMagicLink bool
Require2FAForSDK bool
Require2FAForEmailChange bool
AllowOAuthEmailLinking bool
AllowUnverifiedOAuthEmailLinking bool
TrustProxyHeaders bool
TrustedProxies []string
RateLimits RateLimitConfig
IPBlock IPBlockConfig
// ==================== PRIVACY ====================
IPPrivacy IPPrivacyConfig
AuditLogRetention time.Duration
UnverifiedAccountTTL time.Duration
StoreUserAgentHash bool
NotifyOnPasswordChange bool
NotifyOnEmailChange bool
// ==================== EXTERNAL SERVICES ====================
TurnstileEnabled bool
TurnstileSecret string
TurnstileVerifyURL string
HIBPEnabled bool
HIBPAPIURL string
EmailDomainCheck bool
CaptchaFailOpen bool
CaptchaRequired bool
CaptchaOnRegister bool
CaptchaOnLogin bool
CaptchaOnPasswordReset bool
CaptchaOnMagicLink bool
// ==================== WEBAUTHN ====================
WebAuthn WebAuthnConfig
WebAuthnEnabled bool
AllowRememberMe bool
MaxDevices int // 0 = unlimited
// ==================== DEBUG / HOOKS ====================
OAuthSuccessHandler func(w http.ResponseWriter, r *http.Request, provider string, user *OAuthUser, tokens *OAuthTokens) bool
// ==================== CLIENT CONFIGS ====================
WebClientConfig ClientConfig
MobileClientConfig ClientConfig
APIClientConfig ClientConfig
}
Config holds the authentication service configuration.
type CustomOAuthProvider ¶
type CustomOAuthProvider struct {
BaseOAuthProvider
}
CustomOAuthProvider allows creating custom OAuth providers.
func NewCustomProvider ¶
func NewCustomProvider(name, clientID, clientSecret, authURL, tokenURL, userURL string, scopes []string, userParser func([]byte) (*OAuthUser, error)) *CustomOAuthProvider
NewCustomProvider creates a custom OAuth provider.
type DataExporter ¶
DataExporter handles data export.
type Device ¶
type Device struct {
ID string
UserID string
Name string // "Chrome on Windows", "iPhone 15"
DeviceType string // "browser", "mobile", "desktop", "api"
LastIP string // Last seen IP (encrypted or hashed based on config)
LastIPNonce []byte
LastActive time.Time
CreatedAt time.Time
RefreshToken string // JTI of the associated refresh token
TrustLevel string // "untrusted", "trusted", "remembered"
Fingerprint string // Device fingerprint hash
}
Device represents a user's authenticated device/session.
type DeviceStore ¶
type DeviceStore interface {
// CreateDevice creates a new device entry.
CreateDevice(ctx context.Context, device Device) error
// GetUserDevices returns all devices for a user.
GetUserDevices(ctx context.Context, userID string) ([]Device, error)
// GetDevice returns a specific device.
GetDevice(ctx context.Context, deviceID string) (*Device, error)
// UpdateDeviceActivity updates last active time and IP.
UpdateDeviceActivity(ctx context.Context, deviceID string, ip []byte, ipNonce []byte) error
// RevokeDevice removes a device and its associated tokens.
RevokeDevice(ctx context.Context, deviceID string) error
// RevokeAllDevices removes all devices for a user except current.
RevokeAllDevices(ctx context.Context, userID, exceptDeviceID string) error
// TrustDevice marks a device as trusted (skip 2FA).
TrustDevice(ctx context.Context, deviceID string, trustLevel string) error
}
DeviceStore handles device/session management.
type DiscordOption ¶ added in v1.1.5
type DiscordOption func(*DiscordProvider)
DiscordOption configures a DiscordProvider.
func WithDiscordScopes ¶ added in v1.1.5
func WithDiscordScopes(scopes ...string) DiscordOption
WithDiscordScopes sets custom scopes for Discord OAuth. Default scopes are "identify" and "email".
type DiscordProvider ¶
type DiscordProvider struct {
BaseOAuthProvider
}
DiscordProvider implements OAuth for Discord.
func NewDiscordProvider ¶
func NewDiscordProvider(clientID, clientSecret string, opts ...DiscordOption) *DiscordProvider
NewDiscordProvider creates a Discord OAuth provider.
func (*DiscordProvider) ExchangeCode ¶ added in v1.1.5
func (p *DiscordProvider) ExchangeCode(ctx context.Context, code, redirectURL string) (*OAuthTokens, error)
ExchangeCode exchanges an authorization code for tokens using HTTP Basic Auth. Discord requires client credentials via HTTP Basic Auth, not form-encoded.
func (*DiscordProvider) RefreshToken ¶
func (p *DiscordProvider) RefreshToken(ctx context.Context, refreshToken string) (*OAuthTokens, error)
RefreshToken refreshes a Discord access token.
func (*DiscordProvider) RevokeToken ¶
func (p *DiscordProvider) RevokeToken(ctx context.Context, token string) error
RevokeToken revokes a Discord access token.
type EmailChangeMailer ¶
EmailChangeMailer sends email change confirmation links.
type EmailChangeToken ¶
type EmailChangeToken struct {
ID string
UserID string
TokenHash []byte
NewEmailHash []byte
NewEmailEncrypted []byte
NewEmailNonce []byte
ExpiresAt time.Time
Used bool
}
EmailChangeToken for email change confirmation.
type EmailChangedMailer ¶
type EmailChangedMailer interface {
SendEmailChanged(ctx context.Context, to, newEmail string) error
}
EmailChangedMailer sends notifications when email changes are completed.
type GitHubOption ¶ added in v1.1.5
type GitHubOption func(*GitHubProvider)
GitHubOption configures a GitHubProvider.
func WithGitHubScopes ¶ added in v1.1.5
func WithGitHubScopes(scopes ...string) GitHubOption
WithGitHubScopes sets custom scopes for GitHub OAuth. Default scope is "user:email".
type GitHubProvider ¶
type GitHubProvider struct {
BaseOAuthProvider
}
GitHubProvider implements OAuth for GitHub.
func NewGitHubProvider ¶
func NewGitHubProvider(clientID, clientSecret string, opts ...GitHubOption) *GitHubProvider
NewGitHubProvider creates a GitHub OAuth provider.
func (*GitHubProvider) RevokeToken ¶
func (p *GitHubProvider) RevokeToken(ctx context.Context, token string) error
RevokeToken deletes a GitHub OAuth app authorization.
type GoogleOption ¶ added in v1.1.5
type GoogleOption func(*GoogleProvider)
GoogleOption configures a GoogleProvider.
func WithGoogleScopes ¶ added in v1.1.5
func WithGoogleScopes(scopes ...string) GoogleOption
WithGoogleScopes sets custom scopes for Google OAuth. Default scopes are "email" and "profile".
type GoogleProvider ¶
type GoogleProvider struct {
BaseOAuthProvider
}
GoogleProvider implements OAuth for Google.
func NewGoogleProvider ¶
func NewGoogleProvider(clientID, clientSecret string, opts ...GoogleOption) *GoogleProvider
NewGoogleProvider creates a Google OAuth provider.
func (*GoogleProvider) RefreshToken ¶
func (p *GoogleProvider) RefreshToken(ctx context.Context, refreshToken string) (*OAuthTokens, error)
RefreshToken refreshes a Google access token.
func (*GoogleProvider) RevokeToken ¶
func (p *GoogleProvider) RevokeToken(ctx context.Context, token string) error
RevokeToken revokes a Google access token.
type GracefulShutdown ¶
type GracefulShutdown struct {
// contains filtered or unexported fields
}
GracefulShutdown handles graceful shutdown of the auth service.
func (*GracefulShutdown) OnShutdown ¶
func (g *GracefulShutdown) OnShutdown(fn func(context.Context))
OnShutdown registers a callback to be called during shutdown.
type HCaptchaProvider ¶
type HCaptchaProvider struct {
// contains filtered or unexported fields
}
HCaptchaProvider implements CaptchaProvider for hCaptcha.
func NewHCaptcha ¶
func NewHCaptcha(secret string) *HCaptchaProvider
NewHCaptcha creates an hCaptcha provider. Get your keys from: https://dashboard.hcaptcha.com
func (*HCaptchaProvider) Name ¶
func (h *HCaptchaProvider) Name() string
type HTTPClientPool ¶
type HTTPClientPool struct {
// contains filtered or unexported fields
}
HTTPClientPool provides a pool of HTTP clients for external services.
func NewHTTPClientPool ¶
func NewHTTPClientPool() *HTTPClientPool
NewHTTPClientPool creates a new HTTP client pool.
type HealthChecker ¶
HealthChecker is implemented by stores that support health checks.
type HealthStatus ¶
type HealthStatus struct {
Status string `json:"status"`
Version string `json:"version"`
Uptime string `json:"uptime"`
Checks map[string]ComponentHealth `json:"checks,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
HealthStatus represents the health of the service.
type IPBlockConfig ¶
type IPBlockConfig struct {
Enabled bool
FailureThreshold int
FailureWindow time.Duration
BlockDuration time.Duration
}
IPBlockConfig defines IP block/penalty settings.
type IPBlocker ¶
type IPBlocker interface {
IsBlocked(ctx context.Context, ip string) (bool, time.Time, error)
Block(ctx context.Context, ip string, duration time.Duration, reason string) error
Unblock(ctx context.Context, ip string) error
}
IPBlocker blocks abusive IPs.
type IPIntelligence ¶
type IPIntelligence interface {
// Check returns reputation info for an IP.
Check(ctx context.Context, ip string) (*IPReputation, error)
}
IPIntelligence provides IP reputation data.
type IPPrivacyConfig ¶
IPPrivacyConfig controls how IP addresses are stored.
type IPReputation ¶
type IPReputation struct {
IP string
IsProxy bool
IsVPN bool
IsTor bool
IsDatacenter bool
IsBotnet bool
ThreatScore float64 // 0-1, higher = more risky
Country string
City string
ISP string
}
IPReputation holds IP reputation data.
type JobOption ¶
type JobOption func(*jobConfig)
JobOption configures background jobs.
func WithCleanupInterval ¶
WithCleanupInterval sets how often cleanup runs.
func WithEmailQueueSize ¶
WithEmailQueueSize sets the email queue buffer size.
func WithEmailWorkers ¶
WithEmailWorkers sets the number of email worker goroutines.
type MagicLinkMailer ¶
MagicLinkMailer sends magic link emails.
type MagicLinkStore ¶
type MagicLinkStore interface {
CreateMagicLinkToken(ctx context.Context, token MagicLinkToken) error
GetMagicLinkToken(ctx context.Context, tokenHash []byte) (*MagicLinkToken, error)
MarkMagicLinkUsed(ctx context.Context, tokenID string, ipUsed, ipNonce []byte) error
}
MagicLinkStore handles magic link tokens.
type MagicLinkToken ¶
type MagicLinkToken struct {
ID string
UserID string
TokenHash []byte
ExpiresAt time.Time
Used bool
IPCreated []byte
IPNonce []byte
}
MagicLinkToken represents a passwordless login token.
type Mailer ¶
type Mailer interface {
SendVerification(ctx context.Context, to, code, link string) error
SendPasswordReset(ctx context.Context, to, link string) error
}
Mailer sends emails.
type MemoryBlacklist ¶
type MemoryBlacklist struct {
// contains filtered or unexported fields
}
MemoryBlacklist uses in-memory storage for single-instance deployments.
func NewMemoryBlacklist ¶
func NewMemoryBlacklist() *MemoryBlacklist
NewMemoryBlacklist creates an in-memory token blacklist.
func (*MemoryBlacklist) Cleanup ¶
func (b *MemoryBlacklist) Cleanup()
func (*MemoryBlacklist) IsBlacklisted ¶
type Metrics ¶
type Metrics struct {
// contains filtered or unexported fields
}
Metrics provides Prometheus-compatible metrics.
func (*Metrics) IncrementLoginFailed ¶
func (m *Metrics) IncrementLoginFailed()
IncrementLoginFailed increments the login failed counter.
func (*Metrics) IncrementLoginSuccess ¶
func (m *Metrics) IncrementLoginSuccess()
IncrementLoginSuccess increments the login success counter.
func (*Metrics) IncrementRateLimitHit ¶
func (m *Metrics) IncrementRateLimitHit()
IncrementRateLimitHit increments the rate limit hit counter.
func (*Metrics) IncrementRegisterSuccess ¶
func (m *Metrics) IncrementRegisterSuccess()
IncrementRegisterSuccess increments the register success counter.
type MicrosoftProvider ¶
type MicrosoftProvider struct {
BaseOAuthProvider
}
MicrosoftProvider implements OAuth for Microsoft.
func NewMicrosoftProvider ¶
func NewMicrosoftProvider(clientID, clientSecret string) *MicrosoftProvider
NewMicrosoftProvider creates a Microsoft OAuth provider.
func (*MicrosoftProvider) RefreshToken ¶
func (p *MicrosoftProvider) RefreshToken(ctx context.Context, refreshToken string) (*OAuthTokens, error)
RefreshToken refreshes a Microsoft access token.
type OAuthConnection ¶
type OAuthConnection struct {
ID string
UserID string
Provider string
ProviderID string
AccessToken []byte // Encrypted
RefreshToken []byte // Encrypted
ExpiresAt *time.Time
CreatedAt time.Time
}
OAuthConnection links a user to an OAuth provider.
type OAuthConnectionStore ¶
type OAuthConnectionStore interface {
GetUserByOAuthProvider(ctx context.Context, provider, providerUserID string) (*User, error)
LinkOAuthConnection(ctx context.Context, userID, provider, providerUserID string) error
UnlinkOAuthConnection(ctx context.Context, userID, provider string) error
GetUserOAuthConnections(ctx context.Context, userID string) ([]OAuthConnection, error)
}
OAuthConnectionStore manages OAuth provider links.
type OAuthProvider ¶
type OAuthProvider interface {
Name() string
AuthURL(state, redirectURL string) string
ExchangeCode(ctx context.Context, code, redirectURL string) (*OAuthTokens, error)
GetUser(ctx context.Context, accessToken string) (*OAuthUser, error)
}
OAuthProvider interface for OAuth authentication.
type OAuthRefresher ¶
type OAuthRefresher interface {
RefreshToken(ctx context.Context, refreshToken string) (*OAuthTokens, error)
}
OAuthRefresher is implemented by providers that support token refresh.
type OAuthRevoker ¶
OAuthRevoker is implemented by providers that support token revocation.
type OAuthTokenManager ¶
type OAuthTokenManager struct {
// contains filtered or unexported fields
}
OAuthTokenManager handles OAuth token storage, refresh, and revocation.
func (*OAuthTokenManager) GetValidToken ¶
func (m *OAuthTokenManager) GetValidToken(ctx context.Context, userID, provider string) (string, error)
GetValidToken returns a valid access token, refreshing if needed.
func (*OAuthTokenManager) RevokeTokens ¶
func (m *OAuthTokenManager) RevokeTokens(ctx context.Context, userID, provider string) error
RevokeTokens revokes OAuth tokens for a user (logout from provider).
func (*OAuthTokenManager) StoreTokens ¶
func (m *OAuthTokenManager) StoreTokens(ctx context.Context, userID, provider string, tokens *OAuthTokens) error
StoreTokens stores OAuth tokens for a user.
type OAuthTokenStore ¶
type OAuthTokenStore interface {
StoreOAuthTokens(ctx context.Context, userID, provider string, accessEnc, accessNonce, refreshEnc, refreshNonce []byte, expiresAt time.Time) error
GetOAuthTokens(ctx context.Context, userID, provider string) (accessEnc, accessNonce, refreshEnc, refreshNonce []byte, expiresAt time.Time, err error)
DeleteOAuthTokens(ctx context.Context, userID, provider string) error
}
OAuthTokenStore handles OAuth token persistence.
type OAuthTokens ¶
OAuthTokens from provider.
type OAuthUser ¶
type OAuthUser struct {
ID string
Email string
EmailVerified bool
Name string
Avatar string
Raw map[string]any
}
OAuthUser from provider.
type Option ¶
type Option func(*AuthService) error
Option configures the AuthService.
func ConfigFromEnv ¶
func ConfigFromEnv() []Option
ConfigFromEnv creates common configuration from environment variables. See docs/env.md for the full list.
func WithAllowPasskeysForRoles ¶
WithAllowPasskeysForRoles restricts passkey registration to specific roles.
func WithAuditRetention ¶
WithAuditRetention sets audit log retention period.
func WithBackupCodeCount ¶
WithBackupCodeCount sets how many backup codes to generate.
func WithBackupCodeDigitsOnly ¶
WithBackupCodeDigitsOnly controls whether backup codes are numeric only.
func WithBackupCodeLength ¶
WithBackupCodeLength sets the length of backup codes.
func WithBlockDisposableEmails ¶
WithBlockDisposableEmails enables or disables disposable email blocking.
func WithCallbackPath ¶
WithCallbackPath sets the OAuth callback base path (mounted path for /{provider}/callback).
func WithCaptcha ¶
func WithCaptcha(provider CaptchaProvider) Option
WithCaptcha sets the CAPTCHA provider.
func WithCaptchaFailOpen ¶
WithCaptchaFailOpen controls whether captcha errors allow the request.
func WithCaptchaPolicy ¶
func WithCaptchaPolicy(policy CaptchaPolicy) Option
WithCaptchaPolicy configures CAPTCHA enforcement.
func WithCaptchaRequired ¶
WithCaptchaRequired enables or disables CAPTCHA enforcement.
func WithDatabase ¶
func WithDatabase(db interface{}) Option
WithDatabase is deprecated. Use stores/postgres.WithDatabase instead. This stub remains for documentation purposes.
func WithDatabases ¶
func WithDatabases(users, audit interface{}) Option
WithDatabases is deprecated. Use stores/postgres.WithDatabases instead.
func WithDeviceManagement ¶
func WithDeviceManagement(store DeviceStore) Option
WithDeviceManagement enables device/session management.
func WithDiscord ¶
WithDiscord adds Discord OAuth provider.
func WithDisposableEmailDomains ¶
WithDisposableEmailDomains overrides the disposable email domain list.
func WithEmailChangeTTL ¶
WithEmailChangeTTL sets the email change token TTL.
func WithEmailDomainCheck ¶
WithEmailDomainCheck enables or disables MX validation for email domains.
func WithEmailPassword ¶
WithEmailPassword enables/disables email+password auth.
func WithEmailVerification ¶
WithEmailVerification enables/disables email verification requirement.
func WithGitHub ¶
WithGitHub adds GitHub OAuth provider.
func WithGoogle ¶
WithGoogle adds Google OAuth provider.
func WithHIBPAPIURL ¶
WithHIBPAPIURL overrides the Have I Been Pwned API URL.
func WithIPBlock ¶
func WithIPBlock(cfg IPBlockConfig) Option
WithIPBlock configures IP blocking behavior.
func WithIPBlocker ¶
WithIPBlocker sets a custom IP blocker.
func WithIPIntelligence ¶
func WithIPIntelligence(provider IPIntelligence) Option
WithIPIntelligence adds IP reputation checking.
func WithIPPrivacy ¶
func WithIPPrivacy(cfg IPPrivacyConfig) Option
WithIPPrivacy configures IP address handling.
func WithIPRetention ¶
WithIPRetention sets IP retention period in days.
func WithLockout ¶
WithLockout configures account lockout.
func WithMagicLinks ¶
func WithMagicLinks() Option
WithMagicLinks enables passwordless magic link login.
func WithMailgun ¶
WithMailgun sets up Mailgun email provider.
func WithMailgunEmail ¶
WithMailgunEmail configures Mailgun email provider.
func WithMaxPasskeysPerUser ¶
WithMaxPasskeysPerUser limits the number of passkeys per user (0 = unlimited).
func WithMemoryBlacklist ¶
func WithMemoryBlacklist() Option
WithMemoryBlacklist enables in-memory token blacklisting.
func WithMemoryRateLimiter ¶
func WithMemoryRateLimiter() Option
WithMemoryRateLimiter configures in-memory rate limiting. Note: Only suitable for single-instance deployments or development.
func WithMicrosoft ¶
WithMicrosoft adds Microsoft OAuth provider.
func WithMongoStore ¶
WithMongoStore is deprecated. Use stores/mongodb.WithDatabase instead.
func WithMultiTenant ¶
func WithMultiTenant(store TenantStore) Option
WithMultiTenant enables multi-tenant support.
func WithMySQLStore ¶
func WithMySQLStore(usersDB, auditDB interface{}) Option
WithMySQLStore is deprecated. Use stores/mysql.WithDatabase instead.
func WithNotifyOnEmailChange ¶
WithNotifyOnEmailChange enables email change notifications.
func WithNotifyOnPasswordChange ¶
WithNotifyOnPasswordChange enables password change notifications.
func WithOAuth ¶
func WithOAuth(provider OAuthProvider) Option
WithOAuth adds a custom OAuth provider.
func WithOAuthEmailLinking ¶
WithOAuthEmailLinking configures OAuth email linking behavior.
func WithOAuthSuccessHandler ¶ added in v1.1.5
func WithOAuthSuccessHandler(handler func(http.ResponseWriter, *http.Request, string, *OAuthUser, *OAuthTokens) bool) Option
WithOAuthSuccessHandler sets a custom handler for successful OAuth authentication.
func WithPasswordPolicy ¶
WithPasswordPolicy configures password requirements.
func WithPasswordReset ¶
WithPasswordReset enables/disables password reset.
func WithPostgresStore ¶
func WithPostgresStore(usersPool, auditPool interface{}) Option
WithPostgresStore is deprecated. Use stores/postgres.WithDatabase instead.
func WithProfileStore ¶
func WithProfileStore(store ProfileStore) Option
WithProfileStore sets a custom profile store.
func WithRateLimiter ¶
func WithRateLimiter(limiter RateLimiter) Option
WithRateLimiter sets a custom rate limiter.
func WithRateLimits ¶
func WithRateLimits(cfg RateLimitConfig) Option
WithRateLimits sets rate limits for auth endpoints.
func WithReCaptcha ¶
WithReCaptcha adds Google reCAPTCHA v2.
func WithReCaptchaV3 ¶
WithReCaptchaV3 adds Google reCAPTCHA v3 with score threshold.
func WithRedisBlacklist ¶
WithRedisBlacklist enables Redis-backed token blacklisting.
func WithRedisRateLimiter ¶
WithRedisRateLimiter configures Redis-based rate limiting.
func WithRequire2FAForAuth ¶
WithRequire2FAForAuth enforces 2FA on protected routes.
func WithRequire2FAForEmailChange ¶
WithRequire2FAForEmailChange enforces 2FA for email change requests.
func WithRequire2FAForMagicLink ¶
WithRequire2FAForMagicLink enforces 2FA after magic link login.
func WithRequire2FAForOAuth ¶
WithRequire2FAForOAuth enforces 2FA after OAuth login.
func WithRequire2FAForSDK ¶
WithRequire2FAForSDK enforces 2FA before issuing SDK tokens.
func WithRequireVerifiedEmailForAuth ¶
WithRequireVerifiedEmailForAuth enforces verified email on protected routes.
func WithResend ¶
WithResend sets up Resend email provider.
func WithResendEmail ¶
WithResendEmail configures the Resend email provider.
func WithRolePermissions ¶
func WithRolePermissions(rp map[Role][]Permission) Option
WithRolePermissions sets custom role-permission mappings.
func WithRotateRefreshTokens ¶
WithRotateRefreshTokens enables refresh token rotation.
func WithSMTPEmail ¶
WithSMTPEmail configures SMTP email provider.
func WithSQLiteStore ¶
func WithSQLiteStore(usersDB, auditDB interface{}) Option
WithSQLiteStore is deprecated. Use stores/sqlite.WithDatabase instead.
func WithSecrets ¶
WithSecrets sets the cryptographic secrets.
func WithSecretsFromAWSSSM ¶
func WithSecretsFromAWSSSM(ctx context.Context, cfg AWSSSMConfig) Option
WithSecretsFromAWSSSM loads secrets from AWS SSM Parameter Store.
func WithSecretsFromAWSSecretsManager ¶
func WithSecretsFromAWSSecretsManager(ctx context.Context, cfg AWSSecretsConfig) Option
WithSecretsFromAWSSecretsManager loads secrets from AWS Secrets Manager.
func WithSecretsFromEnv ¶
func WithSecretsFromEnv() Option
WithSecretsFromEnv loads secrets from environment variables.
func WithSecretsFromEnvFile ¶
WithSecretsFromEnvFile loads secrets from a .env file.
func WithSecretsFromEnvFileWithPrefix ¶
WithSecretsFromEnvFileWithPrefix loads secrets from a .env file with a custom prefix.
func WithSecretsFromFiles ¶
WithSecretsFromFiles loads secrets from three files (one per secret).
func WithSecretsFromJSONFile ¶
WithSecretsFromJSONFile loads secrets from a JSON file.
func WithSecretsFromRawFile ¶
WithSecretsFromRawFile loads secrets from a raw file with three lines.
func WithSecretsFromVault ¶
func WithSecretsFromVault(cfg VaultConfig) Option
WithSecretsFromVault loads secrets from HashiCorp Vault.
func WithSecretsFromVaultEnv ¶
func WithSecretsFromVaultEnv() Option
WithSecretsFromVaultEnv loads Vault config from env and fetches secrets.
func WithSecurityMode ¶
func WithSecurityMode(mode SecurityMode) Option
WithSecurityMode applies a preset security configuration.
func WithSecurityMonitor ¶
func WithSecurityMonitor(monitor SecurityMonitor) Option
WithSecurityMonitor sets a custom security monitor.
func WithSendGrid ¶
WithSendGrid sets up SendGrid email provider.
func WithSendGridEmail ¶
WithSendGridEmail configures SendGrid email provider.
func WithTOTPAccountName ¶
WithTOTPAccountName sets a fixed account name for TOTP entries.
func WithTOTPDigits ¶
WithTOTPDigits sets the number of digits for TOTP (6 or 8).
func WithTOTPQRCode ¶
WithTOTPQRCode enables or disables QR code generation in setup responses.
func WithTOTPQRCodeSize ¶
WithTOTPQRCodeSize sets the QR code size in pixels.
func WithTOTPUseUsername ¶
WithTOTPUseUsername uses the username (when present) for TOTP account name.
func WithTokenBlacklist ¶
func WithTokenBlacklist(bl TokenBlacklist) Option
WithTokenBlacklist enables immediate token revocation.
func WithTokenTTL ¶
WithTokenTTL sets token lifetimes.
func WithTrustProxyHeaders ¶
WithTrustProxyHeaders enables or disables proxy header parsing.
func WithTrustedProxies ¶
WithTrustedProxies enables trusted proxy parsing for client IPs.
func WithTurnstile ¶
WithTurnstile adds Cloudflare Turnstile CAPTCHA.
func WithTwitch ¶
WithTwitch adds Twitch OAuth provider.
func WithUnverifiedAccountTTL ¶
WithUnverifiedAccountTTL sets how long unverified accounts can remain.
func WithUserAgentHashInLogs ¶
WithUserAgentHashInLogs toggles user-agent hashing in audit logs.
func WithUsername ¶
WithUsername enables/disables username support.
func WithUsernameAllowNumericOnly ¶
WithUsernameAllowNumericOnly allows usernames that are only digits.
func WithUsernamePattern ¶
WithUsernamePattern enforces a regex pattern for usernames.
func WithUsernamePolicy ¶
WithUsernamePolicy configures username length rules.
func WithUsernameRequired ¶
WithUsernameRequired enforces username on registration.
func WithUsernameReserved ¶
WithUsernameReserved configures reserved usernames.
func WithWebAuthn ¶
func WithWebAuthn(config WebAuthnConfig) Option
WithWebAuthn enables WebAuthn/Passkey support.
func WithWebAuthnStore ¶
func WithWebAuthnStore(store WebAuthnStore) Option
WithWebAuthnStore sets the WebAuthn credential store.
func WithWebhooks ¶
func WithWebhooks(store WebhookStore) Option
WithWebhooks enables webhook support.
func WithoutIPStorage ¶
func WithoutIPStorage() Option
WithoutIPStorage disables IP storage entirely.
type PasswordChangeMailer ¶
PasswordChangeMailer sends password change notifications.
type PasswordHistory ¶
PasswordHistory for preventing password reuse.
type PasswordResetToken ¶
type PasswordResetToken struct {
ID string
UserID string
TokenHash []byte
ExpiresAt time.Time
Used bool
}
PasswordResetToken for password resets.
type Permission ¶
type Permission string
Permission represents a specific permission.
const ( PermissionRead Permission = "read" PermissionWrite Permission = "write" PermissionDelete Permission = "delete" PermissionAdmin Permission = "admin" )
Common permissions
type Profile ¶
type Profile struct {
UserID string
DisplayName string
DisplayPhotoURL string
Bio string
Locale string
Timezone string
Metadata map[string]any
CreatedAt time.Time
UpdatedAt time.Time
}
Profile represents user profile data stored separately from auth records.
type ProfileProvider ¶
type ProfileProvider interface {
Profiles() ProfileStore
}
ProfileProvider exposes a profile store when supported.
type ProfileStore ¶
type ProfileStore interface {
GetProfile(ctx context.Context, userID string) (*Profile, error)
UpsertProfile(ctx context.Context, profile Profile) error
DeleteProfile(ctx context.Context, userID string) error
}
ProfileStore handles user profiles.
type RateLimitConfig ¶
type RateLimitConfig struct {
LoginLimit int
LoginWindow time.Duration
TwoFALimit int
TwoFAWindow time.Duration
RegisterLimit int
RegisterWindow time.Duration
PasswordResetLimit int
PasswordResetWindow time.Duration
MagicLinkLimit int
MagicLinkWindow time.Duration
}
RateLimitConfig defines per-endpoint rate limits.
type RateLimiter ¶
type RateLimiter interface {
Allow(ctx context.Context, key string, limit int, window time.Duration) (allowed bool, remaining int, err error)
}
RateLimiter provides rate limiting.
type ReCaptchaConfig ¶
type ReCaptchaConfig struct {
// Secret is your reCAPTCHA secret key
Secret string
// MinScore is the minimum score for v3 (0.0 to 1.0, default 0.5)
MinScore float64
// IsV3 indicates whether this is reCAPTCHA v3 (score-based)
IsV3 bool
}
ReCaptchaConfig holds reCAPTCHA configuration.
type ReCaptchaProvider ¶
type ReCaptchaProvider struct {
// contains filtered or unexported fields
}
ReCaptchaProvider implements CaptchaProvider for Google reCAPTCHA.
func NewReCaptcha ¶
func NewReCaptcha(secret string) *ReCaptchaProvider
NewReCaptcha creates a Google reCAPTCHA provider. Get your keys from: https://www.google.com/recaptcha/admin
func NewReCaptchaV3 ¶
func NewReCaptchaV3(secret string, minScore float64) *ReCaptchaProvider
NewReCaptchaV3 creates a Google reCAPTCHA v3 provider with score threshold.
func (*ReCaptchaProvider) Name ¶
func (r *ReCaptchaProvider) Name() string
type RedisBlacklist ¶
type RedisBlacklist struct {
// contains filtered or unexported fields
}
RedisBlacklist uses Redis for distributed token blacklisting.
func NewRedisBlacklist ¶
func NewRedisBlacklist(client *redis.Client) *RedisBlacklist
NewRedisBlacklist creates a Redis-backed token blacklist.
func (*RedisBlacklist) Cleanup ¶
func (b *RedisBlacklist) Cleanup()
func (*RedisBlacklist) IsBlacklisted ¶
type RequestDeduplicator ¶
type RequestDeduplicator struct {
// contains filtered or unexported fields
}
RequestDeduplicator prevents duplicate requests within a time window.
func NewRequestDeduplicator ¶
func NewRequestDeduplicator(ttl time.Duration) *RequestDeduplicator
NewRequestDeduplicator creates a new request deduplicator.
type RequestTracker ¶
type RequestTracker struct {
// contains filtered or unexported fields
}
RequestTracker tracks in-flight requests for graceful shutdown.
type ResourceChecker ¶
ResourceChecker is called to verify access to a specific resource.
type Secrets ¶
Secrets holds cryptographic secrets.
func MustSecretsFromEnv ¶
func MustSecretsFromEnv() Secrets
MustSecretsFromEnv loads secrets from environment or panics.
func SecretsFromAWSSSM ¶
func SecretsFromAWSSSM(ctx context.Context, cfg AWSSSMConfig) (Secrets, error)
SecretsFromAWSSSM loads secrets from AWS SSM Parameter Store.
func SecretsFromAWSSecretsManager ¶
func SecretsFromAWSSecretsManager(ctx context.Context, cfg AWSSecretsConfig) (Secrets, error)
SecretsFromAWSSecretsManager loads secrets from AWS Secrets Manager. The secret value must be a JSON object with jwt/encryption/pepper keys.
func SecretsFromEnv ¶
SecretsFromEnv loads secrets from environment variables. Expected variables:
- GOAUTH_JWT_SECRET (base64 encoded, 32 bytes)
- GOAUTH_ENCRYPTION_KEY (base64 encoded, 32 bytes)
- GOAUTH_PEPPER (base64 encoded, 32 bytes)
func SecretsFromEnvFile ¶
SecretsFromEnvFile loads secrets from a .env style file.
func SecretsFromEnvFileWithPrefix ¶
SecretsFromEnvFileWithPrefix loads secrets from a .env file with a custom prefix.
func SecretsFromEnvWithPrefix ¶
SecretsFromEnvWithPrefix loads secrets with a custom prefix. Example: SecretsFromEnvWithPrefix("MYAPP") reads MYAPP_JWT_SECRET, etc.
func SecretsFromFiles ¶
SecretsFromFiles loads secrets from three plain files (one per secret).
func SecretsFromJSON ¶
SecretsFromJSON loads secrets from a JSON payload.
func SecretsFromJSONFile ¶
SecretsFromJSONFile loads secrets from a JSON file.
func SecretsFromRawFile ¶
SecretsFromRawFile loads secrets from a single raw file with three lines. Line 1: JWT secret, Line 2: Encryption key, Line 3: Pepper.
func SecretsFromVault ¶
func SecretsFromVault(ctx context.Context, cfg VaultConfig) (Secrets, error)
SecretsFromVault loads secrets from HashiCorp Vault.
type SecurityAlert ¶
type SecurityAlert struct {
Type string
UserID string
IP string
Details map[string]any
Severity string // "low", "medium", "high", "critical"
Timestamp time.Time
}
SecurityAlert represents a security event that may need attention.
type SecurityAlertMailer ¶
type SecurityAlertMailer interface {
SendSecurityAlert(ctx context.Context, to, event, details string) error
}
SecurityAlertMailer sends security alert emails.
type SecurityMode ¶
type SecurityMode string
SecurityMode defines preset security configurations.
const ( SecurityModePermissive SecurityMode = "permissive" SecurityModeBalanced SecurityMode = "balanced" SecurityModeStrict SecurityMode = "strict" )
type SecurityMonitor ¶
type SecurityMonitor interface {
OnAlert(ctx context.Context, alert SecurityAlert)
}
SecurityMonitor interface for security event handling.
type Session ¶
type Session struct {
ID string
UserID string
TenantID string // For multi-tenant
DeviceID string
ExpiresAt time.Time
CreatedAt time.Time
LastActive time.Time
IPAddress []byte // Encrypted
IPNonce []byte
UserAgent string
Data map[string]any // Custom session data
}
Session represents an active user session.
type SessionStore ¶
type SessionStore interface {
CreateSession(ctx context.Context, session Session) error
GetSession(ctx context.Context, sessionID string) (*Session, error)
UpdateSession(ctx context.Context, sessionID string, data map[string]any) error
ExtendSession(ctx context.Context, sessionID string, expiresAt time.Time) error
DeleteSession(ctx context.Context, sessionID string) error
DeleteUserSessions(ctx context.Context, userID string) error
}
SessionStore handles session persistence.
type SlidingWindowRateLimiter ¶
type SlidingWindowRateLimiter struct {
// contains filtered or unexported fields
}
SlidingWindowRateLimiter implements a precise sliding window rate limiter.
func NewSlidingWindowRateLimiter ¶
func NewSlidingWindowRateLimiter(limit int, window time.Duration) *SlidingWindowRateLimiter
NewSlidingWindowRateLimiter creates a new sliding window rate limiter.
type Store ¶
type Store interface {
Users() UserStore
Tokens() TokenStore
Audit() AuditStore
}
Store is the main storage interface.
type StoreCleaner ¶
type StoreCleaner interface {
// CleanupExpiredTokens removes all expired tokens.
CleanupExpiredTokens(ctx context.Context) (int64, error)
// CleanupOldAuditLogs removes audit logs older than retention period.
CleanupOldAuditLogs(ctx context.Context, retention time.Duration) (int64, error)
// CleanupUnverifiedAccounts removes unverified accounts past deadline.
CleanupUnverifiedAccounts(ctx context.Context) (int64, error)
}
StoreCleaner is an optional interface for stores that support cleanup.
type Tenant ¶
type Tenant struct {
ID string
Name string
Slug string // URL-friendly identifier
Plan string // "free", "pro", "enterprise"
Settings TenantSettings
CreatedAt time.Time
SuspendedAt *time.Time
}
Tenant represents an organization/workspace in multi-tenant mode.
type TenantSettings ¶
type TenantSettings struct {
MaxUsers int
AllowedDomains []string // Email domains allowed to register
EnforceMFA bool // Require 2FA for all users
SessionTimeout time.Duration
AllowedOAuthProviders []string
CustomBranding map[string]string // logo_url, primary_color, etc.
}
TenantSettings holds per-tenant configuration.
type TenantStore ¶
type TenantStore interface {
GetTenant(ctx context.Context, tenantID string) (*Tenant, error)
GetTenantBySlug(ctx context.Context, slug string) (*Tenant, error)
CreateTenant(ctx context.Context, tenant Tenant) (string, error)
UpdateTenantSettings(ctx context.Context, tenantID string, settings TenantSettings) error
GetUserTenants(ctx context.Context, userID string) ([]Tenant, error)
}
TenantStore handles tenant operations.
type TokenBlacklist ¶
type TokenBlacklist interface {
// Add adds a token to the blacklist until its expiry.
Add(ctx context.Context, jti string, expiresAt time.Time) error
// IsBlacklisted checks if a token is blacklisted.
IsBlacklisted(ctx context.Context, jti string) (bool, error)
// Cleanup removes expired entries (for in-memory implementation).
Cleanup()
}
TokenBlacklist allows immediate revocation of JWT tokens.
type TokenStore ¶
type TokenStore interface {
CreateVerificationToken(ctx context.Context, token VerificationToken, ipEnc, ipNonce []byte) (string, error)
GetActiveVerificationToken(ctx context.Context, userID string) (*VerificationToken, error)
GetVerificationTokenByLinkHash(ctx context.Context, linkHash []byte) (*VerificationToken, error)
IncrementVerificationAttempts(ctx context.Context, tokenID string) (int, error)
MarkVerificationTokenUsed(ctx context.Context, tokenID string, ipEnc, ipNonce []byte) error
CreatePasswordResetToken(ctx context.Context, token PasswordResetToken, ipEnc, ipNonce []byte) (string, error)
GetPasswordResetTokenByHash(ctx context.Context, tokenHash []byte) (*PasswordResetToken, error)
MarkPasswordResetUsed(ctx context.Context, tokenID string, ipEnc, ipNonce []byte) error
CreateEmailChangeToken(ctx context.Context, token EmailChangeToken, ipEnc, ipNonce []byte) (string, error)
GetEmailChangeTokenByHash(ctx context.Context, tokenHash []byte) (*EmailChangeToken, error)
MarkEmailChangeUsed(ctx context.Context, tokenID string, ipEnc, ipNonce []byte) error
StoreRefreshToken(ctx context.Context, userID, jti string, expiresAt time.Time, ipEnc, ipNonce []byte) error
RefreshTokenValid(ctx context.Context, jti string) (bool, error)
RevokeRefreshToken(ctx context.Context, jti string) error
RevokeAllRefreshTokens(ctx context.Context, userID string) error
}
TokenStore handles token operations.
type TurnstileProvider ¶
type TurnstileProvider struct {
// contains filtered or unexported fields
}
TurnstileProvider implements CaptchaProvider for Cloudflare Turnstile.
func NewTurnstile ¶
func NewTurnstile(secret string) *TurnstileProvider
NewTurnstile creates a Cloudflare Turnstile CAPTCHA provider. Get your site key and secret from: https://dash.cloudflare.com/turnstile
func (*TurnstileProvider) Name ¶
func (t *TurnstileProvider) Name() string
type TwitchProvider ¶
type TwitchProvider struct {
BaseOAuthProvider
}
TwitchProvider implements OAuth for Twitch.
func NewTwitchProvider ¶
func NewTwitchProvider(clientID, clientSecret string) *TwitchProvider
NewTwitchProvider creates a Twitch OAuth provider.
func (*TwitchProvider) RefreshToken ¶
func (p *TwitchProvider) RefreshToken(ctx context.Context, refreshToken string) (*OAuthTokens, error)
RefreshToken refreshes a Twitch access token.
func (*TwitchProvider) RevokeToken ¶
func (p *TwitchProvider) RevokeToken(ctx context.Context, token string) error
RevokeToken revokes a Twitch access token.
type User ¶
type User struct {
ID string
EmailHash []byte
EmailEncrypted []byte
EmailNonce []byte
Username string
UsernameNormalized string
PasswordHash []byte
PasswordSalt []byte
TOTPSecretEncrypted []byte
TOTPNonce []byte
TOTPEnabled bool
EmailVerified bool
AccountStatus string
Role string
FailedLoginAttempts int
LockedAt *time.Time
LastLoginAt *time.Time
LastLoginIPEncrypted []byte
LastLoginIPNonce []byte
CreatedAt time.Time
UpdatedAt time.Time
Metadata map[string]any
}
User represents an authenticated user.
type UserDeleter ¶
UserDeleter handles user deletion.
type UserStore ¶
type UserStore interface {
EmailExists(ctx context.Context, emailHash []byte) (bool, error)
UsernameExists(ctx context.Context, usernameNormalized string) (bool, error)
CreateUser(ctx context.Context, user User, verificationDeadline time.Time) (string, error)
GetUserByEmailHash(ctx context.Context, emailHash []byte) (*User, error)
GetUserByUsername(ctx context.Context, usernameNormalized string) (*User, error)
GetUserByID(ctx context.Context, userID string) (*User, error)
SetUserVerified(ctx context.Context, userID string) error
IncrementLoginFailures(ctx context.Context, userID string) (int, error)
LockUser(ctx context.Context, userID string) error
UnlockUser(ctx context.Context, userID string) error
ResetLoginFailures(ctx context.Context, userID string) error
UpdateLastLogin(ctx context.Context, userID string, ipEnc, ipNonce []byte) error
UpdateUsername(ctx context.Context, userID, username, usernameNormalized string) error
UpdatePassword(ctx context.Context, userID string, hash, salt []byte) error
UpdateEmail(ctx context.Context, userID string, emailHash, emailEnc, emailNonce []byte, verified bool) error
RecentPasswordHistory(ctx context.Context, userID string, limit int) ([]PasswordHistory, error)
UpdateTOTPSecret(ctx context.Context, userID string, secretEnc, secretNonce []byte) error
EnableTOTP(ctx context.Context, userID string) error
DisableTOTP(ctx context.Context, userID string) error
ReplaceBackupCodes(ctx context.Context, userID string, hashes [][]byte) error
UseBackupCode(ctx context.Context, userID string, codeHash []byte) (bool, error)
UpdateUserRole(ctx context.Context, userID string, role string) error
}
UserStore handles user operations.
type VaultConfig ¶
type VaultConfig struct {
// Address is the Vault server address (e.g., https://vault.example.com)
Address string
// Token is the Vault authentication token
Token string
// Path is the secret path (e.g., secret/data/myapp)
Path string
// Keys maps secret keys to our expected keys (optional)
// Default: jwt_secret, encryption_key, pepper
Keys map[string]string
}
VaultConfig holds HashiCorp Vault configuration.
type VerificationToken ¶
type VerificationToken struct {
ID string
UserID string
CodeHash []byte
LinkHash []byte
EmailHash []byte
ExpiresAt time.Time
CodeAttempts int
MaxAttempts int
Used bool
}
VerificationToken for email verification.
type WebAuthnChallenge ¶
type WebAuthnChallenge struct {
Challenge []byte
UserID string
SessionData []byte
ExpiresAt time.Time
Type string // "registration" or "authentication"
}
WebAuthnChallenge represents a pending WebAuthn challenge.
type WebAuthnConfig ¶
type WebAuthnConfig struct {
// RPDisplayName is the display name of your application
RPDisplayName string
// RPID is the relying party ID (usually your domain without protocol)
RPID string
// RPOrigins are the allowed origins for WebAuthn requests
RPOrigins []string
// Timeout for challenges in milliseconds
Timeout int
// AttestationPreference: "none", "indirect", or "direct"
AttestationPreference string
// UserVerification: "required", "preferred", or "discouraged"
UserVerification string
// ResidentKeyRequirement: "required", "preferred", or "discouraged"
ResidentKeyRequirement string
// AllowCredentials enables discoverable credentials (passkeys)
AllowCredentials bool
// MaxPasskeysPerUser limits how many passkeys a user can register (0 = unlimited)
MaxPasskeysPerUser int
// AllowPasskeysForRoles limits passkey registration to specific roles (empty = allow all)
AllowPasskeysForRoles []Role
}
WebAuthnConfig configures WebAuthn/Passkey behavior.
func DefaultWebAuthnConfig ¶
func DefaultWebAuthnConfig() WebAuthnConfig
DefaultWebAuthnConfig returns sensible defaults for WebAuthn.
type WebAuthnCredential ¶
type WebAuthnCredential struct {
ID string `json:"id"`
UserID string `json:"user_id"`
CredentialID []byte `json:"credential_id"`
PublicKey []byte `json:"public_key"`
AttestationType string `json:"attestation_type"`
AAGUID []byte `json:"aaguid"`
SignCount uint32 `json:"sign_count"`
CloneWarning bool `json:"clone_warning"`
Transports []string `json:"transports,omitempty"`
CreatedAt time.Time `json:"created_at"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
Name string `json:"name"`
}
WebAuthnCredential represents a stored passkey/security key.
type WebAuthnNameStore ¶
type WebAuthnNameStore interface {
UpdateCredentialName(ctx context.Context, userID string, credentialID []byte, name string) error
}
WebAuthnNameStore updates credential names when supported.
type WebAuthnStore ¶
type WebAuthnStore interface {
// Credentials
CreateCredential(ctx context.Context, cred WebAuthnCredential) error
GetCredentialByID(ctx context.Context, credentialID []byte) (*WebAuthnCredential, error)
GetUserCredentials(ctx context.Context, userID string) ([]WebAuthnCredential, error)
UpdateCredentialSignCount(ctx context.Context, credentialID []byte, signCount uint32) error
DeleteCredential(ctx context.Context, userID string, credentialID []byte) error
// Challenges
StoreChallenge(ctx context.Context, challenge WebAuthnChallenge) error
GetChallenge(ctx context.Context, challenge []byte) (*WebAuthnChallenge, error)
DeleteChallenge(ctx context.Context, challenge []byte) error
}
WebAuthnStore handles WebAuthn credential persistence.
type WebAuthnUsageStore ¶
type WebAuthnUsageStore interface {
UpdateCredentialUsage(ctx context.Context, credentialID []byte, signCount uint32, lastUsedAt time.Time) error
}
WebAuthnUsageStore updates usage metadata when supported.
type Webhook ¶
type Webhook struct {
ID string
URL string
Secret string // For signature verification
Events []WebhookEvent
TenantID string // Optional, for multi-tenant
Active bool
CreatedAt time.Time
}
Webhook represents a configured webhook.
type WebhookEvent ¶
type WebhookEvent string
WebhookEvent represents an event that can trigger webhooks.
const ( WebhookEventUserCreated WebhookEvent = "user.created" WebhookEventUserVerified WebhookEvent = "user.verified" WebhookEventUserLogin WebhookEvent = "user.login" WebhookEventUserLogout WebhookEvent = "user.logout" WebhookEventUserPasswordReset WebhookEvent = "user.password_reset" WebhookEvent2FAEnabled WebhookEvent = "user.2fa_enabled" WebhookEvent2FADisabled WebhookEvent = "user.2fa_disabled" WebhookEventAccountLocked WebhookEvent = "user.account_locked" WebhookEventAccountDeleted WebhookEvent = "user.account_deleted" WebhookEventSuspiciousLogin WebhookEvent = "security.suspicious_login" )
type WebhookPayload ¶
type WebhookPayload struct {
Event WebhookEvent `json:"event"`
Timestamp time.Time `json:"timestamp"`
Data map[string]any `json:"data"`
}
WebhookPayload is sent to webhook endpoints.
type WebhookStore ¶
type WebhookStore interface {
GetActiveWebhooks(ctx context.Context, event WebhookEvent, tenantID string) ([]Webhook, error)
CreateWebhook(ctx context.Context, webhook Webhook) (string, error)
DeleteWebhook(ctx context.Context, webhookID string) error
}
WebhookStore handles webhook configuration.
Source Files
¶
- abuse.go
- adapters.go
- blacklist.go
- captcha.go
- clients.go
- email_change.go
- email_policy.go
- enterprise.go
- env.go
- errors.go
- goauth.go
- handlers.go
- http.go
- interfaces.go
- ip_access.go
- jobs.go
- middleware.go
- oauth.go
- oauth_handlers.go
- oauth_refresh.go
- oauth_tokens.go
- observability.go
- options.go
- performance.go
- profile.go
- rbac.go
- sdk.go
- secrets_aws.go
- security.go
- security_mode.go
- webauthn.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package crypto provides cryptographic utilities for secure authentication.
|
Package crypto provides cryptographic utilities for secure authentication. |
|
examples
|
|
|
full
command
Example: Full Setup with OAuth, Email, CAPTCHA
|
Example: Full Setup with OAuth, Email, CAPTCHA |
|
minimal
command
Example: Minimal Setup
|
Example: Minimal Setup |
|
oauth_only
command
Example: OAuth Only
|
Example: OAuth Only |
|
privacy
command
Example: Privacy-Focused
|
Example: Privacy-Focused |
|
mailers
|
|
|
mailgun
Package mailgun provides a Mailgun email provider implementation.
|
Package mailgun provides a Mailgun email provider implementation. |
|
resend
Package resend provides a Resend email provider implementation.
|
Package resend provides a Resend email provider implementation. |
|
sendgrid
Package sendgrid provides a SendGrid email provider implementation.
|
Package sendgrid provides a SendGrid email provider implementation. |
|
smtp
Package smtp provides an SMTP email provider implementation.
|
Package smtp provides an SMTP email provider implementation. |
|
ratelimit
|
|
|
memory
Package memory provides an in-memory rate limiter for development.
|
Package memory provides an in-memory rate limiter for development. |
|
redis
Package redis provides a Redis rate limiter implementation.
|
Package redis provides a Redis rate limiter implementation. |
|
stores
|
|
|
mongodb
Package mongodb provides a MongoDB implementation of the goauth.Store interface.
|
Package mongodb provides a MongoDB implementation of the goauth.Store interface. |
|
mysql
Package mysql provides a MySQL implementation of the goauth.Store interface.
|
Package mysql provides a MySQL implementation of the goauth.Store interface. |
|
postgres
Package postgres provides a PostgreSQL implementation of the goauth.Store interface.
|
Package postgres provides a PostgreSQL implementation of the goauth.Store interface. |
|
sqlite
Package sqlite provides a SQLite implementation of the goauth.Store interface.
|
Package sqlite provides a SQLite implementation of the goauth.Store interface. |
|
sqlstore
Package sqlstore provides a SQL store implementation for goauth using database/sql.
|
Package sqlstore provides a SQL store implementation for goauth using database/sql. |