domain

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2025 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultBasePath              = "/api/auth"
	DefaultSessionExpiresIn      = 604800 // 7 days
	DefaultSessionUpdateAge      = 86400  // 1 day
	DefaultMinPasswordLength     = 8
	DefaultMaxPasswordLength     = 128
	DefaultVerificationExpiresIn = 1 * time.Hour
	DefaultResetPasswordExpiry   = 1 * time.Hour
	DefaultRateLimitWindow       = 10
	DefaultRateLimitMax          = 100
	DefaultCookieCacheMaxAge     = 300 // 5 minutes
	DefaultFindManyLimit         = 100
	DefaultSecret                = "go-better-auth-secret-0123456789"
)

Default configuration values

Variables

View Source
var (
	ErrInvalidCredentials = &AuthError{
		Code:    "invalid_credentials",
		Message: "Invalid email or password",
		Status:  401,
	}
	ErrUserNotFound = &AuthError{
		Code:    "user_not_found",
		Message: "User not found",
		Status:  404,
	}
	ErrUserAlreadyExists = &AuthError{
		Code:    "user_already_exists",
		Message: "A user with this email already exists",
		Status:  409,
	}
	ErrInvalidToken = &AuthError{
		Code:    "invalid_token",
		Message: "Invalid or expired token",
		Status:  401,
	}
	ErrSessionExpired = &AuthError{
		Code:    "session_expired",
		Message: "Session has expired",
		Status:  401,
	}
	ErrSessionNotFound = &AuthError{
		Code:    "session_not_found",
		Message: "Session not found",
		Status:  401,
	}
	ErrEmailNotVerified = &AuthError{
		Code:    "email_not_verified",
		Message: "Email address not verified",
		Status:  403,
	}
	ErrInvalidRequest = &AuthError{
		Code:    "invalid_request",
		Message: "Invalid request parameters",
		Status:  400,
	}
	ErrNotFound = &AuthError{
		Code:    "not_found",
		Message: "Resource not found",
		Status:  404,
	}
	ErrAccountLocked = &AuthError{
		Code:    "account_locked",
		Message: "Account is temporarily locked due to too many failed login attempts",
		Status:  429,
	}
)

Common error codes

Functions

This section is empty.

Types

type AccountConfig

type AccountConfig struct {
	// ModelName is the model name for the account
	ModelName string

	// Fields maps field names to different column names
	Fields map[string]string

	// EncryptOAuthTokens encrypts OAuth tokens before storing them (default: false)
	EncryptOAuthTokens bool

	// UpdateAccountOnSignIn updates account data on sign in with latest data from provider
	UpdateAccountOnSignIn bool

	// AccountLinking configuration
	AccountLinking *AccountLinkingConfig
}

AccountConfig holds account configuration options

type AccountLinkingConfig

type AccountLinkingConfig struct {
	// Enabled enables account linking (default: false)
	Enabled bool

	// TrustedProviders is a list of trusted providers
	TrustedProviders []string

	// AllowDifferentEmails allows users to link accounts with different email addresses
	AllowDifferentEmails bool

	// AllowUnlinkingAll allows users to unlink all accounts
	AllowUnlinkingAll bool
}

AccountLinkingConfig holds account linking configuration

type AdditionalField

type AdditionalField struct {
	Type string
}

AdditionalField defines an additional field for a model

type AdvancedConfig

type AdvancedConfig struct {
	// IPAddress configuration for rate limiting and session tracking
	IPAddress *IPAddressConfig

	// UseSecureCookies uses secure cookies (default: false)
	UseSecureCookies bool

	// DisableCSRFCheck disables trusted origins check (⚠️ security risk)
	DisableCSRFCheck bool

	// CrossSubDomainCookies configures cookies to be shared across subdomains
	CrossSubDomainCookies *CrossSubDomainCookiesConfig

	// Cookies allows customizing cookie names and attributes
	Cookies map[string]CookieConfig

	// DefaultCookieAttributes sets default attributes for all cookies
	DefaultCookieAttributes *CookieAttributes

	// CookiePrefix is a prefix for all cookies
	CookiePrefix string

	// Database holds advanced database configuration
	Database *DatabaseAdvancedConfig
}

AdvancedConfig holds advanced configuration options

type AuthError

type AuthError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Status  int    `json:"status"`
}

AuthError represents an authentication error

func (*AuthError) Error

func (e *AuthError) Error() string

type CRUDHooks

type CRUDHooks struct {
	Before func(ctx context.Context, data interface{}) (interface{}, error)
	After  func(ctx context.Context, result interface{}) error
}

CRUDHooks holds before/after hooks for CRUD operations

type ChangeEmailConfig

type ChangeEmailConfig struct {
	// Enabled enables the change email feature (default: false)
	Enabled bool

	// SendChangeEmailVerification is a function to send change email verification
	SendChangeEmailVerification func(ctx context.Context, user *user.User, newEmail string, url string, token string) error
}

ChangeEmailConfig holds change email configuration

type Config

type Config struct {
	// AppName is the name of the application
	AppName string

	// BaseURL is the base URL for Better Auth (e.g., "https://example.com")
	// If not set, will check GO_BETTER_AUTH_URL environment variable
	BaseURL string

	// BasePath is the base path for Better Auth routes (default: "/api/auth")
	// Will be overridden if there is a path component within BaseURL
	BasePath string

	// TrustedOrigins is a list of trusted origins for CORS
	// Supports static origins, dynamic origins via function, and wildcard patterns
	TrustedOrigins TrustedOriginsConfig

	// Secret is used for encryption, signing, and hashing
	// If not set, will check GO_BETTER_AUTH_SECRET or AUTH_SECRET environment variables
	// In production, if not set, will throw an error
	Secret string

	// Database configuration
	Database DatabaseConfig

	// Secondary Storage
	SecondaryStorage storage.SecondaryStorage

	// EmailAndPassword authentication configuration
	EmailAndPassword *EmailPasswordConfig

	// EmailVerification configuration
	EmailVerification *EmailVerificationConfig

	// SocialProviders configuration
	SocialProviders *SocialProvidersConfig

	// Plugins is a list of Better Auth plugins
	Plugins []Plugin

	// User configuration options
	User *UserConfig

	// Session configuration options
	Session *SessionConfig

	// Account configuration options
	Account *AccountConfig

	// Verification configuration options
	Verification *VerificationConfig

	// RateLimit configuration
	RateLimit *RateLimitOptions

	// BruteForce configuration
	BruteForce *security.BruteForceConfig

	// Advanced configuration options
	Advanced *AdvancedConfig

	// Logger configuration
	Logger *LoggerConfig

	// DatabaseHooks for lifecycle events
	DatabaseHooks *DatabaseHooksConfig

	// OnAPIError configuration
	OnAPIError *OnAPIErrorConfig

	// Hooks for request lifecycle
	Hooks *HooksConfig

	// DisabledPaths is a list of paths to disable
	DisabledPaths []string
}

Config is the main configuration struct for Go Better Auth

func (*Config) ApplyDefaults

func (c *Config) ApplyDefaults()

ApplyDefaults applies default values to a Config

func (*Config) IsTrustedOrigin

func (c *Config) IsTrustedOrigin(origin string) bool

IsTrustedOrigin checks if an origin is trusted, supporting wildcard patterns

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration

type ConfigValidationResult

type ConfigValidationResult struct {
	Valid  bool
	Errors []ValidationError
}

ConfigValidationResult holds validation results

func ValidateConfig

func ValidateConfig(config *Config) *ConfigValidationResult

ValidateConfig validates the entire configuration

func (*ConfigValidationResult) AddError

func (r *ConfigValidationResult) AddError(field, message string)

AddError adds a validation error

func (*ConfigValidationResult) Error

func (r *ConfigValidationResult) Error() string

Error returns the error message for all validation errors

type CookieAttributes

type CookieAttributes struct {
	HTTPOnly bool
	Secure   bool
	SameSite string
	Path     string
	Domain   string
	MaxAge   int
}

CookieAttributes holds cookie attributes

type CookieCacheConfig

type CookieCacheConfig struct {
	// Enabled enables caching session in cookie (default: false)
	Enabled bool

	// MaxAge is the cache duration in seconds (default: 300 - 5 minutes)
	MaxAge int
}

CookieCacheConfig holds cookie cache configuration

type CookieConfig

type CookieConfig struct {
	Name       string
	Attributes CookieAttributes
}

CookieConfig holds cookie configuration

type CrossSubDomainCookiesConfig

type CrossSubDomainCookiesConfig struct {
	// Enabled enables cross subdomain cookies
	Enabled bool

	// AdditionalCookies is a list of additional cookies to share across subdomains
	AdditionalCookies []string

	// Domain is the domain for the cookies
	Domain string
}

CrossSubDomainCookiesConfig holds cross subdomain cookie configuration

type DatabaseAdvancedConfig

type DatabaseAdvancedConfig struct {
	// UseNumberId uses auto-incrementing IDs instead of UUIDs
	UseNumberId bool

	// GenerateId is a custom ID generator function, or false to disable ID generation
	GenerateId interface{} // func(model string, size int) string or false

	// DefaultFindManyLimit is the default limit for findMany queries
	DefaultFindManyLimit int
}

DatabaseAdvancedConfig holds advanced database configuration

type DatabaseConfig

type DatabaseConfig struct {
	// Provider is the database option ("sqlite", "postgres")
	Provider string

	// ConnectionString is the database connection string
	ConnectionString string

	// LogQueries enables SQL query logging for debugging (default: false)
	LogQueries bool

	// MaxOpenConns sets the maximum number of open connections to the database (default: 25)
	MaxOpenConns int

	// MaxIdleConns sets the maximum number of idle connections (default: 5)
	MaxIdleConns int

	// ConnMaxLifetime sets the maximum amount of time a connection may be reused in seconds (default: 3600)
	ConnMaxLifetime int
}

DatabaseConfig holds database configuration

type DatabaseHooksConfig

type DatabaseHooksConfig struct {
	User         *ModelHooks
	Session      *ModelHooks
	Account      *ModelHooks
	Verification *ModelHooks
}

DatabaseHooksConfig holds database lifecycle hooks

type DeleteUserConfig

type DeleteUserConfig struct {
	// Enabled enables the delete user feature (default: false)
	Enabled bool

	// SendDeleteAccountVerification is a function to send delete account verification
	SendDeleteAccountVerification func(ctx context.Context, user *user.User, url string, token string) error

	// BeforeDelete is called before user deletion
	BeforeDelete func(ctx context.Context, user *user.User) error

	// AfterDelete is called after user deletion
	AfterDelete func(ctx context.Context, user *user.User) error
}

DeleteUserConfig holds user deletion configuration

type DiscordProviderConfig

type DiscordProviderConfig struct {
	ClientID     string
	ClientSecret string
	RedirectURI  string
}

DiscordProviderConfig holds Discord OAuth configuration

type EmailPasswordConfig

type EmailPasswordConfig struct {
	// Enabled enables email and password authentication (default: false)
	Enabled bool

	// DisableSignUp disables email and password sign up (default: false)
	DisableSignUp bool

	// RequireEmailVerification requires email verification before session creation
	RequireEmailVerification bool

	// MinPasswordLength is the minimum password length (default: 8)
	MinPasswordLength int

	// MaxPasswordLength is the maximum password length (default: 128)
	MaxPasswordLength int

	// AutoSignIn automatically signs in the user after sign up
	AutoSignIn bool

	// SendResetPassword is a function to send reset password emails
	SendResetPassword func(ctx context.Context, user *user.User, url string, token string) error

	// ResetPasswordTokenExpiresIn is the duration the reset token is valid for (default: 1 hour)
	ResetPasswordTokenExpiresIn time.Duration

	// Password holds custom password hashing and verification functions
	Password *PasswordConfig
}

EmailPasswordConfig holds email/password auth configuration

type EmailVerificationConfig

type EmailVerificationConfig struct {
	// Enabled enables email verification feature (default: false)
	Enabled bool

	// SendVerificationEmail is a function to send verification emails
	SendVerificationEmail func(ctx context.Context, user *user.User, url string, token string) error

	// SendOnSignUp automatically sends verification email after sign up (default: false)
	SendOnSignUp bool

	// SendOnSignIn sends verification email on sign in when user's email is not verified (default: false)
	SendOnSignIn bool

	// AutoSignInAfterVerification automatically signs in the user after email verification
	AutoSignInAfterVerification bool

	// ExpiresIn is the duration the verification token is valid for (default: 1 hour)
	ExpiresIn time.Duration
}

EmailVerificationConfig holds email verification configuration

type GitHubProviderConfig

type GitHubProviderConfig struct {
	ClientID     string
	ClientSecret string
	RedirectURI  string
}

GitHubProviderConfig holds GitHub OAuth configuration

type GoogleProviderConfig

type GoogleProviderConfig struct {
	ClientID     string
	ClientSecret string
	RedirectURI  string
}

GoogleProviderConfig holds Google OAuth configuration

type HookResponse

type HookResponse struct {
	// Context contains the modified context to be merged with the original
	Context *RequestContext
}

HookResponse is returned by hook functions to modify the request context. If the hook returns nil, the original context is used.

type HooksConfig

type HooksConfig struct {
	// Before is executed before processing the request.
	// It receives the request context and can return a modified context.
	// If it returns an error, the request is blocked.
	Before func(ctx *RequestContext) (*HookResponse, error)

	// After is executed after processing the request.
	// It receives the request context and can return a modified context.
	// Errors are silently handled to avoid disrupting responses.
	After func(ctx *RequestContext) (*HookResponse, error)
}

HooksConfig holds request lifecycle hooks

type IPAddressConfig

type IPAddressConfig struct {
	// IPAddressHeaders is a list of headers to check for IP address
	IPAddressHeaders []string

	// DisableIpTracking disables IP tracking
	DisableIpTracking bool
}

IPAddressConfig holds IP address configuration

type LogLevel

type LogLevel string

LogLevel defines the log level

const (
	LogLevelInfo  LogLevel = "info"
	LogLevelWarn  LogLevel = "warn"
	LogLevelError LogLevel = "error"
	LogLevelDebug LogLevel = "debug"
)

type LoggerConfig

type LoggerConfig struct {
	// Disabled disables all logging (default: false)
	Disabled bool

	// DisableColors disables colors in the default logger (default: auto-detected)
	DisableColors bool

	// Level is the minimum log level to display
	Level LogLevel

	// Log is a custom logging function
	Log func(level LogLevel, message string, args ...any)
}

LoggerConfig holds logger configuration

type MigrationInfo

type MigrationInfo struct {
	CurrentVersion uint `json:"current_version"`
	Dirty          bool `json:"dirty"`
}

MigrationInfo represents migration status information

type MigrationService

type MigrationService interface {
	// Up runs all pending migrations
	Up(ctx context.Context) error

	// Down runs one migration down
	Down(ctx context.Context) error

	// Steps runs n migrations up (positive) or down (negative)
	Steps(ctx context.Context, n int) error

	// Version returns the current migration version and dirty state
	Version(ctx context.Context) (uint, bool, error)

	// Force sets the migration version without running migrations
	Force(ctx context.Context, version int) error

	// Drop drops all tables and schema
	Drop(ctx context.Context) error

	// GetMigrationInfo returns information about migration status
	GetMigrationInfo(ctx context.Context) (*MigrationInfo, error)

	// Close closes the migration instance
	Close() error
}

MigrationService defines the interface for database migration operations

type ModelHooks

type ModelHooks struct {
	Create *CRUDHooks
	Update *CRUDHooks
}

ModelHooks holds before/after hooks for a model

type OnAPIErrorConfig

type OnAPIErrorConfig struct {
	// Throw throws an error on API error (default: false)
	Throw bool

	// OnError is a custom error handler
	OnError func(err error, ctx context.Context)

	// ErrorURL is the URL to redirect to on error (default: "/api/auth/error")
	ErrorURL string
}

OnAPIErrorConfig holds API error handling configuration

type PasswordConfig

type PasswordConfig struct {
	// Hash is a custom password hashing function
	Hash func(password string) (string, error)

	// Verify is a custom password verification function
	Verify func(password, hash string) bool
}

PasswordConfig holds custom password hashing and verification

type Plugin

type Plugin interface {
	Name() string
	Initialize(config any) error
}

Plugin defines the interface for Go Better Auth plugins

type RateLimitOptions

type RateLimitOptions struct {
	// Enabled enables rate limiting (defaults: true in production, false in development)
	Enabled bool

	// Window is the time window in seconds (default: 10)
	Window int

	// Max is the maximum number of requests allowed within the window (default: 100)
	Max int

	// Algorithm specifies the rate limiting algorithm to use
	// Options: "fixed-window" (default), "sliding-window"
	// Fixed window: Simple counter that resets at window boundaries
	// Sliding window: Weighted counter using current and previous window for smoother limiting
	Algorithm string

	// CustomRules defines custom rate limit rules for specific paths
	CustomRules map[string]RateLimitRule

	// Storage defines the storage type ("memory", "database", "secondary-storage")
	Storage string

	// ModelName is the name of the table for rate limiting if database is used (default: "rateLimit")
	ModelName string
}

RateLimitOptions holds rate limiting configuration options

type RateLimitRule

type RateLimitRule struct {
	Window int
	Max    int
}

RateLimitRule defines a custom rate limit rule

type RedisConfig

type RedisConfig struct {
	// Host is the Redis server host (default: "localhost")
	Host string

	// Port is the Redis server port (default: 6379)
	Port int

	// DB is the Redis database number (default: 0)
	DB int

	// Password is the Redis password (optional)
	Password string

	// TLS enables TLS connection to Redis (default: false)
	TLS bool

	// MaxRetries is the maximum number of retries (default: 3)
	MaxRetries int

	// PoolSize is the connection pool size (default: 10)
	PoolSize int
}

RedisConfig holds Redis configuration for secondary storage

type RequestContext

type RequestContext struct {
	// Path is the URL path of the request (e.g., "/auth/signin")
	Path string
	// Method is the HTTP method of the request (GET, POST, etc.)
	Method string
	// Body contains the parsed request body (for POST/PUT requests)
	Body any
	// Headers contains the request headers
	Headers map[string][]string
	// Query contains query parameters from the URL
	Query map[string][]string
	// Request is the underlying *http.Request object
	Request *http.Request
	// Context contains auth-related context like session, config, etc.
	Context map[string]any
}

RequestContext holds request context information passed to hooks. Users can read all properties to understand the request and optionally modify fields by returning a new context object from hook functions.

type SessionConfig

type SessionConfig struct {
	// ModelName is the model name for the session (default: "session")
	ModelName string

	// Fields maps field names to different column names
	Fields map[string]string

	// ExpiresIn is the expiration time for the session token in seconds (default: 604800 - 7 days)
	ExpiresIn time.Duration

	// UpdateAge is how often the session should be refreshed in seconds (default: 86400 - 1 day)
	UpdateAge time.Duration

	// DisableSessionRefresh disables session refresh (default: false)
	DisableSessionRefresh bool

	// AdditionalFields defines additional fields for the session table
	AdditionalFields map[string]AdditionalField

	// StoreSessionInDatabase stores session in database when secondary storage is provided (default: false)
	StoreSessionInDatabase bool

	// PreserveSessionInDatabase preserves session records in database when deleted from secondary storage (default: false)
	PreserveSessionInDatabase bool

	// CookieCache enables caching session in cookie
	CookieCache *CookieCacheConfig
}

SessionConfig holds session configuration

type SocialProvidersConfig

type SocialProvidersConfig struct {
	Google  *GoogleProviderConfig
	GitHub  *GitHubProviderConfig
	Discord *DiscordProviderConfig
}

SocialProvidersConfig holds social provider configuration

type TrustedOriginsConfig

type TrustedOriginsConfig struct {
	// StaticOrigins is a static list of trusted origins
	StaticOrigins []string

	// DynamicOrigins is a function that returns origins dynamically based on the request
	DynamicOrigins func(r *http.Request) []string
}

TrustedOriginsConfig can be a static list, dynamic function, or support wildcards

func (*TrustedOriginsConfig) IsOriginTrusted

func (c *TrustedOriginsConfig) IsOriginTrusted(origin string, r *http.Request) bool

IsOriginTrusted checks if the given origin is trusted. It supports static origins, dynamic origins via callback, and wildcard patterns. Returns true if the origin is trusted, false otherwise.

type UserConfig

type UserConfig struct {
	// ModelName is the model name for the user (default: "user")
	ModelName string

	// Fields maps field names to different column names
	Fields map[string]string

	// AdditionalFields defines additional fields for the user table
	AdditionalFields map[string]AdditionalField

	// ChangeEmail configuration
	ChangeEmail *ChangeEmailConfig

	// DeleteUser configuration
	DeleteUser *DeleteUserConfig
}

UserConfig holds user configuration options

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a configuration validation error

type VerificationConfig

type VerificationConfig struct {
	// ModelName is the model name for the verification table
	ModelName string

	// Fields maps field names to different column names
	Fields map[string]string

	// DisableCleanup disables cleaning up expired values when a verification value is fetched
	DisableCleanup bool
}

VerificationConfig holds verification configuration options

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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