Documentation
¶
Overview ¶
Package twofactor implements Two-Factor Authentication (2FA) via TOTP.
Package twofactor implements Two-Factor Authentication (2FA) via Time-based One-Time Passwords (TOTP / RFC 6238).
Configuration Options ¶
You can customize the behavior of the TwoFactor plugin using functional options:
- twofactor.WithIssuer(issuer string): Sets the application/issuer name shown in authenticator apps (default: "Auth").
Custom Storage Repository ¶
To store TOTP secrets in a custom database, implement the twofactor.Repository interface:
type MyDatabase struct { /* db connection */ }
func (db *MyDatabase) SaveTOTPSecret(ctx context.Context, userID string, secret string) error { ... }
func (db *MyDatabase) GetTOTPSecret(ctx context.Context, userID string) (string, error) { ... }
Event Hooks ¶
The plugin emits the following event hook on the global EventBus:
- twofactor.EventTOTPGenerated: Published when a new 2FA TOTP secret URI is created.
Index ¶
Constants ¶
const ( // EventTOTPGenerated is published when a new 2FA TOTP secret has been generated and stored. // // Event payload: (ctx context.Context, userID string, secret string) // // Example usage: // // app.Events().Subscribe(twofactor.EventTOTPGenerated, func(ctx context.Context, userID string, secret string) { // log.Printf("New 2FA TOTP secret generated for user %s: %s", userID, secret) // }) EventTOTPGenerated = "two-factor:totp:generated" )
Event names published by the TwoFactor plugin.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
Issuer string
}
Config contains configuration settings for the TwoFactor plugin.
type Option ¶
type Option func(*Config)
Option defines a functional option for configuring the TwoFactor plugin.
func WithIssuer ¶
WithIssuer sets the issuer name embedded in the generated TOTP URI (e.g. "My App").
type Plugin ¶
type Plugin struct {
// contains filtered or unexported fields
}
Plugin implements 2FA TOTP secret generation and verification functionality.
func New ¶
func New(repo Repository, opts ...Option) *Plugin
New creates a new TwoFactor plugin instance with the specified repository and options.
func (*Plugin) GenerateTOTPSecret ¶
GenerateTOTPSecret creates and stores a new TOTP secret for the specified user and returns the otpauth:// URI. Emits EventTOTPGenerated upon creation.
type Repository ¶
type Repository interface {
// SaveTOTPSecret stores a user's generated TOTP secret.
SaveTOTPSecret(ctx context.Context, userID string, secret string) error
// GetTOTPSecret retrieves a user's stored TOTP secret. Returns domain.ErrTOTPNotFound if not found.
GetTOTPSecret(ctx context.Context, userID string) (string, error)
}
Repository defines the storage contract required by the TwoFactor plugin to persist and retrieve TOTP secrets.