Documentation
¶
Overview ¶
Package twofactor defines event names and typed event payloads published by the TwoFactor plugin on the global EventBus.
Index ¶
- Constants
- Variables
- func BuildTOTPURI(issuer, accountName, secret string, digits, period int, alg TOTPAlgorithm) string
- func DecodeBase32Secret(secret string) ([]byte, error)
- func GenerateBackupCodes(amount, length int) ([]string, error)
- func GenerateBase32Secret(byteLength int) (string, error)
- func GenerateRandomNumericCode(digits int) (string, error)
- func GenerateRandomToken(byteLength int) (string, error)
- func GenerateTOTPCode(secret string, timestamp int64, period int, digits int, alg TOTPAlgorithm) (string, error)
- func GenerateTrustDeviceToken(userID, deviceID, secret string, expiresAt time.Time) string
- func NormalizeCode(code string) string
- func TwoFactorChallengeKey(token string) string
- func TwoFactorMethodKey(userID string) string
- func TwoFactorPendingKey(userID string) string
- func TwoFactorVerifiedKey(userID string) string
- func ValidateBackupCode(codes []string, inputCode string) (int, bool)
- func ValidateTOTPCode(secret, code string, period int, digits int, alg TOTPAlgorithm) bool
- func VerifyTrustDeviceToken(token, userID, deviceID, secret string) bool
- type AccountLockedEventPayload
- type AccountLockoutConfig
- type BackupCodesRegeneratedEventPayload
- type BackupCodesResult
- type ChallengeCreatedEventPayload
- type ChallengeRecord
- type ChallengeResult
- type Config
- type CreateChallengeParams
- type DeviceTrustedEventPayload
- type DisableAfterEventPayload
- type DisableBeforeEventPayload
- type DisableParams
- type EnableAfterEventPayload
- type EnableBeforeEventPayload
- type EnableParams
- type EnableResult
- type GenerateBackupCodesParams
- type GetTOTPURIParams
- type OTPChallenge
- type Option
- func WithAccountLockout(enabled bool, maxAttempts int, duration time.Duration) Option
- func WithAlgorithm(alg TOTPAlgorithm) Option
- func WithAllowPasswordless(allow bool) Option
- func WithBackupCodeOptions(amount, length int) Option
- func WithChallengeExpiry(d time.Duration) Option
- func WithIssuer(issuer string) Option
- func WithLockoutProtection(maxAttempts int, duration time.Duration) Option
- func WithOTPOptions(digits int, period time.Duration) Option
- func WithSendOTP(fn SendOTPFunc) Option
- func WithSkipVerificationOnEnable(skip bool) Option
- func WithTOTPOptions(digits int, period int) Option
- func WithTrustDevice(secret string, maxAge time.Duration) Option
- type Plugin
- func (p *Plugin) CreateChallenge(ctx context.Context, params CreateChallengeParams) (*ChallengeResult, error)
- func (p *Plugin) Disable(ctx context.Context, params DisableParams) error
- func (p *Plugin) Enable(ctx context.Context, params EnableParams) (*EnableResult, error)
- func (p *Plugin) GenerateBackupCodes(ctx context.Context, params GenerateBackupCodesParams) (*BackupCodesResult, error)
- func (p *Plugin) GenerateTOTPSecret(ctx context.Context, userID string) (string, error)
- func (p *Plugin) GetTOTPURI(ctx context.Context, params GetTOTPURIParams) (string, error)
- func (p *Plugin) ID() string
- func (p *Plugin) Init(ctx *plugin.Context) error
- func (p *Plugin) RevokeAllTrustedDevices(ctx context.Context, userID string) error
- func (p *Plugin) RevokeTrustedDevice(ctx context.Context, params RevokeTrustedDeviceParams) error
- func (p *Plugin) SendOTP(ctx context.Context, params SendOTPParams) (*SendOTPResult, error)
- func (p *Plugin) TrustDevice(ctx context.Context, params TrustDeviceParams) (*TrustDeviceResult, error)
- func (p *Plugin) VerifyBackupCode(ctx context.Context, params VerifyBackupCodeParams) (*VerifyResult, error)
- func (p *Plugin) VerifyChallenge(ctx context.Context, params VerifyChallengeParams) (*VerifyResult, error)
- func (p *Plugin) VerifyCode(ctx context.Context, userID, code string) (bool, error)
- func (p *Plugin) VerifyOTP(ctx context.Context, params VerifyOTPParams) (*VerifyResult, error)
- func (p *Plugin) VerifyTOTP(ctx context.Context, params VerifyTOTPParams) (*VerifyResult, error)
- func (p *Plugin) VerifyTrustDevice(ctx context.Context, params VerifyTrustDeviceParams) (bool, error)
- func (p *Plugin) ViewBackupCodes(ctx context.Context, params ViewBackupCodesParams) (*BackupCodesResult, error)
- type Repository
- type RevokeTrustedDeviceParams
- type SendOTPAfterEventPayload
- type SendOTPBeforeEventPayload
- type SendOTPFunc
- type SendOTPParams
- type SendOTPResult
- type TOTPAlgorithm
- type TOTPGeneratedEventPayload
- type TrustDeviceParams
- type TrustDeviceRecord
- type TrustDeviceResult
- type TwoFactor
- type VerifyBackupCodeParams
- type VerifyChallengeParams
- type VerifyFailedEventPayload
- type VerifyOTPParams
- type VerifyResult
- type VerifySuccessEventPayload
- type VerifyTOTPParams
- type VerifyTrustDeviceParams
- type ViewBackupCodesParams
Constants ¶
const ( // EventEnableBefore is emitted right before starting 2FA enrollment for a user. // Payload: *EnableBeforeEventPayload EventEnableBefore = "twofactor:enable:before" // EventEnableAfter is emitted after successfully generating and persisting 2FA secrets and backup codes. // Payload: *EnableAfterEventPayload EventEnableAfter = "twofactor:enable:after" // EventDisableBefore is emitted before disabling 2FA credentials for a user. // Payload: *DisableBeforeEventPayload EventDisableBefore = "twofactor:disable:before" // EventDisableAfter is emitted after 2FA credentials have been removed from storage. // Payload: *DisableAfterEventPayload EventDisableAfter = "twofactor:disable:after" // EventVerifySuccess is emitted after any successful 2FA verification (TOTP, Backup Code, OTP, Challenge). // Payload: *VerifySuccessEventPayload EventVerifySuccess = "twofactor:verify:success" // EventVerifyFailed is emitted after any failed 2FA verification attempt. // Payload: *VerifyFailedEventPayload EventVerifyFailed = "twofactor:verify:failed" // EventSendOTPBefore is emitted before generating and sending an SMS/Email OTP challenge. // Payload: *SendOTPBeforeEventPayload EventSendOTPBefore = "twofactor:send_otp:before" // EventSendOTPAfter is emitted after an OTP challenge has been successfully dispatched. // Payload: *SendOTPAfterEventPayload EventSendOTPAfter = "twofactor:send_otp:after" // EventAccountLocked is emitted when 2FA verification is locked out due to excessive failed attempts. // Payload: *AccountLockedEventPayload EventAccountLocked = "twofactor:account:locked" // EventDeviceTrusted is emitted when a client device is authorized as a trusted device. // Payload: *DeviceTrustedEventPayload EventDeviceTrusted = "twofactor:device:trusted" // EventBackupCodesRegenerated is emitted after fresh single-use backup recovery codes are generated. // Payload: *BackupCodesRegeneratedEventPayload EventBackupCodesRegenerated = "twofactor:backup_codes:regenerated" // EventTOTPGenerated is emitted whenever a raw Base32 TOTP secret is created. // Payload: *TOTPGeneratedEventPayload EventTOTPGenerated = "twofactor:totp:generated" // EventChallengeCreated is emitted when a temporary sign-in 2FA challenge is issued. // Payload: *ChallengeCreatedEventPayload EventChallengeCreated = "twofactor:challenge:created" )
const ( // ExtraKeyTwoFactorMethod specifies the method used for 2FA (e.g. "totp", "backup_code", "otp", "sms", "email"). ExtraKeyTwoFactorMethod = "two_factor_method" // ExtraKeyDeviceID represents the unique hardware or installation identifier of the client device. ExtraKeyDeviceID = "device_id" // ExtraKeyIPAddress represents the IP address of the client performing 2FA enrollment or verification. ExtraKeyIPAddress = "ip_address" // ExtraKeyUserAgent represents the User-Agent header of the client device during 2FA operations. ExtraKeyUserAgent = "user_agent" // ExtraKeyTrustDevice indicates whether the client requests trusting the current device to bypass subsequent 2FA challenges. ExtraKeyTrustDevice = "trust_device" // ExtraKeyTrustDeviceToken represents the cryptographic HMAC token issued to an authorized trusted device. ExtraKeyTrustDeviceToken = "trust_device_token" // ExtraKeySessionID represents the session ID associated with the 2FA authentication flow. ExtraKeySessionID = "session_id" // ExtraKeyIssuer overrides the default application issuer name shown in authenticator apps. ExtraKeyIssuer = "issuer" // ExtraKeyPhoneNumber represents the destination phone number for SMS OTP challenges. ExtraKeyPhoneNumber = "phone_number" // ExtraKeyEmail represents the destination email address for Email OTP challenges. ExtraKeyEmail = "email" // ExtraKeyChallengeToken represents the temporary challenge token issued following a primary sign-in. ExtraKeyChallengeToken = "challenge_token" // ExtraKeyTwoFactorVerified indicates if two-factor verification succeeded. ExtraKeyTwoFactorVerified = "two_factor_verified" )
Standard Extra metadata keys that can be set or consumed in TwoFactor parameters (such as EnableParams.Extra, VerifyChallengeParams.Extra, and Event payloads).
const ( // MethodTOTP represents Time-based One-Time Password authentication (RFC 6238). MethodTOTP = "totp" // MethodBackupCode represents single-use recovery backup codes. MethodBackupCode = "backup_code" // MethodOTP represents challenge-based one-time password verification. MethodOTP = "otp" // MethodSMS represents SMS-delivered OTP challenges. MethodSMS = "sms" // MethodEmail represents Email-delivered OTP challenges. MethodEmail = "email" )
Supported two-factor authentication method constants.
const ( // ContextKeyTwoFactorPendingPrefix is the key prefix indicating a pending 2FA challenge for a user. ContextKeyTwoFactorPendingPrefix = "2fa_pending_" // ContextKeyTwoFactorVerifiedPrefix is the key prefix indicating verified 2FA status for a user. ContextKeyTwoFactorVerifiedPrefix = "2fa_verified_" // ContextKeyTwoFactorMethodPrefix is the key prefix indicating the active 2FA method for a user. ContextKeyTwoFactorMethodPrefix = "2fa_method_" // ContextKeyTwoFactorChallengePrefix is the key prefix for temporary challenge tokens. ContextKeyTwoFactorChallengePrefix = "2fa_challenge_" )
Context keys stored in plugin.Context for TwoFactor state management.
const (
// BackupCharset defines the unambiguous alfanumeric charset (excluding 0/O, 1/I/L) used for backup recovery codes.
BackupCharset = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
)
const PluginID = "two-factor"
PluginID is the unique string identifier for the TwoFactor plugin ("two-factor").
Variables ¶
var ( // ErrTwoFactorNotEnabled is returned when 2FA operations are attempted for a user without active 2FA configuration. ErrTwoFactorNotEnabled = errors.New("twofactor: two-factor authentication is not enabled for this user") // ErrTwoFactorAlreadyEnabled is returned when attempting to enable 2FA on an account that already has verified 2FA active. ErrTwoFactorAlreadyEnabled = errors.New("twofactor: two-factor authentication is already enabled") // ErrInvalidCode is returned when a provided TOTP or backup code is invalid or does not match stored credentials. ErrInvalidCode = errors.New("twofactor: invalid verification code") // ErrAccountLocked is returned when 2FA verification is temporarily locked due to excessive failed attempts. ErrAccountLocked = errors.New("twofactor: two-factor authentication is temporarily locked due to excessive failed attempts") // ErrOTPNotConfigured is returned when attempting to send an OTP challenge without a registered SendOTP delivery callback. ErrOTPNotConfigured = errors.New("twofactor: send OTP callback is not configured") // ErrOTPExpired is returned when attempting to verify an OTP challenge that has expired or does not exist. ErrOTPExpired = errors.New("twofactor: OTP challenge has expired or does not exist") // ErrTooManyAttempts is returned when the maximum number of failed attempts on an active OTP challenge or lockout threshold has been exceeded. ErrTooManyAttempts = errors.New("twofactor: maximum attempt limit reached") // ErrPasswordRequired is returned when an operation strictly requires password confirmation before proceeding. ErrPasswordRequired = errors.New("twofactor: password is required for this operation") // ErrInvalidDeviceToken is returned when a trusted device token signature fails validation or has expired. ErrInvalidDeviceToken = errors.New("twofactor: trusted device token is invalid or expired") // ErrChallengeExpired is returned when a sign-in challenge token has passed its expiration time. ErrChallengeExpired = errors.New("twofactor: challenge token has expired") // ErrInvalidChallengeToken is returned when a submitted sign-in challenge token does not exist in storage. ErrInvalidChallengeToken = errors.New("twofactor: invalid challenge token") )
Functions ¶
func BuildTOTPURI ¶ added in v0.7.0
func BuildTOTPURI(issuer, accountName, secret string, digits, period int, alg TOTPAlgorithm) string
BuildTOTPURI constructs a RFC 6238 compliant otpauth:// URI for authenticator app QR code generation.
func DecodeBase32Secret ¶ added in v0.7.0
DecodeBase32Secret decodes a Base32 encoded secret, normalizing spaces and stripping padding.
func GenerateBackupCodes ¶ added in v0.7.0
GenerateBackupCodes creates a set of random alphanumeric single-use recovery codes formatted as XXXXX-XXXXX.
func GenerateBase32Secret ¶ added in v0.7.0
GenerateBase32Secret generates a cryptographically secure random secret encoded in RFC 4648 Base32 without padding.
func GenerateRandomNumericCode ¶ added in v0.7.0
GenerateRandomNumericCode generates a cryptographically secure random numeric string of specified length.
func GenerateRandomToken ¶ added in v0.7.0
GenerateRandomToken generates a cryptographically secure URL-safe random token string.
func GenerateTOTPCode ¶ added in v0.7.0
func GenerateTOTPCode(secret string, timestamp int64, period int, digits int, alg TOTPAlgorithm) (string, error)
GenerateTOTPCode calculates the RFC 6238 TOTP code for the specified secret, timestamp, and parameters.
func GenerateTrustDeviceToken ¶ added in v0.7.0
GenerateTrustDeviceToken generates a signed cryptographic token authorizing a trusted device. Format: "<payload_base64>.<hmac_signature_base64>" where payload is "userID:deviceID:expiresAtUnix".
func NormalizeCode ¶ added in v0.7.0
NormalizeCode standardizes an input code by removing spaces, hyphens and converting to uppercase.
func TwoFactorChallengeKey ¶ added in v0.7.0
TwoFactorChallengeKey formats the context store key used to cache challenge tokens.
func TwoFactorMethodKey ¶ added in v0.4.0
TwoFactorMethodKey formats the context store key used to track the active 2FA method for the given user.
func TwoFactorPendingKey ¶ added in v0.4.0
TwoFactorPendingKey formats the context store key used to track a pending 2FA verification for the given user.
func TwoFactorVerifiedKey ¶ added in v0.4.0
TwoFactorVerifiedKey formats the context store key used to track a completed 2FA verification for the given user.
func ValidateBackupCode ¶ added in v0.7.0
ValidateBackupCode searches for the given input code within a slice of backup codes using constant-time comparison. Returns the index of the matching code and true if valid, or -1 and false otherwise.
func ValidateTOTPCode ¶ added in v0.7.0
func ValidateTOTPCode(secret, code string, period int, digits int, alg TOTPAlgorithm) bool
ValidateTOTPCode validates an incoming TOTP code against a secret across the ±1 period tolerance window. It executes comparison using constant-time comparison to guard against side-channel timing attacks.
func VerifyTrustDeviceToken ¶ added in v0.7.0
VerifyTrustDeviceToken validates the HMAC signature, payload structure, and expiration of a trusted device token.
Types ¶
type AccountLockedEventPayload ¶ added in v0.7.0
type AccountLockedEventPayload struct {
// UserID identifies the locked user.
UserID string
// Failures is the number of consecutive failed attempts triggering the lockout.
Failures int
// LockedUntil specifies the timestamp when the lockout expires.
LockedUntil time.Time
}
AccountLockedEventPayload contains details when an account lockout is triggered.
type AccountLockoutConfig ¶ added in v0.7.0
type AccountLockoutConfig struct {
// Enabled indicates if failed verification attempts should lock the account.
Enabled bool
// MaxFailedAttempts specifies the maximum consecutive failed attempts before lockout triggers.
MaxFailedAttempts int
// Duration specifies how long 2FA operations remain locked out after exceeding max failed attempts.
Duration time.Duration
}
AccountLockoutConfig defines rate-limiting brute force protection rules.
type BackupCodesRegeneratedEventPayload ¶ added in v0.7.0
type BackupCodesRegeneratedEventPayload struct {
// UserID identifies the user whose codes were regenerated.
UserID string
// Amount is the number of new backup codes generated.
Amount int
}
BackupCodesRegeneratedEventPayload contains confirmation when backup codes are regenerated.
type BackupCodesResult ¶ added in v0.7.0
type BackupCodesResult struct {
// BackupCodes is the collection of alphanumeric backup recovery codes.
BackupCodes []string `json:"backup_codes"`
}
BackupCodesResult contains the slice of active single-use backup recovery codes.
type ChallengeCreatedEventPayload ¶ added in v0.7.0
type ChallengeCreatedEventPayload struct {
// Token is the challenge token string.
Token string
// UserID identifies the target user.
UserID string
// ExpiresAt specifies when the challenge token expires.
ExpiresAt time.Time
}
ChallengeCreatedEventPayload contains details of an issued sign-in challenge.
type ChallengeRecord ¶ added in v0.7.0
type ChallengeRecord struct {
// Token is the unique challenge token string.
Token string `json:"token"`
// UserID is the target user required to fulfill the 2FA challenge.
UserID string `json:"user_id"`
// ExpiresAt is the timestamp after which this challenge token becomes invalid.
ExpiresAt time.Time `json:"expires_at"`
// CreatedAt is the timestamp when the challenge was generated.
CreatedAt time.Time `json:"created_at"`
}
ChallengeRecord represents a temporary sign-in challenge issued after primary credential validation.
type ChallengeResult ¶ added in v0.7.0
type ChallengeResult struct {
// ChallengeToken is the random token string used to complete the multi-factor flow.
ChallengeToken string `json:"challenge_token"`
// UserID is the target user's identifier.
UserID string `json:"user_id"`
// ExpiresAt is the timestamp when this challenge token becomes invalid.
ExpiresAt time.Time `json:"expires_at"`
}
ChallengeResult contains the generated challenge token and its expiration.
type Config ¶
type Config struct {
// Issuer specifies the application name embedded into the TOTP URI shown in authenticator apps (default: "GoModularAuth").
Issuer string
// Algorithm specifies the hashing algorithm for TOTP (AlgorithmSHA1, AlgorithmSHA256, AlgorithmSHA512).
Algorithm TOTPAlgorithm
// TotpDigits specifies the number of digits in generated TOTP codes (6 or 8, default: 6).
TotpDigits int
// TotpPeriod specifies the rotation interval for TOTP codes in seconds (default: 30).
TotpPeriod int
// BackupCodeAmount defines the total number of single-use backup codes generated during enrollment (default: 10).
BackupCodeAmount int
// BackupCodeLength defines the character length of each generated backup code (default: 10).
BackupCodeLength int
// AllowPasswordless allows 2FA management operations without requiring prior password re-validation.
AllowPasswordless bool
// SkipVerificationOnEnable marks 2FA as immediately active upon enrollment without demanding a first verified TOTP code.
SkipVerificationOnEnable bool
// ChallengeExpiry defines the expiration duration for sign-in 2FA challenge tokens (default: 10 minutes).
ChallengeExpiry time.Duration
// TrustDeviceMaxAge defines the validity duration for authorized trusted devices (default: 30 days).
TrustDeviceMaxAge time.Duration
// TrustDeviceSecret is the HMAC secret used to cryptographically sign trusted device tokens.
TrustDeviceSecret string
// OTPDigits specifies the numeric length for challenge-based OTP codes (default: 6).
OTPDigits int
// OTPPeriod defines the expiration duration for temporary OTP challenges (default: 3 minutes).
OTPPeriod time.Duration
// Lockout holds configuration for account lockout rate limiting.
Lockout AccountLockoutConfig
// SendOTP registers the external delivery callback for SMS or Email OTP dispatches.
SendOTP SendOTPFunc
}
Config holds configuration parameters for the two-factor authentication plugin.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns the default production configuration for the TwoFactor plugin.
type CreateChallengeParams ¶ added in v0.7.0
type CreateChallengeParams struct {
// UserID identifies the user required to fulfill the 2FA challenge (required).
UserID string `json:"user_id"`
// Extra holds dynamic metadata passed through event interceptors (optional).
Extra map[string]any `json:"extra,omitempty"`
}
CreateChallengeParams defines parameters to issue a temporary sign-in challenge token.
func (*CreateChallengeParams) Get ¶ added in v0.7.0
func (p *CreateChallengeParams) Get(key string) (any, bool)
func (*CreateChallengeParams) Set ¶ added in v0.7.0
func (p *CreateChallengeParams) Set(key string, value any)
type DeviceTrustedEventPayload ¶ added in v0.7.0
type DeviceTrustedEventPayload struct {
// UserID identifies the device owner.
UserID string
// DeviceID identifies the trusted client hardware or installation.
DeviceID string
// ExpiresAt specifies when the device trust expires.
ExpiresAt time.Time
}
DeviceTrustedEventPayload contains details when a client device is authorized.
type DisableAfterEventPayload ¶ added in v0.7.0
type DisableAfterEventPayload struct {
// UserID identifies the user whose 2FA configuration was removed.
UserID string
}
DisableAfterEventPayload contains the user ID associated with a 2FA disablement event.
type DisableBeforeEventPayload ¶ added in v0.7.0
type DisableBeforeEventPayload struct {
// UserID identifies the user whose 2FA configuration is being disabled.
UserID string
// Params holds the mutable disable parameters.
Params *DisableParams
}
DisableBeforeEventPayload contains details before 2FA credentials are removed.
type DisableParams ¶
type DisableParams struct {
// UserID identifies the user whose 2FA is being deactivated (required).
UserID string `json:"user_id"`
// Password is the optional password confirmation.
Password string `json:"password,omitempty"`
// Extra holds dynamic metadata passed through event interceptors (optional).
Extra map[string]any `json:"extra,omitempty"`
}
DisableParams defines parameters to disable 2FA for a user.
func (*DisableParams) Set ¶ added in v0.7.0
func (p *DisableParams) Set(key string, value any)
type EnableAfterEventPayload ¶ added in v0.7.0
type EnableAfterEventPayload struct {
// UserID identifies the user whose 2FA enrollment completed.
UserID string
// BackupCodesCount is the number of single-use backup codes generated.
BackupCodesCount int
}
EnableAfterEventPayload contains confirmation details after 2FA secrets have been created.
type EnableBeforeEventPayload ¶ added in v0.7.0
type EnableBeforeEventPayload struct {
// UserID identifies the user beginning 2FA setup.
UserID string
// Params holds the mutable enrollment parameters (including dynamic Extra metadata).
Params *EnableParams
}
EnableBeforeEventPayload contains the user ID and mutable parameters for pre-enrollment interception.
type EnableParams ¶
type EnableParams struct {
// UserID is the unique identifier of the user enrolling in 2FA (required).
UserID string `json:"user_id"`
// Password is the user's current password if password re-authentication is enforced (optional).
Password string `json:"password,omitempty"`
// Issuer overrides the default application issuer name shown in authenticator apps (optional).
Issuer string `json:"issuer,omitempty"`
// Extra holds dynamic metadata passed through event interceptors (optional).
Extra map[string]any `json:"extra,omitempty"`
}
EnableParams defines parameters required to initialize 2FA enrollment for a user.
func (*EnableParams) Set ¶
func (p *EnableParams) Set(key string, value any)
Helper methods for Extra metadata manipulation
type EnableResult ¶
type EnableResult struct {
// TOTPURI is the otpauth:// URI encoded with secret, issuer, digits, and period for QR code generation.
TOTPURI string `json:"totp_uri"`
// Secret is the generated Base32 encoded secret.
Secret string `json:"secret"`
// BackupCodes is the list of generated single-use recovery codes.
BackupCodes []string `json:"backup_codes"`
}
EnableResult contains the generated Base32 secret, TOTP setup URI, and initial single-use backup codes.
type GenerateBackupCodesParams ¶
type GenerateBackupCodesParams struct {
// UserID identifies the user requesting new backup codes (required).
UserID string `json:"user_id"`
// Password is an optional password check.
Password string `json:"password,omitempty"`
}
GenerateBackupCodesParams defines parameters to regenerate a fresh set of single-use backup codes.
type GetTOTPURIParams ¶
type GetTOTPURIParams struct {
// UserID identifies the enrolled user (required).
UserID string `json:"user_id"`
// Password is an optional password check.
Password string `json:"password,omitempty"`
}
GetTOTPURIParams defines parameters to retrieve the TOTP URI for an already configured user.
type OTPChallenge ¶
type OTPChallenge struct {
// Key is the unique challenge storage key (e.g. "2fa-otp-<userID>").
Key string `json:"key"`
// UserID is the recipient user's unique identifier.
UserID string `json:"user_id"`
// CodeHash is the generated numeric OTP challenge code.
CodeHash string `json:"code_hash"`
// Attempts tracks the number of failed verification tries against this specific challenge.
Attempts int `json:"attempts"`
// ExpiresAt specifies the exact timestamp after which this challenge is invalid.
ExpiresAt time.Time `json:"expires_at"`
}
OTPChallenge represents a temporary, short-lived one-time challenge delivered via SMS or Email.
type Option ¶
type Option func(*Config)
Option defines a functional option for configuring the TwoFactor plugin.
func WithAccountLockout ¶ added in v0.7.0
WithAccountLockout configures the full AccountLockout settings.
func WithAlgorithm ¶ added in v0.7.0
func WithAlgorithm(alg TOTPAlgorithm) Option
WithAlgorithm sets the cryptographic hashing algorithm for TOTP calculations (SHA1, SHA256, SHA512).
func WithAllowPasswordless ¶
WithAllowPasswordless allows 2FA operations without requiring prior user password verification.
func WithBackupCodeOptions ¶
WithBackupCodeOptions sets the quantity and character length of single-use backup codes generated during 2FA setup.
func WithChallengeExpiry ¶ added in v0.7.0
WithChallengeExpiry sets the expiration duration for temporary sign-in 2FA challenge tokens.
func WithIssuer ¶
WithIssuer sets the issuer name displayed in authenticator applications (e.g. "My Company ERP").
func WithLockoutProtection ¶
WithLockoutProtection configures the maximum allowed failed attempts before rate limiting locks the account, and the lockout penalty duration.
func WithOTPOptions ¶ added in v0.7.0
WithOTPOptions configures the number of digits and validity period for temporary challenge OTP codes.
func WithSendOTP ¶
func WithSendOTP(fn SendOTPFunc) Option
WithSendOTP registers the delivery callback function used to dispatch temporary challenge OTP codes via SMS or Email.
func WithSkipVerificationOnEnable ¶
WithSkipVerificationOnEnable marks 2FA as actively enforced immediately upon secret generation.
func WithTOTPOptions ¶
WithTOTPOptions configures the number of digits (6 or 8) and rotation period in seconds for RFC 6238 TOTP codes.
type Plugin ¶
type Plugin struct {
// contains filtered or unexported fields
}
Plugin implements pure Go Two-Factor Authentication capabilities.
func New ¶
func New(repo Repository, opts ...Option) *Plugin
New creates a new TwoFactor plugin instance with the specified repository and functional options.
func (*Plugin) CreateChallenge ¶ added in v0.7.0
func (p *Plugin) CreateChallenge(ctx context.Context, params CreateChallengeParams) (*ChallengeResult, error)
CreateChallenge generates a short-lived sign-in challenge token following primary credentials verification.
func (*Plugin) Disable ¶
func (p *Plugin) Disable(ctx context.Context, params DisableParams) error
Disable removes 2FA configuration for the given user, revokes all trusted devices, and deactivates 2FA.
func (*Plugin) Enable ¶
func (p *Plugin) Enable(ctx context.Context, params EnableParams) (*EnableResult, error)
Enable initializes 2FA enrollment for a user, generating a secure Base32 TOTP secret and recovery backup codes.
func (*Plugin) GenerateBackupCodes ¶
func (p *Plugin) GenerateBackupCodes(ctx context.Context, params GenerateBackupCodesParams) (*BackupCodesResult, error)
GenerateBackupCodes regenerates a fresh set of single-use recovery codes, invalidating prior ones.
func (*Plugin) GenerateTOTPSecret ¶
Convenience Methods
func (*Plugin) GetTOTPURI ¶
GetTOTPURI retrieves the TOTP setup URI for an already configured user.
func (*Plugin) RevokeAllTrustedDevices ¶ added in v0.7.0
RevokeAllTrustedDevices invalidates all authorized devices for the specified user.
func (*Plugin) RevokeTrustedDevice ¶ added in v0.7.0
func (p *Plugin) RevokeTrustedDevice(ctx context.Context, params RevokeTrustedDeviceParams) error
RevokeTrustedDevice revokes authorization for a single trusted client device.
func (*Plugin) SendOTP ¶
func (p *Plugin) SendOTP(ctx context.Context, params SendOTPParams) (*SendOTPResult, error)
SendOTP generates a short-lived numeric challenge and triggers the registered SendOTP callback and EventBus.
func (*Plugin) TrustDevice ¶ added in v0.7.0
func (p *Plugin) TrustDevice(ctx context.Context, params TrustDeviceParams) (*TrustDeviceResult, error)
TrustDevice explicitly authorizes a client device for the configured trust duration.
func (*Plugin) VerifyBackupCode ¶
func (p *Plugin) VerifyBackupCode(ctx context.Context, params VerifyBackupCodeParams) (*VerifyResult, error)
VerifyBackupCode verifies and atomically consumes a single-use backup recovery code.
func (*Plugin) VerifyChallenge ¶ added in v0.7.0
func (p *Plugin) VerifyChallenge(ctx context.Context, params VerifyChallengeParams) (*VerifyResult, error)
VerifyChallenge validates a sign-in challenge token using the requested method (TOTP, Backup Code, OTP).
func (*Plugin) VerifyCode ¶
func (*Plugin) VerifyOTP ¶
func (p *Plugin) VerifyOTP(ctx context.Context, params VerifyOTPParams) (*VerifyResult, error)
VerifyOTP validates a user-submitted code against an active OTP challenge.
func (*Plugin) VerifyTOTP ¶
func (p *Plugin) VerifyTOTP(ctx context.Context, params VerifyTOTPParams) (*VerifyResult, error)
VerifyTOTP validates a user-provided RFC 6238 TOTP code against their stored secret with a ±1 period drift window.
func (*Plugin) VerifyTrustDevice ¶ added in v0.7.0
func (p *Plugin) VerifyTrustDevice(ctx context.Context, params VerifyTrustDeviceParams) (bool, error)
VerifyTrustDevice validates whether an authorized device token is authentic and currently unexpired.
func (*Plugin) ViewBackupCodes ¶
func (p *Plugin) ViewBackupCodes(ctx context.Context, params ViewBackupCodesParams) (*BackupCodesResult, error)
ViewBackupCodes returns the list of active unconsumed single-use backup codes.
type Repository ¶
type Repository interface {
// FindByUserID retrieves the 2FA configuration record for a given user ID.
//
// Function:
// Used during TOTP validation, backup code verification, and viewing active backup codes.
//
// Arguments:
// - ctx: Request cancellation context.
// - userID: The unique user identifier to look up.
//
// Returns:
// - *TwoFactor: The populated TwoFactor configuration entity.
// - error: ErrTwoFactorNotEnabled if no record exists, or database error on failure.
//
// Example SQL:
// SELECT id, user_id, secret, backup_codes, verified, failures, locked_until, created_at, updated_at
// FROM two_factors WHERE user_id = $1 LIMIT 1;
FindByUserID(ctx context.Context, userID string) (*TwoFactor, error)
// Create persists a new TwoFactor entity in storage.
//
// Function:
// Called during Enable when initializing 2FA enrollment for a user.
//
// Arguments:
// - ctx: Request cancellation context.
// - tf: The newly initialized TwoFactor struct.
//
// Returns:
// - error: Nil on success, or database error on failure.
//
// Example SQL:
// INSERT INTO two_factors (id, user_id, secret, backup_codes, verified, failures, locked_until, created_at, updated_at)
// VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
Create(ctx context.Context, tf *TwoFactor) error
// Update modifies an existing TwoFactor record in storage.
//
// Function:
// Called after consuming a backup code, regenerating backup codes, updating failure counts,
// setting lockout expiration, or marking enrollment as verified.
//
// Arguments:
// - ctx: Request cancellation context.
// - tf: The modified TwoFactor struct.
//
// Returns:
// - error: Nil on success, or database error on failure.
//
// Example SQL:
// UPDATE two_factors SET secret = $1, backup_codes = $2, verified = $3, failures = $4, locked_until = $5, updated_at = $6
// WHERE user_id = $7;
Update(ctx context.Context, tf *TwoFactor) error
// DeleteByUserID removes 2FA configuration for a user ID when disabling 2FA.
//
// Function:
// Called during Disable to completely purge 2FA credentials for the user.
//
// Arguments:
// - ctx: Request cancellation context.
// - userID: The target user's ID.
//
// Returns:
// - error: Nil on success, or database error on failure.
//
// Example SQL:
// DELETE FROM two_factors WHERE user_id = $1;
DeleteByUserID(ctx context.Context, userID string) error
// SaveOTPChallenge stores or updates a short-lived challenge code.
//
// Function:
// Called during SendOTP when creating a new numeric challenge, or during VerifyOTP when incrementing failed attempts.
//
// Arguments:
// - ctx: Request cancellation context.
// - challenge: The OTPChallenge entity to persist or update.
//
// Returns:
// - error: Nil on success, or database error on failure.
//
// Example SQL:
// INSERT INTO otp_challenges (key, user_id, code_hash, attempts, expires_at)
// VALUES ($1, $2, $3, $4, $5) ON CONFLICT (key) DO UPDATE SET attempts = $4;
SaveOTPChallenge(ctx context.Context, challenge *OTPChallenge) error
// GetOTPChallenge retrieves an active challenge by its composite key.
//
// Function:
// Called during VerifyOTP to compare the user's submitted challenge code and verify expiration.
//
// Arguments:
// - ctx: Request cancellation context.
// - key: The composite challenge key (e.g. "2fa-otp-<userID>").
//
// Returns:
// - *OTPChallenge: The matching challenge entity.
// - error: ErrOTPExpired if no active challenge matches, or database error on failure.
//
// Example SQL:
// SELECT key, user_id, code_hash, attempts, expires_at FROM otp_challenges WHERE key = $1 LIMIT 1;
GetOTPChallenge(ctx context.Context, key string) (*OTPChallenge, error)
// DeleteOTPChallenge deletes a consumed or expired OTP challenge.
//
// Function:
// Called upon successful verification (single-use consumption) or when maximum attempts are exceeded.
//
// Arguments:
// - ctx: Request cancellation context.
// - key: The composite challenge key to delete.
//
// Returns:
// - error: Nil on success, or database error on failure.
//
// Example SQL:
// DELETE FROM otp_challenges WHERE key = $1;
DeleteOTPChallenge(ctx context.Context, key string) error
// SaveTrustDevice stores or updates an authorized trusted device record.
//
// Function:
// Called when a user marks "Trust this device" during 2FA verification or calls TrustDevice.
//
// Arguments:
// - ctx: Request cancellation context.
// - record: The TrustDeviceRecord to insert or update.
//
// Returns:
// - error: Nil on success, or database error on failure.
//
// Example SQL:
// INSERT INTO trusted_devices (id, user_id, device_id, token_hash, expires_at, created_at)
// VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (user_id, device_id) DO UPDATE SET token_hash = $4, expires_at = $5;
SaveTrustDevice(ctx context.Context, record *TrustDeviceRecord) error
// FindTrustDevice retrieves an authorized device record by user ID and device ID.
//
// Function:
// Called during VerifyTrustDevice or challenge creation to check if 2FA can be safely bypassed.
//
// Arguments:
// - ctx: Request cancellation context.
// - userID: Target user ID.
// - deviceID: Target client hardware/device ID.
//
// Returns:
// - *TrustDeviceRecord: The matching record.
// - error: ErrInvalidDeviceToken if not found or expired, or database error.
//
// Example SQL:
// SELECT id, user_id, device_id, token_hash, expires_at, created_at
// FROM trusted_devices WHERE user_id = $1 AND device_id = $2 LIMIT 1;
FindTrustDevice(ctx context.Context, userID, deviceID string) (*TrustDeviceRecord, error)
// DeleteTrustDevice revokes trust for a single device.
//
// Function:
// Called during RevokeTrustedDevice to unauthorize a specific client device.
//
// Arguments:
// - ctx: Request cancellation context.
// - userID: Owner user ID.
// - deviceID: Device identifier to unauthorize.
//
// Returns:
// - error: Nil on success, or database error on failure.
//
// Example SQL:
// DELETE FROM trusted_devices WHERE user_id = $1 AND device_id = $2;
DeleteTrustDevice(ctx context.Context, userID, deviceID string) error
// DeleteTrustDevicesByUserID revokes all authorized devices for a user.
//
// Function:
// Called during Disable or security credential reset to invalidate all trusted client sessions.
//
// Arguments:
// - ctx: Request cancellation context.
// - userID: Target user ID.
//
// Returns:
// - error: Nil on success, or database error on failure.
//
// Example SQL:
// DELETE FROM trusted_devices WHERE user_id = $1;
DeleteTrustDevicesByUserID(ctx context.Context, userID string) error
// SaveChallenge stores a temporary sign-in challenge token.
//
// Function:
// Called during CreateChallenge after primary login when 2FA is required.
//
// Arguments:
// - ctx: Request cancellation context.
// - challenge: The ChallengeRecord to persist.
//
// Returns:
// - error: Nil on success, or database error on failure.
//
// Example SQL:
// INSERT INTO two_factor_challenges (token, user_id, expires_at, created_at)
// VALUES ($1, $2, $3, $4);
SaveChallenge(ctx context.Context, challenge *ChallengeRecord) error
// GetChallenge retrieves an active sign-in challenge token record.
//
// Function:
// Called during VerifyChallenge to validate challenge validity and expiration.
//
// Arguments:
// - ctx: Request cancellation context.
// - token: The challenge token string.
//
// Returns:
// - *ChallengeRecord: The matching challenge record.
// - error: ErrInvalidChallengeToken if missing, ErrChallengeExpired if past expiration, or database error.
//
// Example SQL:
// SELECT token, user_id, expires_at, created_at
// FROM two_factor_challenges WHERE token = $1 LIMIT 1;
GetChallenge(ctx context.Context, token string) (*ChallengeRecord, error)
// DeleteChallenge removes a consumed or expired sign-in challenge.
//
// Function:
// Called upon successful challenge verification or explicit cancellation.
//
// Arguments:
// - ctx: Request cancellation context.
// - token: The challenge token string to delete.
//
// Returns:
// - error: Nil on success, or database error on failure.
//
// Example SQL:
// DELETE FROM two_factor_challenges WHERE token = $1;
DeleteChallenge(ctx context.Context, token string) error
}
Repository defines the persistent storage contract required by the TwoFactor plugin. Implement this interface on your custom database adapter (e.g. PostgreSQL, MySQL, SQLite, MongoDB, GORM).
Implementation Example (GORM / database/sql): ¶
type GormTwoFactorRepo struct {
db *gorm.DB
}
func (r *GormTwoFactorRepo) FindByUserID(ctx context.Context, userID string) (*twofactor.TwoFactor, error) {
var m TwoFactorModel
if err := r.db.WithContext(ctx).Where("user_id = ?", userID).First(&m).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, twofactor.ErrTwoFactorNotEnabled
}
return nil, err
}
return m.ToEntity(), nil
}
type RevokeTrustedDeviceParams ¶ added in v0.7.0
type RevokeTrustedDeviceParams struct {
// UserID is the owner user identifier (required).
UserID string `json:"user_id"`
// DeviceID is the client hardware/installation identifier to revoke (required).
DeviceID string `json:"device_id"`
}
RevokeTrustedDeviceParams defines parameters to unauthorize a specific client device.
type SendOTPAfterEventPayload ¶
type SendOTPAfterEventPayload struct {
// UserID identifies the target user for the OTP challenge.
UserID string
// OTPCode is the generated numeric challenge code.
OTPCode string
// ExpiresAt specifies the exact expiration time for the OTP challenge.
ExpiresAt time.Time
}
SendOTPAfterEventPayload contains confirmation details after an OTP challenge has been dispatched.
type SendOTPBeforeEventPayload ¶
type SendOTPBeforeEventPayload struct {
// UserID identifies the target user for the OTP challenge.
UserID string
// Params holds the parameters for sending OTP.
Params *SendOTPParams
}
SendOTPBeforeEventPayload contains details before an OTP challenge is created.
type SendOTPFunc ¶
SendOTPFunc defines the callback function signature for dispatching generated OTP challenge codes via SMS or Email.
type SendOTPParams ¶
type SendOTPParams struct {
// UserID identifies the user receiving the OTP challenge (required).
UserID string `json:"user_id"`
// Extra holds dynamic metadata passed through event interceptors (optional).
Extra map[string]any `json:"extra,omitempty"`
}
SendOTPParams defines parameters to trigger an SMS or Email OTP challenge.
func (*SendOTPParams) Set ¶ added in v0.7.0
func (p *SendOTPParams) Set(key string, value any)
type SendOTPResult ¶ added in v0.7.0
type SendOTPResult struct {
// ExpiresAt specifies the exact timestamp when the dispatched challenge expires.
ExpiresAt time.Time `json:"expires_at"`
}
SendOTPResult contains metadata about the dispatched OTP challenge.
type TOTPAlgorithm ¶ added in v0.7.0
type TOTPAlgorithm string
TOTPAlgorithm defines the supported cryptographic hashing algorithm for RFC 6238 TOTP calculations.
const ( // AlgorithmSHA1 represents HMAC-SHA1 (RFC 6238 default). AlgorithmSHA1 TOTPAlgorithm = "SHA1" // AlgorithmSHA256 represents HMAC-SHA256. AlgorithmSHA256 TOTPAlgorithm = "SHA256" // AlgorithmSHA512 represents HMAC-SHA512. AlgorithmSHA512 TOTPAlgorithm = "SHA512" )
type TOTPGeneratedEventPayload ¶
type TOTPGeneratedEventPayload struct {
// UserID identifies the user for whom the secret was created.
UserID string
// Secret is the Base32-encoded TOTP secret.
Secret string
}
TOTPGeneratedEventPayload contains the raw secret generated during 2FA setup.
type TrustDeviceParams ¶ added in v0.7.0
type TrustDeviceParams struct {
// UserID is the owner user identifier (required).
UserID string `json:"user_id"`
// DeviceID is the unique client hardware/installation identifier (required).
DeviceID string `json:"device_id"`
}
TrustDeviceParams defines parameters to explicitly trust a client device.
type TrustDeviceRecord ¶ added in v0.7.0
type TrustDeviceRecord struct {
// ID is the primary key identifier for the trusted device entry.
ID string `json:"id"`
// UserID is the owner user's unique identifier.
UserID string `json:"user_id"`
// DeviceID is the unique client hardware or browser installation identifier.
DeviceID string `json:"device_id"`
// TokenHash is the cryptographic hash or signature of the trusted device token.
TokenHash string `json:"token_hash"`
// ExpiresAt specifies when this device trust authorization expires.
ExpiresAt time.Time `json:"expires_at"`
// CreatedAt is the timestamp when the device was initially authorized.
CreatedAt time.Time `json:"created_at"`
}
TrustDeviceRecord stores a persistent authorization record for a recognized client device.
type TrustDeviceResult ¶ added in v0.7.0
type TrustDeviceResult struct {
// Token is the signed cryptographic authorization token.
Token string `json:"token"`
// ExpiresAt specifies the timestamp after which this device trust expires.
ExpiresAt time.Time `json:"expires_at"`
}
TrustDeviceResult contains the issued cryptographic device token and its expiration.
type TwoFactor ¶
type TwoFactor struct {
// ID is the unique database record identifier.
ID string `json:"id"`
// UserID uniquely identifies the owner user of this 2FA configuration.
UserID string `json:"user_id"`
// Secret is the Base32-encoded cryptographic secret used for TOTP calculation.
Secret string `json:"secret"`
// BackupCodes is a serialized JSON array containing unconsumed single-use backup codes (e.g. `["CODE1", "CODE2"]`).
BackupCodes string `json:"backup_codes"`
// Verified indicates whether initial TOTP verification has succeeded and 2FA is actively enforced.
Verified bool `json:"verified"`
// Failures tracks the number of consecutive failed verification attempts.
Failures int `json:"failures"`
// LockedUntil specifies the timestamp until which 2FA operations are locked due to rate limiting (nil if unlocked).
LockedUntil *time.Time `json:"locked_until"`
// CreatedAt records the timestamp when 2FA enrollment was initialized.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt records the timestamp when 2FA settings were last modified.
UpdatedAt time.Time `json:"updated_at"`
}
TwoFactor represents the persistent storage entity containing a user's 2FA configuration, secrets, and security state.
type VerifyBackupCodeParams ¶
type VerifyBackupCodeParams struct {
// UserID identifies the user attempting backup code recovery (required).
UserID string `json:"user_id"`
// Code is the alphanumeric single-use recovery code (required).
Code string `json:"code"`
// Extra holds dynamic metadata passed through event interceptors (optional).
Extra map[string]any `json:"extra,omitempty"`
}
VerifyBackupCodeParams defines parameters to verify and consume a single-use backup code.
func (*VerifyBackupCodeParams) Get ¶ added in v0.7.0
func (p *VerifyBackupCodeParams) Get(key string) (any, bool)
func (*VerifyBackupCodeParams) Set ¶ added in v0.7.0
func (p *VerifyBackupCodeParams) Set(key string, value any)
type VerifyChallengeParams ¶ added in v0.7.0
type VerifyChallengeParams struct {
// ChallengeToken is the temporary challenge token issued during sign-in (required).
ChallengeToken string `json:"challenge_token"`
// Method specifies the verification method ("totp", "backup_code", "otp") (required).
Method string `json:"method"`
// Code is the verification code (TOTP numeric code, backup alphanumeric string, or OTP code) (required).
Code string `json:"code"`
// TrustDevice indicates whether to trust this device upon successful verification.
TrustDevice bool `json:"trust_device,omitempty"`
// DeviceID specifies the client device identifier.
DeviceID string `json:"device_id,omitempty"`
// Extra holds dynamic metadata passed through event interceptors (optional).
Extra map[string]any `json:"extra,omitempty"`
}
VerifyChallengeParams defines parameters to verify a sign-in challenge token using TOTP, Backup Code, or OTP.
func (*VerifyChallengeParams) Get ¶ added in v0.7.0
func (p *VerifyChallengeParams) Get(key string) (any, bool)
func (*VerifyChallengeParams) Set ¶ added in v0.7.0
func (p *VerifyChallengeParams) Set(key string, value any)
type VerifyFailedEventPayload ¶ added in v0.7.0
type VerifyFailedEventPayload struct {
// UserID identifies the user attempting verification.
UserID string
// Method is the authentication method attempted ("totp", "backup_code", "otp").
Method string
// Failures is the current consecutive failed attempt count.
Failures int
}
VerifyFailedEventPayload reports details of a failed verification attempt.
type VerifyOTPParams ¶
type VerifyOTPParams struct {
// UserID identifies the user submitting the challenge verification code (required).
UserID string `json:"user_id"`
// Code is the numeric challenge code delivered to the user (required).
Code string `json:"code"`
// Extra holds dynamic metadata passed through event interceptors (optional).
Extra map[string]any `json:"extra,omitempty"`
}
VerifyOTPParams defines parameters to verify an active OTP challenge.
func (*VerifyOTPParams) Set ¶ added in v0.7.0
func (p *VerifyOTPParams) Set(key string, value any)
type VerifyResult ¶ added in v0.7.0
type VerifyResult struct {
// Success indicates whether the submitted verification credential was accepted.
Success bool `json:"success"`
// UserID is the owner user's identifier.
UserID string `json:"user_id"`
// Method specifies the authentication method verified ("totp", "backup_code", "otp").
Method string `json:"method"`
// TrustDeviceToken contains the signed device authorization token if TrustDevice was requested and succeeded.
TrustDeviceToken string `json:"trust_device_token,omitempty"`
// RemainingCodes reports the count of unconsumed backup recovery codes (populated on backup_code verification).
RemainingCodes int `json:"remaining_codes,omitempty"`
}
VerifyResult represents the comprehensive result of any successful 2FA verification.
type VerifySuccessEventPayload ¶ added in v0.7.0
type VerifySuccessEventPayload struct {
// UserID identifies the user who verified 2FA.
UserID string
// Method is the authentication method used ("totp", "backup_code", "otp").
Method string
// TrustDevice indicates if the device was trusted during verification.
TrustDevice bool
}
VerifySuccessEventPayload reports details of a successful 2FA verification.
type VerifyTOTPParams ¶
type VerifyTOTPParams struct {
// UserID identifies the user submitting the verification code (required).
UserID string `json:"user_id"`
// Code is the numeric TOTP code generated by an authenticator application (required).
Code string `json:"code"`
// TrustDevice indicates whether the client requests authorizing this device to bypass subsequent 2FA prompts.
TrustDevice bool `json:"trust_device,omitempty"`
// DeviceID specifies the unique client hardware/installation identifier required when TrustDevice is true.
DeviceID string `json:"device_id,omitempty"`
// Extra holds dynamic metadata passed through event interceptors (optional).
Extra map[string]any `json:"extra,omitempty"`
}
VerifyTOTPParams defines parameters to verify an incoming 6- or 8-digit TOTP code.
func (*VerifyTOTPParams) Get ¶ added in v0.7.0
func (p *VerifyTOTPParams) Get(key string) (any, bool)
func (*VerifyTOTPParams) Set ¶ added in v0.7.0
func (p *VerifyTOTPParams) Set(key string, value any)
type VerifyTrustDeviceParams ¶ added in v0.7.0
type VerifyTrustDeviceParams struct {
// UserID is the owner user identifier (required).
UserID string `json:"user_id"`
// DeviceID is the unique client hardware/installation identifier (required).
DeviceID string `json:"device_id"`
// Token is the cryptographic token previously issued to this device (required).
Token string `json:"token"`
}
VerifyTrustDeviceParams defines parameters to test if a device token is currently valid.
type ViewBackupCodesParams ¶
type ViewBackupCodesParams struct {
// UserID identifies the user querying their backup codes (required).
UserID string `json:"user_id"`
}
ViewBackupCodesParams defines parameters to retrieve active unconsumed backup codes.