goauth

package module
v1.1.5 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2026 License: MIT Imports: 43 Imported by: 0

README

GoAuth

Go Reference Go Report Card

Security-first authentication for Go apps, designed for SaaS and enterprise scale.

Features

  • Email/password with Argon2id, breach checks (HIBP)
  • OAuth providers (Google, Discord, GitHub, Microsoft, Twitch, custom)
  • WebAuthn/passkeys with optional limits and role gating
  • TOTP 2FA with backup codes (digits-only by default)
  • Magic links, API keys, device sessions, RBAC
  • Privacy controls (IP encryption, hashing, retention)
  • Rate limiting, IP blocking, CAPTCHA, token blacklist

Installation

go get github.com/migueldesapazr-gif/goauth

Database Setup

Initialize your PostgreSQL database with the provided schema:

psql -d your_database -f schema/postgres.sql

Quick Start

package main

import (
	"context"
	"log"
	"net/http"
	"os"

	"github.com/go-chi/chi/v5"
	"github.com/jackc/pgx/v5/pgxpool"

	"github.com/migueldesapazr-gif/goauth"
	"github.com/migueldesapazr-gif/goauth/stores/postgres"
)

func main() {
	db, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	auth, err := goauth.New(
		postgres.WithDatabase(db),
		goauth.WithSecretsFromEnv(),
		goauth.WithSecurityMode(goauth.SecurityModeBalanced),
	)
	if err != nil {
		log.Fatal(err)
	}

	r := chi.NewRouter()
	r.Mount("/auth", auth.Handler())

	log.Println("listening on :8080")
	log.Fatal(http.ListenAndServe(":8080", r))
}

OAuth Configuration

Configure OAuth providers with customizable scopes:

goauth.WithGoogle(clientID, clientSecret, goauth.WithGoogleScopes("email", "profile", "openid"))
goauth.WithDiscord(clientID, clientSecret, goauth.WithDiscordScopes("identify", "email", "guilds"))
goauth.WithGitHub(clientID, clientSecret, goauth.WithGitHubScopes("user:email", "read:user"))

CAPTCHA

Choose your provider:

// Cloudflare Turnstile
goauth.WithTurnstile(secret)

// Google reCAPTCHA v2 (checkbox)
goauth.WithReCaptcha(secret)

// Google reCAPTCHA v3 (invisible, score-based)
goauth.WithReCaptchaV3(secret, 0.5)

// hCaptcha
goauth.WithHCaptcha(secret)

Environment Variables

GOAUTH_JWT_SECRET=base64-32-bytes
GOAUTH_ENCRYPTION_KEY=base64-32-bytes
GOAUTH_PEPPER=base64-32-bytes
DATABASE_URL=postgres://user:pass@localhost/db

OAuth providers (optional):

GOOGLE_CLIENT_ID=xxx
GOOGLE_CLIENT_SECRET=xxx
DISCORD_CLIENT_ID=xxx
DISCORD_CLIENT_SECRET=xxx
GITHUB_CLIENT_ID=xxx
GITHUB_CLIENT_SECRET=xxx

Proxy deployments (Cloudflare, load balancers):

GOAUTH_TRUST_PROXY_HEADERS=true
GOAUTH_TRUSTED_PROXIES=10.0.0.0/8,192.168.0.0/16

Documentation

  • docs/QUICK_START.md
  • docs/CONFIGURATION.md
  • docs/API.md
  • docs/security.md
  • docs/flows.md

License

MIT License - see LICENSE

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

View Source
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.

View Source
const (
	StatusActive              = "active"
	StatusPendingVerification = "pending_verification"
	StatusLocked              = "locked"
	StatusSuspended           = "suspended"
	StatusDeleted             = "deleted"
)

Account statuses

View Source
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

View Source
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

View Source
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.

View Source
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.

View Source
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.

View Source
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)
)

RolePermissions maps roles to their permissions.

View Source
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

func GetClaimsFromContext(ctx context.Context) (*crypto.Claims, bool)

GetClaimsFromContext retrieves the JWT claims from the request context.

func GetClientIP

func GetClientIP(r *http.Request) string

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.

func (*AuthError) Error

func (e *AuthError) Error() string

func (*AuthError) Is

func (e *AuthError) Is(target error) bool

Is implements errors.Is for AuthError comparison.

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

type AuthService

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

AuthService is the main entry point for the authentication library.

func New

func New(opts ...Option) (*AuthService, error)

New creates a new AuthService.

func (*AuthService) APIKeyMiddleware

func (s *AuthService) APIKeyMiddleware() func(http.Handler) http.Handler

APIKeyMiddleware authenticates requests using API keys.

func (*AuthService) CheckSuspiciousLogin

func (s *AuthService) CheckSuspiciousLogin(ctx context.Context, user *User, r *http.Request) bool

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

func (s *AuthService) LastLoginIP(ctx context.Context, userID string) (string, error)

LastLoginIP returns the last stored login IP for a user when IP storage is enabled.

func (*AuthService) Logger

func (s *AuthService) Logger() *zap.Logger

Logger returns the logger.

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

func (s *AuthService) RequireRole(roles ...Role) func(http.Handler) http.Handler

RequireRole creates middleware that requires the user to have a specific role.

func (*AuthService) RequireScope

func (s *AuthService) RequireScope(scopes ...Scope) func(http.Handler) http.Handler

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) Store

func (s *AuthService) Store() Store

Store returns the underlying store.

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.

func (*BackgroundJobs) Stop

func (j *BackgroundJobs) Stop(ctx context.Context) error

Stop gracefully stops all background workers.

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) GetUser

func (p *BaseOAuthProvider) GetUser(ctx context.Context, accessToken string) (*OAuthUser, 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.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sensible defaults.

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

type DataExporter interface {
	ExportUserData(ctx context.Context, userID string) ([]byte, error)
}

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

type EmailChangeMailer interface {
	SendEmailChange(ctx context.Context, to, link string) error
}

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.

func (*GracefulShutdown) Shutdown

func (g *GracefulShutdown) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the service.

func (*GracefulShutdown) Track

func (g *GracefulShutdown) Track() func(http.Handler) http.Handler

Track wraps an HTTP handler to track requests.

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

func (*HCaptchaProvider) Verify

func (h *HCaptchaProvider) Verify(ctx context.Context, token, ip string) (bool, error)

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.

func (*HTTPClientPool) GetClient

func (p *HTTPClientPool) GetClient(service string, timeout time.Duration) *http.Client

GetClient returns an HTTP client for a service.

type HealthChecker

type HealthChecker interface {
	Ping(ctx context.Context) error
}

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

type IPPrivacyConfig struct {
	StoreIP         bool
	EncryptIP       bool
	HashIPInLogs    bool
	IPRetentionDays int
}

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

func WithCleanupInterval(d time.Duration) JobOption

WithCleanupInterval sets how often cleanup runs.

func WithEmailQueueSize

func WithEmailQueueSize(n int) JobOption

WithEmailQueueSize sets the email queue buffer size.

func WithEmailWorkers

func WithEmailWorkers(n int) JobOption

WithEmailWorkers sets the number of email worker goroutines.

type MagicLinkMailer

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

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) Add

func (b *MemoryBlacklist) Add(ctx context.Context, jti string, expiresAt time.Time) error

func (*MemoryBlacklist) Cleanup

func (b *MemoryBlacklist) Cleanup()

func (*MemoryBlacklist) IsBlacklisted

func (b *MemoryBlacklist) IsBlacklisted(ctx context.Context, jti string) (bool, error)

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

type OAuthRevoker interface {
	RevokeToken(ctx context.Context, accessToken string) error
}

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

type OAuthTokens struct {
	AccessToken  string
	RefreshToken string
	ExpiresIn    int
	TokenType    string
}

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 WithAPIKeys

func WithAPIKeys(store APIKeyStore) Option

WithAPIKeys enables API key support.

func WithAllowPasskeysForRoles

func WithAllowPasskeysForRoles(roles ...Role) Option

WithAllowPasskeysForRoles restricts passkey registration to specific roles.

func WithAppName

func WithAppName(name string) Option

WithAppName sets the application name.

func WithAppURL

func WithAppURL(url string) Option

WithAppURL sets the application base URL.

func WithAuditRetention

func WithAuditRetention(d time.Duration) Option

WithAuditRetention sets audit log retention period.

func WithBackupCodeCount

func WithBackupCodeCount(count int) Option

WithBackupCodeCount sets how many backup codes to generate.

func WithBackupCodeDigitsOnly

func WithBackupCodeDigitsOnly(enabled bool) Option

WithBackupCodeDigitsOnly controls whether backup codes are numeric only.

func WithBackupCodeLength

func WithBackupCodeLength(length int) Option

WithBackupCodeLength sets the length of backup codes.

func WithBlockDisposableEmails

func WithBlockDisposableEmails(enabled bool) Option

WithBlockDisposableEmails enables or disables disposable email blocking.

func WithCallbackPath

func WithCallbackPath(path string) Option

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

func WithCaptchaFailOpen(enabled bool) Option

WithCaptchaFailOpen controls whether captcha errors allow the request.

func WithCaptchaPolicy

func WithCaptchaPolicy(policy CaptchaPolicy) Option

WithCaptchaPolicy configures CAPTCHA enforcement.

func WithCaptchaRequired

func WithCaptchaRequired(required bool) Option

WithCaptchaRequired enables or disables CAPTCHA enforcement.

func WithConfig

func WithConfig(cfg Config) Option

WithConfig sets a complete configuration.

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

func WithDiscord(clientID, clientSecret string) Option

WithDiscord adds Discord OAuth provider.

func WithDisposableEmailDomains

func WithDisposableEmailDomains(domains []string) Option

WithDisposableEmailDomains overrides the disposable email domain list.

func WithEmailChangeTTL

func WithEmailChangeTTL(ttl time.Duration) Option

WithEmailChangeTTL sets the email change token TTL.

func WithEmailDomainCheck

func WithEmailDomainCheck(enabled bool) Option

WithEmailDomainCheck enables or disables MX validation for email domains.

func WithEmailPassword

func WithEmailPassword(enabled bool) Option

WithEmailPassword enables/disables email+password auth.

func WithEmailVerification

func WithEmailVerification(required bool) Option

WithEmailVerification enables/disables email verification requirement.

func WithGitHub

func WithGitHub(clientID, clientSecret string) Option

WithGitHub adds GitHub OAuth provider.

func WithGoogle

func WithGoogle(clientID, clientSecret string) Option

WithGoogle adds Google OAuth provider.

func WithHCaptcha

func WithHCaptcha(secret string) Option

WithHCaptcha adds hCaptcha.

func WithHIBP

func WithHIBP() Option

WithHIBP enables password breach checking.

func WithHIBPAPIURL

func WithHIBPAPIURL(url string) Option

WithHIBPAPIURL overrides the Have I Been Pwned API URL.

func WithIPBlock

func WithIPBlock(cfg IPBlockConfig) Option

WithIPBlock configures IP blocking behavior.

func WithIPBlocker

func WithIPBlocker(blocker IPBlocker) Option

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

func WithIPRetention(days int) Option

WithIPRetention sets IP retention period in days.

func WithLockout

func WithLockout(maxAttempts int, duration time.Duration) Option

WithLockout configures account lockout.

func WithLogger

func WithLogger(logger *zap.Logger) Option

WithLogger sets a custom logger.

func WithMagicLinks() Option

WithMagicLinks enables passwordless magic link login.

func WithMailer

func WithMailer(mailer Mailer) Option

WithMailer sets a custom mailer.

func WithMailgun

func WithMailgun(apiKey, domain, fromEmail, fromName string) Option

WithMailgun sets up Mailgun email provider.

func WithMailgunEmail

func WithMailgunEmail(apiKey, domain, fromEmail, fromName string) Option

WithMailgunEmail configures Mailgun email provider.

func WithMaxPasskeysPerUser

func WithMaxPasskeysPerUser(limit int) Option

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

func WithMicrosoft(clientID, clientSecret string) Option

WithMicrosoft adds Microsoft OAuth provider.

func WithMongoStore

func WithMongoStore(client interface{}, dbName string) Option

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

func WithNotifyOnEmailChange(enabled bool) Option

WithNotifyOnEmailChange enables email change notifications.

func WithNotifyOnPasswordChange

func WithNotifyOnPasswordChange(enabled bool) Option

WithNotifyOnPasswordChange enables password change notifications.

func WithOAuth

func WithOAuth(provider OAuthProvider) Option

WithOAuth adds a custom OAuth provider.

func WithOAuthEmailLinking

func WithOAuthEmailLinking(allow bool, allowUnverified bool) Option

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

func WithPasswordPolicy(minLength int, requireComplexity bool, historySize int) Option

WithPasswordPolicy configures password requirements.

func WithPasswordReset

func WithPasswordReset(enabled bool) Option

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

func WithReCaptcha(secret string) Option

WithReCaptcha adds Google reCAPTCHA v2.

func WithReCaptchaV3

func WithReCaptchaV3(secret string, minScore float64) Option

WithReCaptchaV3 adds Google reCAPTCHA v3 with score threshold.

func WithRedis

func WithRedis(client *redis.Client) Option

WithRedis sets up Redis for rate limiting.

func WithRedisBlacklist

func WithRedisBlacklist(client *redis.Client) Option

WithRedisBlacklist enables Redis-backed token blacklisting.

func WithRedisRateLimiter

func WithRedisRateLimiter(client *redis.Client) Option

WithRedisRateLimiter configures Redis-based rate limiting.

func WithRequire2FAForAuth

func WithRequire2FAForAuth(required bool) Option

WithRequire2FAForAuth enforces 2FA on protected routes.

func WithRequire2FAForEmailChange

func WithRequire2FAForEmailChange(required bool) Option

WithRequire2FAForEmailChange enforces 2FA for email change requests.

func WithRequire2FAForMagicLink(required bool) Option

WithRequire2FAForMagicLink enforces 2FA after magic link login.

func WithRequire2FAForOAuth

func WithRequire2FAForOAuth(required bool) Option

WithRequire2FAForOAuth enforces 2FA after OAuth login.

func WithRequire2FAForSDK

func WithRequire2FAForSDK(required bool) Option

WithRequire2FAForSDK enforces 2FA before issuing SDK tokens.

func WithRequireVerifiedEmailForAuth

func WithRequireVerifiedEmailForAuth(required bool) Option

WithRequireVerifiedEmailForAuth enforces verified email on protected routes.

func WithResend

func WithResend(apiKey, fromEmail, fromName string) Option

WithResend sets up Resend email provider.

func WithResendEmail

func WithResendEmail(apiKey, fromEmail, fromName string) Option

WithResendEmail configures the Resend email provider.

func WithRolePermissions

func WithRolePermissions(rp map[Role][]Permission) Option

WithRolePermissions sets custom role-permission mappings.

func WithRotateRefreshTokens

func WithRotateRefreshTokens(enabled bool) Option

WithRotateRefreshTokens enables refresh token rotation.

func WithSMTP

func WithSMTP(cfg smtpmailer.Config) Option

WithSMTP sets up SMTP email provider.

func WithSMTPEmail

func WithSMTPEmail(cfg smtp.Config) Option

WithSMTPEmail configures SMTP email provider.

func WithSQLiteStore

func WithSQLiteStore(usersDB, auditDB interface{}) Option

WithSQLiteStore is deprecated. Use stores/sqlite.WithDatabase instead.

func WithSecrets

func WithSecrets(secrets Secrets) Option

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

func WithSecretsFromEnvFile(path string) Option

WithSecretsFromEnvFile loads secrets from a .env file.

func WithSecretsFromEnvFileWithPrefix

func WithSecretsFromEnvFileWithPrefix(path, prefix string) Option

WithSecretsFromEnvFileWithPrefix loads secrets from a .env file with a custom prefix.

func WithSecretsFromFiles

func WithSecretsFromFiles(jwtPath, encPath, pepperPath string) Option

WithSecretsFromFiles loads secrets from three files (one per secret).

func WithSecretsFromJSONFile

func WithSecretsFromJSONFile(path string, keys map[string]string) Option

WithSecretsFromJSONFile loads secrets from a JSON file.

func WithSecretsFromRawFile

func WithSecretsFromRawFile(path string) Option

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

func WithSendGrid(apiKey, fromEmail, fromName string) Option

WithSendGrid sets up SendGrid email provider.

func WithSendGridEmail

func WithSendGridEmail(apiKey, fromEmail, fromName string) Option

WithSendGridEmail configures SendGrid email provider.

func WithStore

func WithStore(store Store) Option

WithStore sets a custom store implementation.

func WithTOTP

func WithTOTP(enabled bool) Option

WithTOTP enables/disables 2FA.

func WithTOTPAccountName

func WithTOTPAccountName(name string) Option

WithTOTPAccountName sets a fixed account name for TOTP entries.

func WithTOTPDigits

func WithTOTPDigits(digits int) Option

WithTOTPDigits sets the number of digits for TOTP (6 or 8).

func WithTOTPQRCode

func WithTOTPQRCode(enabled bool) Option

WithTOTPQRCode enables or disables QR code generation in setup responses.

func WithTOTPQRCodeSize

func WithTOTPQRCodeSize(size int) Option

WithTOTPQRCodeSize sets the QR code size in pixels.

func WithTOTPUseUsername

func WithTOTPUseUsername(enabled bool) Option

WithTOTPUseUsername uses the username (when present) for TOTP account name.

func WithTokenBlacklist

func WithTokenBlacklist(bl TokenBlacklist) Option

WithTokenBlacklist enables immediate token revocation.

func WithTokenTTL

func WithTokenTTL(access, refresh time.Duration) Option

WithTokenTTL sets token lifetimes.

func WithTrustProxyHeaders

func WithTrustProxyHeaders(enabled bool) Option

WithTrustProxyHeaders enables or disables proxy header parsing.

func WithTrustedProxies

func WithTrustedProxies(proxies []string) Option

WithTrustedProxies enables trusted proxy parsing for client IPs.

func WithTurnstile

func WithTurnstile(secret string) Option

WithTurnstile adds Cloudflare Turnstile CAPTCHA.

func WithTwitch

func WithTwitch(clientID, clientSecret string) Option

WithTwitch adds Twitch OAuth provider.

func WithUnverifiedAccountTTL

func WithUnverifiedAccountTTL(ttl time.Duration) Option

WithUnverifiedAccountTTL sets how long unverified accounts can remain.

func WithUserAgentHashInLogs

func WithUserAgentHashInLogs(enabled bool) Option

WithUserAgentHashInLogs toggles user-agent hashing in audit logs.

func WithUsername

func WithUsername(enabled bool) Option

WithUsername enables/disables username support.

func WithUsernameAllowNumericOnly

func WithUsernameAllowNumericOnly(allowed bool) Option

WithUsernameAllowNumericOnly allows usernames that are only digits.

func WithUsernamePattern

func WithUsernamePattern(pattern string) Option

WithUsernamePattern enforces a regex pattern for usernames.

func WithUsernamePolicy

func WithUsernamePolicy(minLength, maxLength int) Option

WithUsernamePolicy configures username length rules.

func WithUsernameRequired

func WithUsernameRequired(required bool) Option

WithUsernameRequired enforces username on registration.

func WithUsernameReserved

func WithUsernameReserved(reserved []string) Option

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

type PasswordChangeMailer interface {
	SendPasswordChanged(ctx context.Context, to string) error
}

PasswordChangeMailer sends password change notifications.

type PasswordHistory

type PasswordHistory struct {
	Hash []byte
	Salt []byte
}

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

func (*ReCaptchaProvider) Verify

func (r *ReCaptchaProvider) Verify(ctx context.Context, token, ip string) (bool, error)

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) Add

func (b *RedisBlacklist) Add(ctx context.Context, jti string, expiresAt time.Time) error

func (*RedisBlacklist) Cleanup

func (b *RedisBlacklist) Cleanup()

func (*RedisBlacklist) IsBlacklisted

func (b *RedisBlacklist) IsBlacklisted(ctx context.Context, jti string) (bool, error)

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.

func (*RequestDeduplicator) Do

func (d *RequestDeduplicator) Do(key string, fn func() (any, error)) (any, error, bool)

Do executes a function only if no identical request is pending. Identical requests share the result.

type RequestTracker

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

RequestTracker tracks in-flight requests for graceful shutdown.

type ResourceChecker

type ResourceChecker func(ctx context.Context, user *User, resourceID string) bool

ResourceChecker is called to verify access to a specific resource.

type Role

type Role string

Role represents a user role.

const (
	RoleUser      Role = "user"
	RoleAdmin     Role = "admin"
	RoleModerator Role = "moderator"
	RoleService   Role = "service" // For service-to-service auth
)

type SDKToken

type SDKToken struct {
	UserID    string
	DeviceID  string
	Scopes    []string
	ExpiresAt time.Time
}

SDKToken is a long-lived token for SDK/mobile use.

type Scope

type Scope string

Scope represents an OAuth/API scope.

const (
	ScopeRead    Scope = "read"
	ScopeWrite   Scope = "write"
	ScopeProfile Scope = "profile"
	ScopeEmail   Scope = "email"
	ScopeOffline Scope = "offline_access" // For refresh tokens
	ScopeOpenID  Scope = "openid"
)

Common scopes

type Secrets

type Secrets struct {
	JWTSecret     []byte
	EncryptionKey []byte
	Pepper        []byte
}

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

func SecretsFromEnv() (Secrets, error)

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

func SecretsFromEnvFile(path string) (Secrets, error)

SecretsFromEnvFile loads secrets from a .env style file.

func SecretsFromEnvFileWithPrefix

func SecretsFromEnvFileWithPrefix(path, prefix string) (Secrets, error)

SecretsFromEnvFileWithPrefix loads secrets from a .env file with a custom prefix.

func SecretsFromEnvWithPrefix

func SecretsFromEnvWithPrefix(prefix string) (Secrets, error)

SecretsFromEnvWithPrefix loads secrets with a custom prefix. Example: SecretsFromEnvWithPrefix("MYAPP") reads MYAPP_JWT_SECRET, etc.

func SecretsFromFiles

func SecretsFromFiles(jwtPath, encPath, pepperPath string) (Secrets, error)

SecretsFromFiles loads secrets from three plain files (one per secret).

func SecretsFromJSON

func SecretsFromJSON(payload []byte, keys map[string]string) (Secrets, error)

SecretsFromJSON loads secrets from a JSON payload.

func SecretsFromJSONFile

func SecretsFromJSONFile(path string, keys map[string]string) (Secrets, error)

SecretsFromJSONFile loads secrets from a JSON file.

func SecretsFromRawFile

func SecretsFromRawFile(path string) (Secrets, error)

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.

func SecretsFromVaultEnv

func SecretsFromVaultEnv(ctx context.Context) (Secrets, error)

SecretsFromVaultEnv loads Vault config from environment and fetches secrets. Uses: VAULT_ADDR, VAULT_TOKEN, VAULT_SECRET_PATH

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.

func (*SlidingWindowRateLimiter) Allow

func (r *SlidingWindowRateLimiter) Allow(ctx context.Context, key string, limit int, window time.Duration) (bool, int, error)

Allow checks if a request is allowed and records it.

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.

func GetTenantFromContext

func GetTenantFromContext(ctx context.Context) (*Tenant, bool)

GetTenantFromContext retrieves the current tenant from context.

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

func (*TurnstileProvider) Verify

func (t *TurnstileProvider) Verify(ctx context.Context, token, ip string) (bool, error)

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) GetUser

func (p *TwitchProvider) GetUser(ctx context.Context, accessToken string) (*OAuthUser, error)

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.

func GetUserFromContext

func GetUserFromContext(ctx context.Context) (*User, bool)

GetUserFromContext retrieves the authenticated user from the request context.

type UserDeleter

type UserDeleter interface {
	DeleteUser(ctx context.Context, userID string) error
}

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.

type WelcomeMailer

type WelcomeMailer interface {
	SendWelcome(ctx context.Context, to, name string) error
}

WelcomeMailer sends welcome emails.

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.

Jump to

Keyboard shortcuts

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