lastloginmethod

package
v0.27.2 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 8 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 = "modular-auth.last_used_login_method"

DefaultCookieName is the standard cookie key used by modular-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 (
	// 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

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: "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

func (r *MemoryRepository) GetLastLoginMethod(_ context.Context, userID string) (string, error)

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

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

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