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 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 = "better-auth.last_used_login_method"
DefaultCookieName is the standard cookie key used by better-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 ( // ErrRepositoryRequired is returned when StoreInDatabase is true but no Repository implementation is provided. ErrRepositoryRequired = errors.New("lastloginmethod: repository instance required when StoreInDatabase is enabled") // ErrMethodNotResolved is returned when the login method cannot be inferred from the request. ErrMethodNotResolved = errors.New("lastloginmethod: unable to resolve login method from request") // ErrUserNotFound is returned when attempting to update or retrieve last login method for a nonexistent user. ErrUserNotFound = errors.New("lastloginmethod: user not found") )
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: "better-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 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.
UpdateLastLoginMethod(ctx context.Context, userID string, method string) error
// GetLastLoginMethod retrieves the last used authentication method for the specified user.
GetLastLoginMethod(ctx context.Context, userID string) (string, error)
}
Repository defines the persistence contract for updating and retrieving a user's last used login method.
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.