lastloginmethod

package
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
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"
)
View Source
const DefaultCookieName = "better-auth.last_used_login_method"

DefaultCookieName is the standard cookie key used by better-auth to track the last login method.

View Source
const DefaultMaxAge = 30 * 24 * time.Hour

DefaultMaxAge defines the default cookie expiration duration (30 days).

View Source
const PluginID = "last-login-method"

PluginID is the unique string identifier for the LastLoginMethod plugin ("last-login-method").

Variables

View Source
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

func GetLastUsedLoginMethod(r *http.Request, cookieName string) string

GetLastUsedLoginMethod extracts the last used login method from incoming HTTP request cookies.

func ResolveMethod

func ResolveMethod(ctx context.Context, r *http.Request, cfg Config) (string, bool)

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

type BeforeStoreCookieFunc func(ctx context.Context, r *http.Request, method string) (bool, error)

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

func WithCookieAttributes(domain, path string, sameSite http.SameSite, secure bool) Option

WithCookieAttributes sets cookie domain, path, SameSite, and Secure flags.

func WithCookieName

func WithCookieName(name string) Option

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

func WithDisableDefaultRoutes(disable bool) Option

WithDisableDefaultRoutes configures whether built-in route heuristics are disabled.

func WithMaxAge

func WithMaxAge(d time.Duration) Option

WithMaxAge sets a custom cookie duration.

func WithRouteMapping

func WithRouteMapping(pathPattern, method string) Option

WithRouteMapping adds or overrides a custom path pattern to authentication method mapping.

func WithRouteMappings

func WithRouteMappings(routes map[string]string) Option

WithRouteMappings sets a batch of custom path pattern to authentication method mappings.

func WithStoreInDatabase

func WithStoreInDatabase(store bool) Option

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

func New(opts ...Option) *Plugin

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) Config

func (p *Plugin) Config() Config

Config returns a copy of the active plugin configuration.

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) ID

func (p *Plugin) ID() string

ID returns the unique string identifier for the plugin ("last-login-method").

func (*Plugin) Init

func (p *Plugin) Init(ctx *plugin.Context) error

Init initializes the plugin with the shared execution context.

func (*Plugin) Middleware

func (p *Plugin) Middleware() func(next http.Handler) http.Handler

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).

func (*Plugin) ProcessLoginMethod

func (p *Plugin) ProcessLoginMethod(ctx context.Context, w http.ResponseWriter, r *http.Request, userID string, overrideMethod string) (string, error)

ProcessLoginMethod handles method resolution, GDPR consent evaluation, cookie issuance, and DB persistence.

func (*Plugin) SetLastLoginMethod

func (p *Plugin) SetLastLoginMethod(ctx context.Context, w http.ResponseWriter, r *http.Request, userID, method string) (string, error)

SetLastLoginMethod explicitly records a user's last login method (Cookie + DB if enabled).

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

type ResolveMethodFunc func(ctx context.Context, r *http.Request) (string, bool)

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.

Jump to

Keyboard shortcuts

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