Documentation
¶
Index ¶
- Constants
- Variables
- func ClearLastUsedLoginMethod(w http.ResponseWriter, cfg Config)
- func GetLastUsedLoginMethod(r *http.Request, cookieName string) string
- func ResolveMethod(ctx context.Context, r *http.Request, cfg Config) (string, bool)
- func SetLastLoginMethodCookie(w http.ResponseWriter, method string, cfg Config)
- type BeforeStoreCookieFunc
- type Config
- type LastLoginMethodEventPayload
- type MemoryRepository
- type Option
- func WithBeforeStoreCookie(fn BeforeStoreCookieFunc) Option
- func WithCookieAttributes(domain, path string, sameSite http.SameSite, secure bool) Option
- func WithCookieName(name string) Option
- func WithCustomResolver(fn ResolveMethodFunc) Option
- func WithDisableDefaultRoutes(disable bool) Option
- func WithMaxAge(d time.Duration) Option
- func WithRouteMapping(pathPattern, method string) Option
- func WithRouteMappings(routes map[string]string) Option
- func WithStoreInDatabase(store bool) Option
- type Plugin
- func (p *Plugin) ClearLastLoginMethod(ctx context.Context, w http.ResponseWriter)
- func (p *Plugin) Config() Config
- func (p *Plugin) GetLastLoginMethod(ctx context.Context, r *http.Request, userID string) (string, error)
- func (p *Plugin) ID() string
- func (p *Plugin) Init(ctx *plugin.Context) error
- func (p *Plugin) Middleware() func(next http.Handler) http.Handler
- func (p *Plugin) ProcessLoginMethod(ctx context.Context, w http.ResponseWriter, r *http.Request, userID string, ...) (string, error)
- func (p *Plugin) SetLastLoginMethod(ctx context.Context, w http.ResponseWriter, r *http.Request, ...) (string, error)
- type Repository
- type ResolveMethodFunc
- type SetLastLoginMethodParams
Constants ¶
const ( // EventLastLoginMethodSet is emitted whenever a user's last login method is successfully updated and stored. EventLastLoginMethodSet = "lastloginmethod:set" // EventLastLoginMethodCleared is emitted whenever the last login method cookie is cleared. EventLastLoginMethodCleared = "lastloginmethod:cleared" )
const DefaultCookieName = "modular-auth.last_used_login_method"
DefaultCookieName is the standard cookie key used by modular-auth to track the last login method.
const DefaultMaxAge = 30 * 24 * time.Hour
DefaultMaxAge defines the default cookie expiration duration (30 days).
const PluginID = "last-login-method"
PluginID is the unique string identifier for the LastLoginMethod plugin ("last-login-method").
Variables ¶
var ( // ErrMethodNotResolved is returned when no login method can be inferred from the request path or context. ErrMethodNotResolved = errors.New("lastloginmethod: authentication method could not be resolved") // ErrUserNotFound is returned when no user record matches the queried user ID. ErrUserNotFound = errors.New("lastloginmethod: user not found") // ErrRepositoryRequired is returned when database persistence is enabled but no Repository is configured. ErrRepositoryRequired = errors.New("lastloginmethod: repository is required when storeInDatabase is enabled") )
Functions ¶
func ClearLastUsedLoginMethod ¶
func ClearLastUsedLoginMethod(w http.ResponseWriter, cfg Config)
ClearLastUsedLoginMethod expires and deletes the last login method cookie.
func GetLastUsedLoginMethod ¶
GetLastUsedLoginMethod extracts the last used login method from incoming HTTP request cookies.
func ResolveMethod ¶
ResolveMethod inspects the current request (Path, Query, Params), custom route mappings, and custom resolvers to infer the authentication method used.
func SetLastLoginMethodCookie ¶
func SetLastLoginMethodCookie(w http.ResponseWriter, method string, cfg Config)
SetLastLoginMethodCookie sets the last login method cookie on the HTTP response writer. Note: HttpOnly is explicitly set to false to allow client-side JavaScript access.
Types ¶
type BeforeStoreCookieFunc ¶
BeforeStoreCookieFunc defines the signature for GDPR consent and pre-cookie storage interceptors. If it returns false or an error, cookie storage is skipped without aborting the authentication session.
type Config ¶
type Config struct {
// CookieName specifies the key for storing the last used login method cookie.
// Default: "modular-auth.last_used_login_method"
CookieName string
// MaxAge specifies the cookie duration.
// Default: 30 days
MaxAge time.Duration
// Domain specifies the cookie domain.
Domain string
// Path specifies the cookie path. Default: "/"
Path string
// SameSite specifies the cookie SameSite attribute. Default: http.SameSiteLaxMode
SameSite http.SameSite
// Secure specifies whether the cookie requires HTTPS. Default: false
Secure bool
// StoreInDatabase specifies whether the resolved login method should also be persisted in the DB via Repository.
// Default: false
StoreInDatabase bool
// CustomRoutes specifies custom path-to-method mappings (e.g. "/auth/sso/callback" -> "saml").
CustomRoutes map[string]string
// DisableDefaultRoutes specifies whether built-in route heuristics should be disabled.
DisableDefaultRoutes bool
// CustomResolver is an optional custom resolver function for inferring login methods from requests.
CustomResolver ResolveMethodFunc
// BeforeStoreCookie is an optional GDPR consent check callback before issuing the cookie.
BeforeStoreCookie BeforeStoreCookieFunc
}
Config defines the configuration parameters for the LastLoginMethod plugin.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config struct initialized with recommended defaults.
type LastLoginMethodEventPayload ¶
type LastLoginMethodEventPayload struct {
UserID string `json:"userId,omitempty"`
Method string `json:"method"`
CookieStored bool `json:"cookieStored"`
DBStored bool `json:"dbStored"`
Extra map[string]any `json:"extra,omitempty"`
}
LastLoginMethodEventPayload contains payload data dispatched with last login method lifecycle events.
type MemoryRepository ¶ added in v0.26.0
type MemoryRepository struct {
// contains filtered or unexported fields
}
MemoryRepository provides a thread-safe, in-memory implementation of Repository for testing and lightweight usage.
func NewMemoryRepository ¶ added in v0.26.0
func NewMemoryRepository() *MemoryRepository
NewMemoryRepository initializes a fresh MemoryRepository instance.
func (*MemoryRepository) GetLastLoginMethod ¶ added in v0.26.0
GetLastLoginMethod retrieves a user's last login method from memory.
func (*MemoryRepository) UpdateLastLoginMethod ¶ added in v0.26.0
func (r *MemoryRepository) UpdateLastLoginMethod(_ context.Context, userID string, method string) error
UpdateLastLoginMethod stores a user's last login method in memory.
type Option ¶
type Option func(*Config)
Option defines a functional option type for configuring the plugin.
func WithBeforeStoreCookie ¶
func WithBeforeStoreCookie(fn BeforeStoreCookieFunc) Option
WithBeforeStoreCookie configures a GDPR consent check callback before storing the cookie.
func WithCookieAttributes ¶
WithCookieAttributes sets cookie domain, path, SameSite, and Secure flags.
func WithCookieName ¶
WithCookieName sets a custom cookie name for tracking last login method.
func WithCustomResolver ¶
func WithCustomResolver(fn ResolveMethodFunc) Option
WithCustomResolver configures a custom method resolver callback.
func WithDisableDefaultRoutes ¶
WithDisableDefaultRoutes configures whether built-in route heuristics are disabled.
func WithRouteMapping ¶
WithRouteMapping adds or overrides a custom path pattern to authentication method mapping.
func WithRouteMappings ¶
WithRouteMappings sets a batch of custom path pattern to authentication method mappings.
func WithStoreInDatabase ¶
WithStoreInDatabase enables or disables DB persistence of last_login_method.
type Plugin ¶
type Plugin struct {
// contains filtered or unexported fields
}
Plugin implements the last login method tracking plugin for go-modular-auth.
func New ¶
New instantiates a new LastLoginMethod plugin configured with optional Repository and functional options.
func NewWithRepository ¶
func NewWithRepository(repo Repository, opts ...Option) *Plugin
NewWithRepository instantiates a new LastLoginMethod plugin configured with a Repository implementation.
func (*Plugin) ClearLastLoginMethod ¶
func (p *Plugin) ClearLastLoginMethod(ctx context.Context, w http.ResponseWriter)
ClearLastLoginMethod expires the cookie and publishes the cleared event.
func (*Plugin) GetLastLoginMethod ¶
func (p *Plugin) GetLastLoginMethod(ctx context.Context, r *http.Request, userID string) (string, error)
GetLastLoginMethod retrieves the last used login method from HTTP request cookies or DB.
func (*Plugin) Middleware ¶
Middleware returns a net/http middleware handler to automatically intercept HTTP responses, resolve the login method based on configured route rules, and emit the cookie (and DB update if enabled) upon successful authentication responses (HTTP 2xx).
type Repository ¶
type Repository interface {
// UpdateLastLoginMethod persists the authentication method used by the specified user.
//
// Function:
// Called after successful user authentication to store the last used login method (e.g. "email_password", "passkey", "google").
//
// Storage:
// Database (GORM / SQL) - Updates last_login_method column on users table.
//
// Arguments:
// - ctx: Request cancellation context.
// - userID: Target user primary key ID.
// - method: Identifier string of the login method used.
//
// Returns:
// - error: Nil on success, ErrUserNotFound if missing, or database error.
//
// Example SQL:
// UPDATE users SET last_login_method = $1, updated_at = NOW() WHERE id = $2;
UpdateLastLoginMethod(ctx context.Context, userID string, method string) error
// GetLastLoginMethod retrieves the last used authentication method for the specified user.
//
// Function:
// Used to pre-select or highlight the user's preferred login method on sign-in screens.
//
// Storage:
// Database (GORM / SQL) - Query last_login_method column by user ID.
//
// Arguments:
// - ctx: Request cancellation context.
// - userID: Target user primary key ID.
//
// Returns:
// - string: Method identifier string if set (e.g. "email_password", "passkey", "google").
// - error: Nil on success, ErrUserNotFound if missing, or database error.
//
// Example SQL:
// SELECT last_login_method FROM users WHERE id = $1 LIMIT 1;
GetLastLoginMethod(ctx context.Context, userID string) (string, error)
}
Repository defines the persistent storage contract required by the LastLoginMethod plugin. Implement this interface on your custom database adapter (e.g. PostgreSQL, MySQL, SQLite, MongoDB, GORM).
Implementation Example (GORM / database/sql): ¶
type GormLastLoginMethodRepository struct {
db *gorm.DB
}
func (r *GormLastLoginMethodRepository) UpdateLastLoginMethod(ctx context.Context, userID string, method string) error {
res := r.db.WithContext(ctx).Model(&entity.User{}).Where("id = ?", userID).Update("last_login_method", method)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return lastloginmethod.ErrUserNotFound
}
return nil
}
func (r *GormLastLoginMethodRepository) GetLastLoginMethod(ctx context.Context, userID string) (string, error) {
var method string
if err := r.db.WithContext(ctx).Model(&entity.User{}).Where("id = ?", userID).Pluck("last_login_method", &method).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return "", lastloginmethod.ErrUserNotFound
}
return "", err
}
return method, nil
}
type ResolveMethodFunc ¶
ResolveMethodFunc defines the signature for custom authentication method resolvers. It receives the current context and HTTP request, returning the resolved method name and a boolean indicating success.
type SetLastLoginMethodParams ¶
type SetLastLoginMethodParams struct {
UserID string `json:"userId"`
Method string `json:"method"`
}
SetLastLoginMethodParams contains parameters for explicitly setting or updating a user's last login method.