models

package
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EventUserSignedUp    = "user.signed_up"
	EventUserLoggedIn    = "user.logged_in"
	EventEmailVerified   = "user.email_verified"
	EventPasswordChanged = "user.password_changed"
	EventEmailChanged    = "user.email_changed"
)

Built-in event types for the authentication system

View Source
const (
	RateLimitAlgorithmFixedWindow = "fixed_window"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Account

type Account struct {
	ID                    string       `json:"id" gorm:"primaryKey"`
	UserID                string       `json:"user_id" gorm:"index"`
	AccountID             string       `json:"account_id"`
	ProviderID            ProviderType `json:"provider_id"`
	AccessToken           *string      `json:"access_token,omitempty"`
	RefreshToken          *string      `json:"refresh_token,omitempty"`
	IDToken               *string      `json:"id_token,omitempty"`
	AccessTokenExpiresAt  *time.Time   `json:"access_token_expires_at,omitempty"`
	RefreshTokenExpiresAt *time.Time   `json:"refresh_token_expires_at,omitempty"`
	Scope                 *string      `json:"scope,omitempty"`
	Password              *string      `json:"password,omitempty"` // for email/password auth
	CreatedAt             time.Time    `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt             time.Time    `json:"updated_at" gorm:"autoUpdateTime"`
	User                  User         `gorm:"foreignKey:UserID"`
}

type AccountDatabaseHooksConfig

type AccountDatabaseHooksConfig struct {
	BeforeCreate func(account *Account) error
	AfterCreate  func(account Account) error
	BeforeUpdate func(account *Account) error
	AfterUpdate  func(account Account) error
}

type AccountService

type AccountService interface {
	CreateAccount(account *Account) error
	GetAccountByUserID(userID string) (*Account, error)
	GetAccountByProviderAndAccountID(provider ProviderType, accountID string) (*Account, error)
	UpdateAccount(account *Account) error
}

type ApiMiddleware added in v1.4.0

type ApiMiddleware struct {
	AdminAuth     func() func(http.Handler) http.Handler
	Auth          func() func(http.Handler) http.Handler
	OptionalAuth  func() func(http.Handler) http.Handler
	CorsAuth      func() func(http.Handler) http.Handler
	CSRF          func() func(http.Handler) http.Handler
	RateLimit     func() func(http.Handler) http.Handler
	EndpointHooks func() func(http.Handler) http.Handler
}

type AuthApi added in v1.4.0

type AuthApi interface {
	Services() *AuthServices
	SignUpWithEmailAndPassword(ctx context.Context, name string, email string, password string, callbackURL *string) (*SignUpResult, error)
	SignInWithEmailAndPassword(ctx context.Context, email string, password string, callbackURL *string) (*SignInResult, error)
	SignOut(ctx context.Context, sessionToken string) error
	VerifyEmail(ctx context.Context, rawToken string) (*VerifyEmailResult, error)
	SendEmailVerification(ctx context.Context, userID string, callbackURL *string) error
	ResetPassword(ctx context.Context, email string, callbackURL *string) error
	ChangePassword(ctx context.Context, rawToken string, newPassword string) error
	EmailChange(ctx context.Context, userID string, newEmail string, callbackURL *string) error
	GetMe(ctx context.Context, userID string) (*MeResult, error)
	PrepareOAuth2Login(ctx context.Context, providerName string) (*OAuth2LoginResult, error)
	SignInWithOAuth2(ctx context.Context, providerName string, code string, state string, verifier *string) (*SignInResult, error)
}

AuthApi defines the interface for the authentication API

type AuthServices added in v1.4.0

type AuthServices struct {
	Users         UserService
	Accounts      AccountService
	Sessions      SessionService
	Verifications VerificationService
	Passwords     PasswordService
	Tokens        TokenService
	RateLimits    RateLimitService
	Mailers       MailerService
}

AuthServices groups all service interfaces related to authentication

type AuthSettings added in v1.4.0

type AuthSettings struct {
	// The unique key for the config block (e.g., "runtime_config" for the main config)
	Key string `gorm:"primaryKey;type:varchar(255)" json:"key"`
	// Value contains the JSON-encoded configuration data
	Value json.RawMessage `gorm:"type:jsonb" json:"value"`
	// CreatedAt is the timestamp when this setting was created
	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
	// UpdatedAt is the timestamp when this setting was last updated
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}

AuthSettings stores dynamic configuration for the auth system in the database. This is used primarily in database mode to persist the full runtime configuration.

func (AuthSettings) TableName added in v1.4.0

func (AuthSettings) TableName() string

TableName specifies the table name for the AuthSettings model

type BasePlugin added in v1.3.4

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

func (*BasePlugin) Close added in v1.3.4

func (p *BasePlugin) Close() error

func (*BasePlugin) Config added in v1.3.4

func (p *BasePlugin) Config() PluginConfig

func (*BasePlugin) Ctx added in v1.3.4

func (p *BasePlugin) Ctx() *PluginContext

func (*BasePlugin) DatabaseHooks added in v1.3.4

func (p *BasePlugin) DatabaseHooks() any

func (*BasePlugin) EndpointHooks added in v1.4.0

func (p *BasePlugin) EndpointHooks() any

func (*BasePlugin) EventHooks added in v1.3.4

func (p *BasePlugin) EventHooks() any

func (*BasePlugin) Init added in v1.3.4

func (p *BasePlugin) Init(ctx *PluginContext) error

func (*BasePlugin) Metadata added in v1.3.4

func (p *BasePlugin) Metadata() PluginMetadata

func (*BasePlugin) Migrations added in v1.3.4

func (p *BasePlugin) Migrations() []any

func (*BasePlugin) RateLimit added in v1.3.4

func (p *BasePlugin) RateLimit() *PluginRateLimit

func (*BasePlugin) Routes added in v1.3.4

func (p *BasePlugin) Routes() []PluginRoute

func (*BasePlugin) SetClose added in v1.3.4

func (p *BasePlugin) SetClose(fn func() error)

func (*BasePlugin) SetConfig added in v1.3.4

func (p *BasePlugin) SetConfig(config PluginConfig)

func (*BasePlugin) SetCtx added in v1.3.4

func (p *BasePlugin) SetCtx(ctx *PluginContext)

func (*BasePlugin) SetDatabaseHooks added in v1.3.4

func (p *BasePlugin) SetDatabaseHooks(hooks any)

func (*BasePlugin) SetEndpointHooks added in v1.4.0

func (p *BasePlugin) SetEndpointHooks(hooks any)

func (*BasePlugin) SetEventHooks added in v1.3.4

func (p *BasePlugin) SetEventHooks(hooks any)

func (*BasePlugin) SetInit added in v1.3.4

func (p *BasePlugin) SetInit(fn func(ctx *PluginContext) error)

func (*BasePlugin) SetMetadata added in v1.3.4

func (p *BasePlugin) SetMetadata(meta PluginMetadata)

func (*BasePlugin) SetMigrations added in v1.3.4

func (p *BasePlugin) SetMigrations(migrations []any)

func (*BasePlugin) SetRateLimit added in v1.3.4

func (p *BasePlugin) SetRateLimit(rateLimit *PluginRateLimit)

func (*BasePlugin) SetRoutes added in v1.3.4

func (p *BasePlugin) SetRoutes(routes []PluginRoute)

func (*BasePlugin) SetWebhooks added in v1.4.0

func (p *BasePlugin) SetWebhooks(hooks any)

func (*BasePlugin) Webhooks added in v1.4.0

func (p *BasePlugin) Webhooks() any

type CSRFConfig

type CSRFConfig struct {
	Enabled    bool          `json:"enabled" toml:"enabled"`
	CookieName string        `json:"cookie_name" toml:"cookie_name"`
	HeaderName string        `json:"header_name" toml:"header_name"`
	ExpiresIn  time.Duration `json:"expires_in" toml:"expires_in"`
}

type ChangeEmailConfig

type ChangeEmailConfig struct {
	Enabled bool `json:"enabled" toml:"enabled"`
	// Library mode only
	SendEmailChangeVerificationEmail func(user User, newEmail string, url string, token string) error `json:"-" toml:"-"`
}

type Config

type Config struct {
	Mode              Mode                    `json:"-" toml:"-"`
	AppName           string                  `json:"app_name" toml:"app_name"`
	BaseURL           string                  `json:"base_url" toml:"base_url"`
	BasePath          string                  `json:"base_path" toml:"base_path"`
	Secret            string                  `json:"secret" toml:"secret"`
	Logger            LoggerConfig            `json:"logger" toml:"logger"`
	DB                *gorm.DB                `json:"-" toml:"-"`
	Database          DatabaseConfig          `json:"database" toml:"database"`
	Email             EmailConfig             `json:"email" toml:"email"`
	SecondaryStorage  SecondaryStorageConfig  `json:"secondary_storage" toml:"secondary_storage"`
	EmailPassword     EmailPasswordConfig     `json:"email_password" toml:"email_password"`
	EmailVerification EmailVerificationConfig `json:"email_verification" toml:"email_verification"`
	User              UserConfig              `json:"user" toml:"user"`
	Session           SessionConfig           `json:"session" toml:"session"`
	CSRF              CSRFConfig              `json:"csrf" toml:"csrf"`
	SocialProviders   SocialProvidersConfig   `json:"social_providers" toml:"social_providers"`
	TrustedOrigins    TrustedOriginsConfig    `json:"trusted_origins" toml:"trusted_origins"`
	RateLimit         RateLimitConfig         `json:"rate_limit" toml:"rate_limit"`
	EndpointHooks     EndpointHooksConfig     `json:"-" toml:"-"`
	DatabaseHooks     DatabaseHooksConfig     `json:"-" toml:"-"`
	EventHooks        EventHooksConfig        `json:"-" toml:"-"`
	Webhooks          WebhooksConfig          `json:"webhooks" toml:"webhooks"`
	EventBus          EventBusConfig          `json:"event_bus" toml:"event_bus"`
	Plugins           PluginsConfig           `json:"-" toml:"-"`
}

Config holds all configurable options for the GoBetterAuth library.

type ConfigManager added in v1.4.0

type ConfigManager interface {
	Init() error
	GetConfig() *Config
	Load() error
	Update(key string, value any) error
	Watch(ctx context.Context) (<-chan *Config, error)
}

type ConfigOption

type ConfigOption func(*Config)

type CustomRoute

type CustomRoute struct {
	Method     string
	Path       string
	Middleware []RouteMiddleware
	Handler    RouteHandler
}

type DatabaseConfig

type DatabaseConfig struct {
	Provider        string        `json:"provider" toml:"provider"`
	URL             string        `json:"url" toml:"url"`
	MaxOpenConns    int           `json:"max_open_conns" toml:"max_open_conns"`
	MaxIdleConns    int           `json:"max_idle_conns" toml:"max_idle_conns"`
	ConnMaxLifetime time.Duration `json:"conn_max_lifetime" toml:"conn_max_lifetime"`
}

type DatabaseHooksConfig

type DatabaseHooksConfig struct {
	Users         *UserDatabaseHooksConfig
	Accounts      *AccountDatabaseHooksConfig
	Sessions      *SessionDatabaseHooksConfig
	Verifications *VerificationDatabaseHooksConfig
}

type EmailChangeRequestResult added in v1.4.0

type EmailChangeRequestResult struct {
	Message string `json:"message"`
}

EmailChangeRequestResult represents the result of an email change request

type EmailChangeResult added in v1.4.0

type EmailChangeResult struct {
	Message string `json:"message"`
	User    *User  `json:"user,omitempty"`
}

EmailChangeResult represents the result of confirming an email change

type EmailConfig added in v1.4.0

type EmailConfig struct {
	Provider string `json:"provider" toml:"provider"`
	SMTPHost string `json:"smtp_host" toml:"smtp_host"`
	SMTPPort int    `json:"smtp_port" toml:"smtp_port"`
	SMTPUser string `json:"smtp_user" toml:"smtp_user"`
	SMTPPass string `json:"smtp_pass" toml:"smtp_pass"`
	From     string `json:"from" toml:"from"`
}

type EmailPasswordConfig

type EmailPasswordConfig struct {
	Enabled                  bool          `json:"enabled" toml:"enabled"`
	MinPasswordLength        int           `json:"min_password_length" toml:"min_password_length"`
	MaxPasswordLength        int           `json:"max_password_length" toml:"max_password_length"`
	DisableSignUp            bool          `json:"disable_sign_up" toml:"disable_sign_up"`
	RequireEmailVerification bool          `json:"require_email_verification" toml:"require_email_verification"`
	AutoSignIn               bool          `json:"auto_sign_in" toml:"auto_sign_in"`
	ResetTokenExpiry         time.Duration `json:"reset_token_expiry" toml:"reset_token_expiry"`
	// Library mode only
	Password               PasswordConfig                                  `json:"-" toml:"-"`
	SendResetPasswordEmail func(user User, url string, token string) error `json:"-" toml:"-"`
}

type EmailVerificationConfig

type EmailVerificationConfig struct {
	AutoSignIn   bool          `json:"auto_sign_in" toml:"auto_sign_in"`
	SendOnSignUp bool          `json:"send_on_sign_up" toml:"send_on_sign_up"`
	SendOnSignIn bool          `json:"send_on_sign_in" toml:"send_on_sign_in"`
	ExpiresIn    time.Duration `json:"expires_in" toml:"expires_in"`
	// Library mode only
	SendVerificationEmail func(user User, url string, token string) error `json:"-" toml:"-"`
}

type EndpointHookContext

type EndpointHookContext struct {
	Path            string
	Method          string
	Body            map[string]any
	Headers         map[string][]string
	Query           map[string][]string
	Request         *http.Request
	User            *User
	ResponseStatus  int
	ResponseHeaders map[string][]string
	ResponseBody    []byte
	ResponseCookies []*http.Cookie
	Redirect        func(url string, status int)
	Handled         bool
}

type EndpointHooksConfig

type EndpointHooksConfig struct {
	Before   func(ctx *EndpointHookContext) error
	Response func(ctx *EndpointHookContext) error
	After    func(ctx *EndpointHookContext)
}

type Event

type Event struct {
	ID        string            `json:"id"`
	Type      string            `json:"type"`
	Timestamp time.Time         `json:"timestamp"`
	Payload   json.RawMessage   `json:"payload"`
	Metadata  map[string]string `json:"metadata"`
}

Event represents data to be published or received via the EventBus

type EventBus

type EventBus interface {
	EventPublisher
	EventSubscriber
}

EventBus combines publisher and subscriber functionality

type EventBusConfig

type EventBusConfig struct {
	Enabled               bool   `json:"enabled" toml:"enabled"`
	Prefix                string `json:"prefix" toml:"prefix"`
	MaxConcurrentHandlers int    `json:"max_concurrent_handlers" toml:"max_concurrent_handlers"`
	PubSubType            string `json:"pubsub_type" toml:"pubsub_type"`
	PubSub                PubSub `json:"-" toml:"-"`
}

type EventEmitter added in v1.4.0

type EventEmitter interface {
	OnUserSignedUp(user User)
	OnUserLoggedIn(user User)
	OnEmailVerified(user User)
	OnPasswordChanged(user User)
	OnEmailChanged(user User)
}

type EventHandler

type EventHandler func(ctx context.Context, event Event) error

EventHandler processes events

type EventHooksConfig

type EventHooksConfig struct {
	OnUserSignedUp    func(user User)
	OnUserLoggedIn    func(user User)
	OnEmailVerified   func(user User)
	OnPasswordChanged func(user User)
	OnEmailChanged    func(user User)
}

type EventPublisher

type EventPublisher interface {
	Publish(ctx context.Context, event Event) error
	Close() error
}

EventPublisher defines the interface for publishing events

type EventSubscriber

type EventSubscriber interface {
	Subscribe(eventType string, handler EventHandler) (SubscriptionID, error)
	Unsubscribe(eventType string, id SubscriptionID)
	Close() error
}

EventSubscriber defines the interface for subscribing to events

type Handler added in v1.5.2

type Handler interface {
	Handle(w http.ResponseWriter, r *http.Request)
}

Handler is the interface for creating HTTP handlers for routes.

type IPConfig

type IPConfig struct {
	Headers []string `json:"headers" toml:"headers"`
}

type KeyValueStore

type KeyValueStore struct {
	Key       string     `gorm:"primaryKey;type:varchar(255)" json:"key" `
	Value     string     `json:"value"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
}

KeyValueStore represents the persistent key-value store table in the database. This is a domain model used for secondary storage operations.

func (KeyValueStore) TableName added in v1.4.0

func (KeyValueStore) TableName() string

TableName overrides the table name for GORM

type Logger added in v1.4.0

type Logger interface {
	// Debug logs a message at debug level with optional key-value pairs.
	Debug(msg string, args ...any)
	// Info logs a message at info level with optional key-value pairs.
	Info(msg string, args ...any)
	// Warn logs a message at warn level with optional key-value pairs.
	Warn(msg string, args ...any)
	// Error logs a message at error level with optional key-value pairs.
	Error(msg string, args ...any)
}

Logger defines an interface for logging operations, allowing users to plug in different logging implementations such as slog, zerolog, or others.

type LoggerConfig added in v1.4.0

type LoggerConfig struct {
	Level  string `json:"level" toml:"level"`
	Logger Logger `json:"-" toml:"-"`
}

type MailerService added in v1.4.0

type MailerService interface {
	Send(ctx context.Context, to string, subject string, body string, htmlBody string) error
}

type MeResult added in v1.4.0

type MeResult struct {
	User    *User    `json:"user"`
	Session *Session `json:"session"`
}

type Message

type Message struct {
	UUID     string
	Payload  []byte // Message payload (serialized data)
	Metadata map[string]string
}

Message represents a message in the pub/sub system.

type Mode added in v1.4.0

type Mode string
const (
	ModeLibrary    Mode = "library"    // Library mode: embedded in another application
	ModeStandalone Mode = "standalone" // Standalone mode: standalone server with database-backed configuration
)

type OAuth2LoginResult added in v1.4.0

type OAuth2LoginResult struct {
	AuthURL  string  // The authorization URL to redirect to
	State    string  // CSRF protection state
	Verifier *string // PKCE code verifier (if PKCE is required)
}

OAuth2LoginResult contains the information needed for the OAuth2 login flow

type OAuth2ProviderConfig added in v1.4.0

type OAuth2ProviderConfig struct {
	Enabled      bool     `json:"enabled" toml:"enabled"`
	ClientID     string   `json:"client_id" toml:"client_id"`
	ClientSecret string   `json:"client_secret" toml:"client_secret"`
	RedirectURL  string   `json:"redirect_url" toml:"redirect_url"`
	Scopes       []string `json:"scopes" toml:"scopes"`
	// For generic providers or overriding defaults
	AuthURL     string `json:"auth_url" toml:"auth_url"`
	TokenURL    string `json:"token_url" toml:"token_url"`
	UserInfoURL string `json:"user_info_url" toml:"user_info_url"`
}

type OAuth2UserInfo

type OAuth2UserInfo struct {
	ID       string
	Email    string
	Name     string
	Picture  string
	Verified bool
	Raw      map[string]any
}

type PasswordConfig

type PasswordConfig struct {
	Hash   func(password string) (string, error)      `json:"-" toml:"-"`
	Verify func(hashedPassword, password string) bool `json:"-" toml:"-"`
}

Library mode only

type PasswordResetRequestResult added in v1.4.0

type PasswordResetRequestResult struct {
	Message string `json:"message"`
}

PasswordResetRequestResult represents the result of a password reset request

type PasswordResetResult added in v1.4.0

type PasswordResetResult struct {
	Message string `json:"message"`
}

PasswordResetResult represents the result of a password reset

type PasswordService added in v1.4.0

type PasswordService interface {
	HashPassword(password string) (string, error)
	VerifyPassword(password string, hash string) (bool, error)
}

type Plugin

type Plugin interface {
	Metadata() PluginMetadata
	SetMetadata(meta PluginMetadata)

	Config() PluginConfig
	SetConfig(cfg PluginConfig)

	Ctx() *PluginContext
	SetCtx(ctx *PluginContext)

	Init(ctx *PluginContext) error
	SetInit(fn func(ctx *PluginContext) error)

	Migrations() []any
	SetMigrations(migrations []any)

	Routes() []PluginRoute
	SetRoutes(routes []PluginRoute)

	RateLimit() *PluginRateLimit
	SetRateLimit(rateLimit *PluginRateLimit)

	EndpointHooks() any
	SetEndpointHooks(hooks any)

	DatabaseHooks() any
	SetDatabaseHooks(hooks any)

	EventHooks() any
	SetEventHooks(hooks any)

	Webhooks() any
	SetWebhooks(hooks any)

	Close() error
	SetClose(fn func() error)
}

type PluginConfig

type PluginConfig struct {
	Enabled bool
	Options any
}

PluginConfig holds per-plugin configuration.

type PluginContext

type PluginContext struct {
	Config          *Config
	Api             AuthApi
	EventBus        EventBus
	Middleware      *ApiMiddleware
	WebhookExecutor WebhookExecutor
	Plugin          Plugin // Reference to the plugin being initialized
}

type PluginMetadata

type PluginMetadata struct {
	Name        string
	Version     string
	Description string
}

type PluginOption added in v1.3.4

type PluginOption func(p Plugin)

type PluginRateLimit

type PluginRateLimit = RateLimitConfig

type PluginRegistry added in v1.4.0

type PluginRegistry interface {
	Register(p Plugin)
	InitAll() error
	RunMigrations() error
	Plugins() []Plugin
	CloseAll()
}

type PluginRoute

type PluginRoute struct {
	Method     string
	Path       string // Relative path, /auth is auto-prefixed
	Middleware []RouteMiddleware
	Handler    RouteHandler
}

type PluginsConfig

type PluginsConfig struct {
	Plugins []Plugin
}

Library mode only

type ProviderType

type ProviderType string
const (
	ProviderEmail   ProviderType = "email"
	ProviderDiscord ProviderType = "discord"
	ProviderGitHub  ProviderType = "github"
	ProviderGoogle  ProviderType = "google"
)

type PubSub

type PubSub interface {
	// Publish sends a message to the specified topic
	Publish(ctx context.Context, topic string, msg *Message) error

	// Subscribe returns a channel that receives messages from the specified topic.
	// The channel should be closed when the subscription is cancelled or closed.
	Subscribe(ctx context.Context, topic string) (<-chan *Message, error)

	// Close closes the pub/sub and cleans up resources
	Close() error
}

PubSub is a generic publish-subscribe interface.

type RateLimitConfig

type RateLimitConfig struct {
	Enabled     bool                           `json:"enabled" toml:"enabled"`
	Window      time.Duration                  `json:"window" toml:"window"`
	Max         int                            `json:"max" toml:"max"`
	Algorithm   string                         `json:"algorithm" toml:"algorithm"`
	Prefix      string                         `json:"prefix" toml:"prefix"`
	CustomRules map[string]RateLimitCustomRule `json:"custom_rules" toml:"custom_rules"`
	IP          IPConfig                       `json:"ip" toml:"ip"`
}

type RateLimitCustomRule

type RateLimitCustomRule struct {
	Disabled bool          `json:"disabled" toml:"disabled"`
	Window   time.Duration `json:"window" toml:"window"`
	Max      int           `json:"max" toml:"max"`
}

type RateLimitService

type RateLimitService interface {
	Allow(ctx context.Context, key string, req *http.Request) (bool, error)
	GetClientIP(req *http.Request) string
	BuildKey(key string) string
}

type RouteHandler added in v1.5.2

type RouteHandler func() http.Handler

func WrapHandler added in v1.5.2

func WrapHandler(h Handler) RouteHandler

WrapHandler converts a Handler to a RouteHandler.

type RouteMiddleware added in v1.5.2

type RouteMiddleware func(http.Handler) http.Handler

type SecondaryStorage

type SecondaryStorage interface {
	Get(ctx context.Context, key string) (any, error)
	Set(ctx context.Context, key string, value any, ttl *time.Duration) error
	Delete(ctx context.Context, key string) error
	Incr(ctx context.Context, key string, ttl *time.Duration) (int, error)
	Close() error
}

SecondaryStorage defines an interface for secondary storage operations.

type SecondaryStorageConfig

type SecondaryStorageConfig struct {
	Type            SecondaryStorageType            `json:"type" toml:"type"`
	MemoryOptions   SecondaryStorageMemoryOptions   `json:"memory_options" toml:"memory_options"`
	DatabaseOptions SecondaryStorageDatabaseOptions `json:"database_options" toml:"database_options"`
	Storage         SecondaryStorage                `json:"-" toml:"-"`
}

type SecondaryStorageDatabaseOptions

type SecondaryStorageDatabaseOptions struct {
	// CleanupInterval controls how often expired entries are cleaned up.
	CleanupInterval time.Duration `json:"cleanup_interval" toml:"cleanup_interval"`
}

type SecondaryStorageMemoryOptions

type SecondaryStorageMemoryOptions struct {
	// CleanupInterval controls how often expired entries are cleaned up.
	CleanupInterval time.Duration `json:"cleanup_interval" toml:"cleanup_interval"`
}

type SecondaryStorageType

type SecondaryStorageType string
const (
	SecondaryStorageTypeMemory   SecondaryStorageType = "memory"
	SecondaryStorageTypeDatabase SecondaryStorageType = "database"
	SecondaryStorageTypeCustom   SecondaryStorageType = "custom"
)

type Session

type Session struct {
	ID        string    `json:"id" gorm:"primaryKey"`
	UserID    string    `json:"user_id" gorm:"index"`
	Token     string    `json:"token" gorm:"uniqueIndex"`
	ExpiresAt time.Time `json:"expires_at"`
	IPAddress *string   `json:"ip_address,omitempty"`
	UserAgent *string   `json:"user_agent,omitempty"`
	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}

type SessionConfig

type SessionConfig struct {
	CookieName string        `json:"cookie_name" toml:"cookie_name"`
	ExpiresIn  time.Duration `json:"expires_in" toml:"expires_in"`
	UpdateAge  time.Duration `json:"update_age" toml:"update_age"`
}

type SessionDatabaseHooksConfig

type SessionDatabaseHooksConfig struct {
	BeforeCreate func(session *Session) error
	AfterCreate  func(session Session) error
}

type SessionService

type SessionService interface {
	CreateSession(userID string, token string) (*Session, error)
	GetSessionByUserID(userID string) (*Session, error)
	GetSessionByToken(token string) (*Session, error)
	DeleteSessionByID(ID string) error
}

type SignInResult added in v1.4.0

type SignInResult struct {
	Token     string  `json:"token"`
	User      *User   `json:"user"`
	CSRFToken *string `json:"csrf_token,omitempty"`
}

SignInResult represents the result of a sign-in operation

type SignOutResult added in v1.4.0

type SignOutResult struct {
	Message string `json:"message"`
}

SignOutResult represents the result of a sign-out operation

type SignUpResult added in v1.4.0

type SignUpResult struct {
	Token     string  `json:"token,omitempty"`
	User      *User   `json:"user"`
	CSRFToken *string `json:"csrf_token,omitempty"`
}

SignUpResult represents the result of a sign-up operation

type SocialProvidersConfig

type SocialProvidersConfig map[string]OAuth2ProviderConfig

type SubscriptionID added in v1.3.1

type SubscriptionID uint64

SubscriptionID identifies a specific event handler subscription for removal

type TokenService

type TokenService interface {
	GenerateToken() (string, error)
	HashToken(token string) string
	GenerateEncryptedToken() (string, error)
	EncryptToken(token string) (string, error)
	DecryptToken(encryptedToken string) (string, error)
}

type TrustedOriginsConfig

type TrustedOriginsConfig struct {
	Origins []string `json:"origins" toml:"origins"`
}

type User

type User struct {
	ID            string    `json:"id" gorm:"primaryKey"`
	Name          string    `json:"name"`
	Email         string    `json:"email" gorm:"uniqueIndex"`
	EmailVerified bool      `json:"email_verified"`
	Image         *string   `json:"image,omitempty"`
	CreatedAt     time.Time `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt     time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}

type UserConfig

type UserConfig struct {
	ChangeEmail ChangeEmailConfig `json:"change_email" toml:"change_email"`
}

type UserDatabaseHooksConfig

type UserDatabaseHooksConfig struct {
	BeforeCreate func(user *User) error
	AfterCreate  func(user User) error
	BeforeUpdate func(user *User) error
	AfterUpdate  func(user User) error
}

type UserService

type UserService interface {
	CreateUser(user *User) error
	GetUserByID(id string) (*User, error)
	GetUserByEmail(email string) (*User, error)
	UpdateUser(user *User) error
}

type Verification

type Verification struct {
	ID         string           `json:"id" gorm:"primaryKey"`
	UserID     *string          `json:"user_id,omitempty"`
	Identifier string           `json:"identifier"` // email or other identifier
	Token      string           `json:"token"`
	Type       VerificationType `json:"type"`
	ExpiresAt  time.Time        `json:"expires_at"`
	CreatedAt  time.Time        `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt  time.Time        `json:"updated_at" gorm:"autoUpdateTime"`
}

type VerificationDatabaseHooksConfig

type VerificationDatabaseHooksConfig struct {
	BeforeCreate func(verification *Verification) error
	AfterCreate  func(verification Verification) error
}

type VerificationService

type VerificationService interface {
	CreateVerification(verif *Verification) error
	GetVerificationByToken(token string) (*Verification, error)
	DeleteVerification(id string) error
	IsExpired(verif *Verification) bool
}

type VerificationType

type VerificationType string
const (
	TypeEmailVerification VerificationType = "email_verification"
	TypePasswordReset     VerificationType = "password_reset"
	TypeEmailChange       VerificationType = "email_change"
)

type VerifyEmailResult added in v1.4.0

type VerifyEmailResult struct {
	Message string `json:"message"`
	User    *User  `json:"user,omitempty"`
}

VerifyEmailResult represents the result of email verification

type WebhookConfig added in v1.4.0

type WebhookConfig struct {
	URL            string            `json:"url" toml:"url"`
	Headers        map[string]string `json:"headers" toml:"headers"`
	TimeoutSeconds time.Duration     `json:"timeout_seconds" toml:"timeout_seconds"`
}

type WebhookExecutor added in v1.4.0

type WebhookExecutor interface {
	ExecuteWebhook(webhook *WebhookConfig, payload any) error
}

WebhookExecutor defines the interface for executing webhooks

type WebhooksConfig added in v1.4.0

type WebhooksConfig struct {
	OnUserSignedUp    *WebhookConfig `json:"on_user_signed_up" toml:"on_user_signed_up"`
	OnUserLoggedIn    *WebhookConfig `json:"on_user_logged_in" toml:"on_user_logged_in"`
	OnEmailVerified   *WebhookConfig `json:"on_email_verified" toml:"on_email_verified"`
	OnPasswordChanged *WebhookConfig `json:"on_password_changed" toml:"on_password_changed"`
	OnEmailChanged    *WebhookConfig `json:"on_email_changed" toml:"on_email_changed"`
}

Jump to

Keyboard shortcuts

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