auth

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 23 Imported by: 0

README ΒΆ

Go Modular Auth Logo

Go Modular Auth

Server-only, transport-agnostic, modular authentication engine for Go.

Go Reference Go Version


1. Objective & Principles

GoModularAuth is a modular, server-only authentication engine for Go. It is built from the ground up on Clean & Hexagonal Architecture to separate domain authentication workflows from infrastructure and web frameworks.

  • Server-Only & Domain-First: Pure domain operations. Zero global state.
  • Transport-Agnostic: The core engine never imports net/http, grpc, fiber, or gin. Transport adapters bridge HTTP requests or gRPC RPCs to core operations.
  • Adapter = Source of Truth: All identities, credentials, accounts, and sessions live in the authoritative schema-driven Database Adapter.
  • Cache = Ephemeral Acceleration: Optional Cache-Aside acceleration with bounded TTLs, post-commit invalidation, and graceful degradation to the Store on cache outage.
  • ACID Cross-Module Transactions: Transactions propagate seamlessly between Core and Plugins via package sqltx.
  • Topological Plugin Graph: Plugins declare dependencies; the engine sorts them topologically and prevents dependency cycles.
  • Enterprise & Modern Auth Ready: 35 official plugins covering WebAuthn Passkeys, TOTP (AAL1/AAL2), OAuth 2.1 Provider, SCIM 2.0, SAML/OIDC SSO, Multi-Tenancy Organizations, Monetization (Stripe/Polar), and AI Agent identities.

πŸ“š Comprehensive Documentation: Complete in-depth guides and API references are available in the doc/ directory.


2. Architecture

                                GoModularAuth Engine
                                         β”‚
             β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
             β”‚                           β”‚                           β”‚
      Transport Adapters             Core Engine                 Plugin SDK &
             β”‚                           β”‚                       35 Plugins
      β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”             β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”                    β”‚
      β”‚             β”‚             β”‚             β”‚             β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”
     HTTP          gRPC        Adapter        Cache          OAuth         2FA
 (Middleware,  (Interceptors,  (Truth)     (Ephemeral)     Passkeys       SCIM
  Extractors)   Metadata)         β”‚             β”‚          Organizations  Admin
                                  β”‚             β”‚           SAML / OIDC   Agents
                                  β–Ό             β–Ό             Billing      ...
                           β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                           β”‚ SQLite       β”‚ β”‚ Redis        β”‚
                           β”‚ PostgreSQL   β”‚ β”‚ Valkey       β”‚
                           β”‚ MySQL        β”‚ β”‚ Memory       β”‚
                           β”‚ SurrealDB    β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚ Memory       β”‚
                           β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

3. Adapters & Plugins Ecosystem

Production Adapters (adapters/)

  • Persistence Stores:
    • adapters/postgres: Production PostgreSQL store with automatic migrations and connection pooling.
    • adapters/sqlite: Production SQLite store (WAL mode, busy timeout support).
    • adapters/mysql: Production MySQL store.
    • adapters/surrealdb: Production SurrealDB multi-model database adapter with dynamic schema generation.
    • adapters/memory: In-memory thread-safe store for unit and integration testing.
  • Caching & Ephemeral State:
    • adapters/redis: Distributed cache and atomic counter for rate limiting.
    • adapters/valkey: High-performance Valkey cache adapter.
    • adapters/memory: In-memory cache with TTL eviction.
  • Transactional Delivery:
    • adapters/smtp: Production SMTP sender supporting TLS, STARTTLS, and multipart/alternative MIME.
    • adapters/memory: In-memory mock sender for testing.
  • Transports:
    • adapters/http: HTTP middleware (Authenticate, RequireSession) and extractors (BearerExtractor, CookieExtractor).
    • adapters/grpc: Unary and streaming gRPC server interceptors with metadata token extractors.

35 Official Plugins (plugins/)

  • Authentication: passkeys (WebAuthn/FIDO2), twofactor (TOTP RFC 6238 + AAL1/AAL2), magic-link, email-otp, phone (SMS OTP), account-linking, username, anonymous.
  • Tokens & Sessions: jwt, bearer, multisession, one-time-token.
  • SSO & Client Protocols: oauth (Google, GitHub, etc.), oidc, saml, sso.
  • Identity Provider (IdP) Servers: oauth-provider (OAuth 2.1 Server with PKCE S256), oidc-provider, saml-provider, scim (SCIM 2.0 Provisioning).
  • Multi-Tenancy & Authorization: organizations, rbac, policy (ABAC engine), admin, api-keys.
  • Autonomous Identities: agent (Autonomous AI agents & MCP client credentials), device-authorization (RFC 8628), service-accounts.
  • Monetization & Subscriptions: stripe (Stripe billing & customer portal), polar (Polar SaaS & benefit licensing).
  • Security & Governance: audit, rate-limit, password-policy, lastlogin, openapi (Spec generator).

4. Installation

go get github.com/BladiCreator/go-modular-auth

Requires Go 1.27+.


5. Quickstart

Production Setup with PostgreSQL, HTTP Middleware & Organizations Plugin

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"net/http"

	_ "github.com/jackc/pgx/v5/stdlib"

	auth "github.com/BladiCreator/go-modular-auth"
	authhttp "github.com/BladiCreator/go-modular-auth/adapters/http"
	"github.com/BladiCreator/go-modular-auth/adapters/postgres"
	"github.com/BladiCreator/go-modular-auth/plugins/organizations"
)

func main() {
	ctx := context.Background()

	// 1. Initialize PostgreSQL database and storage adapter
	db, err := sql.Open("pgx", "postgres://user:pass@localhost:5432/authdb?sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}
	ad := postgres.New(db)

	// 2. Initialize Organizations plugin
	orgModule := organizations.New()

	// 3. Initialize GoModularAuth Engine with schema-driven adapter
	engine, err := auth.New(auth.Config{
		Adapter: ad,
		Plugins: []auth.PluginModule{orgModule},
	})
	if err != nil {
		log.Fatalf("failed to initialize auth engine: %v", err)
	}

	// 4. Resolve strongly-typed plugin capability
	orgService := auth.MustGet[organizations.Organization](engine)
	_ = orgService

	// 5. Setup HTTP router with authentication middleware
	mux := http.NewServeMux()

	// Public Sign-Up Endpoint
	mux.HandleFunc("POST /api/signup", func(w http.ResponseWriter, r *http.Request) {
		res, err := engine.SignUp(r.Context(), auth.SignUpInput{
			Email:    "alice@example.com",
			Password: "SuperSecretPassword123!",
		})
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		fmt.Fprintf(w, "User created: %s, Session Token: %s\n", res.User.ID, res.Token)
	})

	// Protected Endpoint guarded by RequireSession
	protectedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		principal, _ := authhttp.PrincipalFrom(r.Context())
		fmt.Fprintf(w, "Authenticated Principal: %s\n", principal.Subject)
	})

	mux.Handle("GET /api/me", authhttp.RequireSession(engine,
		authhttp.WithExtractor(authhttp.BearerExtractor),
		authhttp.WithExtractor(authhttp.CookieExtractor("session_token")),
	)(protectedHandler))

	log.Println("Server listening on :8080...")
	log.Fatal(http.ListenAndServe(":8080", mux))
}

6. Documentation Index


7. License

MIT License. See LICENSE for details.

Documentation ΒΆ

Overview ΒΆ

Package auth is the core of GoModularAuth: a small, server-only, transport-agnostic authentication engine.

The core defines what it means to authenticate (users, accounts, credentials, opaque sessions, verification tokens). Persistence is delegated to a Store adapter (source of truth), acceleration to an optional Cache adapter, delivery to an optional Email adapter, and optional capabilities to plugin modules. The core never imports net/http: transport adapters translate requests into calls such as SignIn or RequireSession.

Index ΒΆ

Examples ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var (
	ErrAdapterRequired         = errors.New("auth: adapter is required")
	ErrInvalidEmail            = errors.New("auth: invalid email")
	ErrInvalidPassword         = errors.New("auth: password does not satisfy the policy")
	ErrEmailAlreadyExists      = errors.New("auth: email already registered")
	ErrInvalidCredentials      = errors.New("auth: invalid credentials")
	ErrEmailNotVerified        = errors.New("auth: email not verified")
	ErrUnauthenticated         = errors.New("auth: unauthenticated")
	ErrUserNotFound            = errors.New("auth: user not found")
	ErrInvalidToken            = errors.New("auth: invalid or expired token")
	ErrEmailNotConfigured      = errors.New("auth: email sender not configured")
	ErrPluginDependency        = errors.New("auth: plugin dependency not satisfied")
	ErrSchemaExportUnsupported = errors.New("auth: configured adapter does not support schema export")
)

Sentinel errors returned by core operations. Compare with errors.Is.

Credential and token errors are deliberately coarse (ErrInvalidCredentials, ErrInvalidToken) so callers cannot be used as user/token existence oracles.

Functions ΒΆ

func Get ΒΆ

func Get[T any](a *Auth) (T, error)

Get returns the plugin capability T registered by an installed module:

orgs, err := auth.Get[plugins.Organization](a)

func MustGet ΒΆ

func MustGet[T any](a *Auth) T

MustGet is like Get but panics when the capability is missing. Use it only during application wiring.

func OrganizationFrom ΒΆ

func OrganizationFrom(ctx context.Context) (string, bool)

OrganizationFrom retrieves the organization identifier bound to ctx, if any.

func Provide ΒΆ

func Provide[T any](h *Host, impl T) error

Provide registers impl as the capability T exposed by the module. T is usually an interface exported by the plugin; applications retrieve it with auth.Get[T](a).

func WithOrganization ΒΆ

func WithOrganization(ctx context.Context, orgID string) context.Context

WithOrganization binds an organization identifier to ctx.

func WithPrincipal ΒΆ

func WithPrincipal(ctx context.Context, p Principal) context.Context

WithPrincipal returns a context carrying p. Transport adapters call it after resolving the request credentials.

Types ΒΆ

type Auth ΒΆ

type Auth struct {
	// contains filtered or unexported fields
}

Auth is the authentication engine. It is safe for concurrent use and holds no global state: create as many independent instances as needed.

func New ΒΆ

func New(cfg Config) (*Auth, error)

New builds an Auth instance and initializes its plugin modules.

Example ΒΆ
package main

import (
	"fmt"
	"log"

	auth "github.com/BladiCreator/go-modular-auth"
	adaptermem "github.com/BladiCreator/go-modular-auth/adapter/memory"
)

func main() {
	app, err := auth.New(auth.Config{
		Adapter: adaptermem.New(),
	})
	if err != nil {
		log.Fatalf("failed to initialize auth: %v", err)
	}

	fmt.Println(app != nil)
}
Output:
true

func (*Auth) Cache ΒΆ

func (a *Auth) Cache() cache.Cache

Cache returns the configured cache adapter, or nil.

func (*Auth) ChangePassword ΒΆ

func (a *Auth) ChangePassword(ctx context.Context, in ChangePasswordInput) error

ChangePassword verifies the current password and rotates the credential.

func (*Auth) Close ΒΆ

func (a *Auth) Close(ctx context.Context) error

Close gracefully stops the authentication engine and all registered plugin lifecycles. Modules are stopped in reverse registration order (LIFO).

func (*Auth) ConsumeToken ΒΆ

func (a *Auth) ConsumeToken(ctx context.Context, purpose verification.Purpose, token string) (*verification.Token, error)

ConsumeToken validates and atomically consumes a token issued for purpose. Unknown, expired, already used or wrong-purpose tokens all yield ErrInvalidToken, so callers cannot distinguish them.

func (*Auth) CreateSession ΒΆ

func (a *Auth) CreateSession(ctx context.Context, userID string, opts SessionOptions) (*IssuedSession, error)

CreateSession issues a session for an existing user. It is the entry point for plugins that authenticate by other means (OAuth, passkeys, magic link).

func (*Auth) Email ΒΆ

func (a *Auth) Email() email.Sender

Email returns the configured email sender, or nil.

func (*Auth) Events ΒΆ

func (a *Auth) Events() *Events

Events returns the event dispatcher.

func (*Auth) ExportSchema ΒΆ

func (a *Auth) ExportSchema(ctx context.Context) ([]string, error)

ExportSchema returns the raw DDL statements generated by the configured adapter for the compiled schema (Core + Plugins). It returns ErrSchemaExportUnsupported if the adapter does not implement adapter.SchemaExporter.

func (*Auth) GetSession ΒΆ

func (a *Auth) GetSession(ctx context.Context, token string) (*SessionResult, error)

GetSession resolves an opaque token. It returns (nil, nil) when the token does not identify a valid (existing, unexpired, unrevoked) session.

func (*Auth) GetUser ΒΆ

func (a *Auth) GetUser(ctx context.Context, userID string) (*user.User, error)

GetUser returns the user with the given ID, or (nil, nil) when it does not exist.

func (*Auth) Hooks ΒΆ

func (a *Auth) Hooks() *Hooks

Hooks returns the workflow hooks registry.

func (*Auth) IssueToken ΒΆ

func (a *Auth) IssueToken(ctx context.Context, purpose verification.Purpose, subject string, ttl time.Duration) (string, error)

IssueToken creates a single-use verification token for subject and returns its plaintext value. Only the hash is persisted. Plugins (magic link, OTP, one-time token, device authorization) reuse this primitive.

func (*Auth) Logger ΒΆ

func (a *Auth) Logger() *slog.Logger

Logger returns the configured logger.

func (*Auth) Now ΒΆ

func (a *Auth) Now() time.Time

Now returns the current time according to the configured clock.

func (*Auth) PurgeExpired ΒΆ

func (a *Auth) PurgeExpired(ctx context.Context) (sessions, tokens int, err error)

PurgeExpired deletes expired sessions and verification tokens from the Store. Schedule it periodically (e.g. from a background job).

func (*Auth) Registry ΒΆ

func (a *Auth) Registry() *plugin.Registry

Registry returns the capability registry.

func (*Auth) RequestEmailVerification ΒΆ

func (a *Auth) RequestEmailVerification(ctx context.Context, userID string) error

RequestEmailVerification emails a verification token to the user. It is a no-op for already verified users.

func (*Auth) RequestPasswordReset ΒΆ

func (a *Auth) RequestPasswordReset(ctx context.Context, in RequestPasswordResetInput) error

RequestPasswordReset emails a reset token. It returns nil when the email is unknown so the endpoint cannot be used to enumerate users.

func (*Auth) RequireSession ΒΆ

func (a *Auth) RequireSession(ctx context.Context, token string) (*SessionResult, error)

RequireSession is like GetSession but returns ErrUnauthenticated when no valid session exists.

func (*Auth) RequireUser ΒΆ

func (a *Auth) RequireUser(ctx context.Context, userID string) (*user.User, error)

RequireUser is like GetUser but returns ErrUserNotFound when the user does not exist.

func (*Auth) ResetPassword ΒΆ

func (a *Auth) ResetPassword(ctx context.Context, in ResetPasswordInput) error

ResetPassword consumes a reset token, rotates the password credential and revokes every session of the user, atomically.

func (*Auth) RevokeSession ΒΆ

func (a *Auth) RevokeSession(ctx context.Context, sessionID string) error

RevokeSession revokes a session by ID: Store first, then cache invalidation. Revoking an already revoked session is a no-op.

func (*Auth) RevokeTokens ΒΆ

func (a *Auth) RevokeTokens(ctx context.Context, purpose verification.Purpose, subject string) error

RevokeTokens deletes every outstanding token of purpose issued to subject.

func (*Auth) RevokeUserSessions ΒΆ

func (a *Auth) RevokeUserSessions(ctx context.Context, userID, exceptSessionID string) error

RevokeUserSessions revokes every active session of a user except the one with ID exceptSessionID (pass "" to revoke all).

func (*Auth) Schema ΒΆ

func (a *Auth) Schema() *schema.Schema

Schema returns a cloned copy of the compiled engine schema (core models + plugin extensions).

func (*Auth) SignIn ΒΆ

func (a *Auth) SignIn(ctx context.Context, in SignInInput) (*AuthResult, error)

SignIn verifies email and password and issues a session.

Unknown email and wrong password both return ErrInvalidCredentials after a comparable amount of work, preventing user enumeration by timing.

Example ΒΆ
package main

import (
	"context"
	"fmt"
	"log"

	auth "github.com/BladiCreator/go-modular-auth"
	adaptermem "github.com/BladiCreator/go-modular-auth/adapter/memory"
)

func main() {
	ctx := context.Background()
	app, err := auth.New(auth.Config{
		Adapter: adaptermem.New(),
	})
	if err != nil {
		log.Fatalf("init error: %v", err)
	}

	_, err = app.SignUp(ctx, auth.SignUpInput{
		Email:    "loginuser@example.com",
		Password: "Password123!",
	})
	if err != nil {
		log.Fatalf("signup error: %v", err)
	}

	signInRes, err := app.SignIn(ctx, auth.SignInInput{
		Email:    "loginuser@example.com",
		Password: "Password123!",
	})
	if err != nil {
		log.Fatalf("signin error: %v", err)
	}

	fmt.Println(signInRes.Session != nil)
}
Output:
true

func (*Auth) SignOut ΒΆ

func (a *Auth) SignOut(ctx context.Context, in SignOutInput) error

SignOut revokes the session identified by the token. Unknown or already revoked tokens are a no-op, making SignOut idempotent.

func (*Auth) SignUp ΒΆ

func (a *Auth) SignUp(ctx context.Context, in SignUpInput) (*AuthResult, error)

SignUp creates User + password Account + Credential (+ Session) in a single Store transaction. Cache population, events and After hooks run after commit.

Example ΒΆ
package main

import (
	"context"
	"fmt"
	"log"

	auth "github.com/BladiCreator/go-modular-auth"
	adaptermem "github.com/BladiCreator/go-modular-auth/adapter/memory"
)

func main() {
	ctx := context.Background()
	app, err := auth.New(auth.Config{
		Adapter: adaptermem.New(),
	})
	if err != nil {
		log.Fatalf("init error: %v", err)
	}

	res, err := app.SignUp(ctx, auth.SignUpInput{
		Email:    "newuser@example.com",
		Password: "Password123!",
	})
	if err != nil {
		log.Fatalf("signup error: %v", err)
	}

	fmt.Println(res.User.Email)
}
Output:
newuser@example.com

func (*Auth) Store ΒΆ

func (a *Auth) Store() store.Store

Store returns the configured store adapter.

func (*Auth) VerifyEmail ΒΆ

func (a *Auth) VerifyEmail(ctx context.Context, in VerifyEmailInput) (*user.User, error)

VerifyEmail consumes a verification token and marks the email as verified.

type AuthResult ΒΆ

type AuthResult struct {
	User    *user.User
	Session *session.Session
	Token   string
}

AuthResult is the outcome of SignUp/SignIn. Session and Token are empty when SignUp does not issue a session (email verification required).

func (*AuthResult) Principal ΒΆ

func (r *AuthResult) Principal() Principal

Principal returns the authenticated identity.

type ChangePasswordInput ΒΆ

type ChangePasswordInput struct {
	UserID          string
	CurrentPassword string
	NewPassword     string
	// CurrentSessionID is kept alive; every other session is revoked unless
	// KeepOtherSessions is true.
	CurrentSessionID  string
	KeepOtherSessions bool
}

ChangePasswordInput changes the password of an authenticated user.

type Config ΒΆ

type Config struct {
	// Adapter is the generic, schema-driven storage adapter. Required.
	Adapter adapter.Adapter
	// Cache is an optional performance layer. When nil every read hits the Store.
	Cache cache.Cache
	// Email is an optional sender used by email verification and password reset.
	Email email.Sender
	// Hasher hashes passwords. Defaults to Argon2id with OWASP parameters.
	Hasher password.Hasher
	// Plugins are the plugin modules to install.
	Plugins []PluginModule
	// Logger receives operational logs (cache degradation, hook panics...). Defaults to discard.
	Logger *slog.Logger
	// Now is the clock. Defaults to time.Now.
	Now func() time.Time

	Session           SessionConfig
	User              UserConfig
	Password          PasswordPolicy
	EmailVerification EmailVerificationConfig
	PasswordReset     PasswordResetConfig
	Messages          Messages
}

Config configures an Auth instance. Adapter is required; every zero value falls back to a secure default.

type Dependent ΒΆ

type Dependent interface {
	Dependencies() []string
}

Dependent is implemented by modules that require other modules. Required modules are initialized first; missing ones make New fail.

type EmailVerificationConfig ΒΆ

type EmailVerificationConfig struct {
	// Required forbids sign in (and session issuance at sign up) until the email is verified.
	Required bool
	// SendOnSignUp sends the verification email right after sign up (requires Config.Email).
	SendOnSignUp bool
	// TokenTTL is the verification token lifetime. Default: 24 hours.
	TokenTTL time.Duration
}

EmailVerificationConfig configures email verification.

type Event ΒΆ

type Event struct {
	Name    EventName
	Time    time.Time
	Subject string // usually the user ID
	Payload any
}

Event notifies that something happened. Events are observational: they are published after the Store commit and cannot alter the workflow.

type EventHandler ΒΆ

type EventHandler func(ctx context.Context, e Event)

EventHandler handles an event. Handlers run synchronously, in subscription order; long work should be offloaded by the handler itself.

type EventName ΒΆ

type EventName string

EventName identifies an event. Plugins define their own names, prefixed with their module ID (e.g. "organizations.created").

const (
	EventUserCreated     EventName = "user.created"
	EventUserSignedIn    EventName = "user.signed_in"
	EventUserSignedOut   EventName = "user.signed_out"
	EventSessionCreated  EventName = "session.created"
	EventSessionRevoked  EventName = "session.revoked"
	EventPasswordChanged EventName = "password.changed"
	EventEmailVerified   EventName = "email.verified"
)

Core events.

type Events ΒΆ

type Events struct {
	// contains filtered or unexported fields
}

Events is the in-process event dispatcher.

func (*Events) Publish ΒΆ

func (e *Events) Publish(ctx context.Context, ev Event)

Publish dispatches ev. A panicking handler is recovered and logged so an observer can never break an authentication workflow.

func (*Events) Subscribe ΒΆ

func (e *Events) Subscribe(name EventName, h EventHandler)

Subscribe registers h for the given event name.

func (*Events) SubscribeAll ΒΆ

func (e *Events) SubscribeAll(h EventHandler)

SubscribeAll registers h for every event (useful for audit logging).

type Hooks ΒΆ

type Hooks struct {
	// contains filtered or unexported fields
}

Hooks let applications and plugins intervene in core workflows.

Hooks differ from Events: a Before hook may mutate its input or abort the workflow by returning an error (returned unchanged to the caller); an After hook runs once the Store transaction has committed and observes the result.

BeforeUserCreate and BeforeSessionCreate run INSIDE the Store transaction: store operations performed with the received ctx join that transaction, so plugins can atomically persist their own rows (or veto the operation).

func (*Hooks) AfterSignIn ΒΆ

func (h *Hooks) AfterSignIn(fn func(ctx context.Context, res *AuthResult))

AfterSignIn registers a hook run after a successful sign in.

func (*Hooks) AfterSignOut ΒΆ

func (h *Hooks) AfterSignOut(fn func(ctx context.Context, s *session.Session))

AfterSignOut registers a hook run after a session has been revoked.

func (*Hooks) AfterSignUp ΒΆ

func (h *Hooks) AfterSignUp(fn func(ctx context.Context, res *AuthResult))

AfterSignUp registers a hook run after a successful sign up.

func (*Hooks) AfterUserCreate ΒΆ

func (h *Hooks) AfterUserCreate(fn func(ctx context.Context, u *user.User))

AfterUserCreate registers a hook run after the user creation has committed.

func (*Hooks) BeforeSessionCreate ΒΆ

func (h *Hooks) BeforeSessionCreate(fn func(ctx context.Context, s *session.Session) error)

BeforeSessionCreate registers a hook run inside the transaction before a session is persisted (e.g. enforce a maximum number of sessions).

func (*Hooks) BeforeSignIn ΒΆ

func (h *Hooks) BeforeSignIn(fn func(ctx context.Context, in *SignInInput) error)

BeforeSignIn registers a hook run before credentials are checked (e.g. rate limiting, captcha).

func (*Hooks) BeforeSignOut ΒΆ

func (h *Hooks) BeforeSignOut(fn func(ctx context.Context, in *SignOutInput) error)

BeforeSignOut registers a hook run before a session is revoked.

func (*Hooks) BeforeSignUp ΒΆ

func (h *Hooks) BeforeSignUp(fn func(ctx context.Context, in *SignUpInput) error)

BeforeSignUp registers a hook run before input validation.

func (*Hooks) BeforeUserCreate ΒΆ

func (h *Hooks) BeforeUserCreate(fn func(ctx context.Context, u *user.User) error)

BeforeUserCreate registers a hook run inside the transaction before a user is persisted.

type Host ΒΆ

type Host struct {
	// contains filtered or unexported fields
}

Host is the surface exposed to a plugin module during and after Init.

func (*Host) Adapter ΒΆ

func (h *Host) Adapter() adapter.Adapter

Adapter returns the generic storage adapter, or nil if none is configured.

func (*Host) Auth ΒΆ

func (h *Host) Auth() *Auth

Auth returns the engine, giving access to core operations (CreateSession, IssueToken, ConsumeToken, ...).

func (*Host) Cache ΒΆ

func (h *Host) Cache() cache.Cache

Cache returns the shared cache adapter, or nil when none is configured. Plugins must namespace their keys: cache.Key(h.ModuleID(), ...).

func (*Host) Email ΒΆ

func (h *Host) Email() email.Sender

Email returns the email sender, or nil when none is configured.

func (*Host) Events ΒΆ

func (h *Host) Events() *Events

Events returns the event dispatcher.

func (*Host) Hooks ΒΆ

func (h *Host) Hooks() *Hooks

Hooks returns the workflow hooks registry.

func (*Host) Logger ΒΆ

func (h *Host) Logger() *slog.Logger

Logger returns a logger tagged with the module ID.

func (*Host) ModuleID ΒΆ

func (h *Host) ModuleID() string

ModuleID returns the ID of the module owning this host.

func (*Host) Now ΒΆ

func (h *Host) Now() time.Time

Now returns the current time according to the configured clock.

func (*Host) RegisterLifecycle ΒΆ

func (h *Host) RegisterLifecycle(l Lifecycle)

RegisterLifecycle registers a Lifecycle callback for graceful shutdown.

func (*Host) Schema ΒΆ

func (h *Host) Schema() *schema.Schema

Schema returns the compiled database schema, or nil if schema compilation is not active.

type IssuedSession ΒΆ

type IssuedSession struct {
	Session *session.Session
	Token   string
}

IssuedSession is a newly created session and its plaintext token. The token is returned exactly once: hand it to the client and discard it.

type Lifecycle ΒΆ

type Lifecycle interface {
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
}

Lifecycle is optionally implemented by plugin modules or services that manage background tasks, workers, or buffers requiring graceful startup or shutdown.

type Messages ΒΆ

type Messages struct {
	EmailVerification func(u *user.User, token string) email.Message
	PasswordReset     func(u *user.User, token string) email.Message
}

Messages builds the emails sent by the core. Builders receive the plaintext token; it is the application's job to embed it (e.g. into a URL served by its transport adapter). The core fills Message.To.

type PasswordPolicy ΒΆ

type PasswordPolicy struct {
	// MinLength in bytes. Default: 8.
	MinLength int
	// MaxLength in bytes, protecting the hasher from DoS. Default: 128.
	MaxLength int
}

PasswordPolicy constrains acceptable passwords.

type PasswordResetConfig ΒΆ

type PasswordResetConfig struct {
	// TokenTTL is the reset token lifetime. Default: 1 hour.
	TokenTTL time.Duration
}

PasswordResetConfig configures password reset.

type PluginModule ΒΆ

type PluginModule interface {
	ID() string
	Init(host *Host) error
}

PluginModule is an installable plugin. Plugins depend on the core; the core never depends on concrete plugins.

Init receives a Host scoped to the module, through which it registers hooks, subscribes to events, accesses infrastructure and provides its capabilities with Provide.

type Principal ΒΆ

type Principal struct {
	Subject string
	Type    PrincipalType
}

Principal is the authenticated identity interacting with the system. It is the boundary between Authentication (who) and Authorization (what): authorization plugins consume a Principal, never a Session directly.

func PrincipalFrom ΒΆ

func PrincipalFrom(ctx context.Context) (Principal, bool)

PrincipalFrom returns the Principal stored in ctx, if any.

type PrincipalType ΒΆ

type PrincipalType string

PrincipalType classifies the authenticated identity.

const (
	PrincipalUser           PrincipalType = "user"
	PrincipalServiceAccount PrincipalType = "service_account"
	PrincipalAPIKey         PrincipalType = "api_key"
)

Core principal types. Plugins may define additional types.

type RequestPasswordResetInput ΒΆ

type RequestPasswordResetInput struct {
	Email string
}

RequestPasswordResetInput starts a password reset.

type ResetPasswordInput ΒΆ

type ResetPasswordInput struct {
	Token       string
	NewPassword string
}

ResetPasswordInput completes a password reset.

type SchemaProvider ΒΆ

type SchemaProvider interface {
	RegisterSchema(s *schema.Schema) error
}

SchemaProvider is optionally implemented by PluginModule instances that contribute to the persistent database schema (registering new models or extending existing models).

type SessionConfig ΒΆ

type SessionConfig struct {
	// TTL is the session lifetime. Default: 7 days.
	TTL time.Duration
	// CacheTTL is the maximum time a session stays cached. The effective TTL
	// is min(CacheTTL, time until expiration). It bounds the inconsistency
	// window should a cache invalidation fail. Default: 5 minutes.
	CacheTTL time.Duration
}

SessionConfig configures opaque sessions.

type SessionOptions ΒΆ

type SessionOptions struct {
	IPAddress string
	UserAgent string
}

SessionOptions carries optional metadata recorded with a new session.

type SessionResult ΒΆ

type SessionResult struct {
	Session *session.Session
	User    *user.User
}

SessionResult is a validated session together with its user.

func (*SessionResult) Principal ΒΆ

func (r *SessionResult) Principal() Principal

Principal returns the authenticated identity of the session.

type SignInInput ΒΆ

type SignInInput struct {
	Email    string
	Password string
	Session  SessionOptions
}

SignInInput authenticates a user with email and password.

type SignOutInput ΒΆ

type SignOutInput struct {
	Token string
}

SignOutInput ends the session identified by Token.

type SignUpInput ΒΆ

type SignUpInput struct {
	Email    string
	Password string
	Session  SessionOptions
}

SignUpInput registers a user with email and password.

type UserConfig ΒΆ

type UserConfig struct {
	// CacheTTL is the time a user stays cached. Default: 5 minutes.
	CacheTTL time.Duration
}

UserConfig configures user caching.

type VerifyEmailInput ΒΆ

type VerifyEmailInput struct {
	Token string
}

VerifyEmailInput completes an email verification.

Directories ΒΆ

Path Synopsis
Package account defines the Account entity: the link between a User and an authentication provider (password, google, github, passkey, ...).
Package account defines the Account entity: the link between a User and an authentication provider (password, google, github, passkey, ...).
Package adapter defines the generic, schema-driven persistence contracts for GoModularAuth.
Package adapter defines the generic, schema-driven persistence contracts for GoModularAuth.
bridge
Package bridge implements a store.Store adapter on top of adapter.Adapter.
Package bridge implements a store.Store adapter on top of adapter.Adapter.
memory
Package memory provides an in-memory implementation of adapter.Adapter.
Package memory provides an in-memory implementation of adapter.Adapter.
sql
Package sqladapter provides generic SQL dialect handling and a base relational adapter.
Package sqladapter provides generic SQL dialect handling and a base relational adapter.
adapters
http module
memory module
surrealdb module
Package cache defines the Cache Adapter contracts of GoModularAuth.
Package cache defines the Cache Adapter contracts of GoModularAuth.
memory
Package memory provides an in-process cache.Cache for tests and local development.
Package memory provides an in-process cache.Cache for tests and local development.
Package credential defines the Credential entity: the material used to prove an identity (password hash, passkey public key, API key hash, ...).
Package credential defines the Credential entity: the material used to prove an identity (password hash, passkey public key, API key hash, ...).
Package email defines the Email Adapter contract.
Package email defines the Email Adapter contract.
memory
Package memory provides a fake email.Sender that records messages in memory, for tests and local development.
Package memory provides a fake email.Sender that records messages in memory, for tests and local development.
internal
secure
Package secure contains the cryptographic primitives shared by the core: random identifiers, opaque secret tokens and their storage representation.
Package secure contains the cryptographic primitives shared by the core: random identifiers, opaque secret tokens and their storage representation.
Package password abstracts password hashing behind the Hasher interface and ships an Argon2id implementation as the secure default.
Package password abstracts password hashing behind the Hasher interface and ships an Argon2id implementation as the secure default.
Package plugin provides the type-keyed capability registry used by the GoModularAuth plugin runtime.
Package plugin provides the type-keyed capability registry used by the GoModularAuth plugin runtime.
plugins
account-linking
Package accountlinking provides secure linking and unlinking of authentication accounts while preserving a single canonical Core User identity in GoModularAuth.
Package accountlinking provides secure linking and unlinking of authentication accounts while preserving a single canonical Core User identity in GoModularAuth.
account-linking/migrations
Package migrations embeds SQL migrations for the Account Linking plugin.
Package migrations embeds SQL migrations for the Account Linking plugin.
admin
Package admin is a reserved module for administrative capabilities.
Package admin is a reserved module for administrative capabilities.
admin/cache
Package cache provides caching support for high-frequency administrative queries.
Package cache provides caching support for high-frequency administrative queries.
admin/events
Package events exports administrative audit event types for GoModularAuth.
Package events exports administrative audit event types for GoModularAuth.
admin/migrations
Package migrations contains SQL schema migrations for the admin plugin.
Package migrations contains SQL schema migrations for the admin plugin.
admin/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
agent
Package agent provides AI and autonomous agent authentication capabilities (reserved module).
Package agent provides AI and autonomous agent authentication capabilities (reserved module).
anonymous
Package anonymous provides anonymous authentication identities and lifecycle management with optional conversion and account linking to permanent authenticated users for GoModularAuth.
Package anonymous provides anonymous authentication identities and lifecycle management with optional conversion and account linking to permanent authenticated users for GoModularAuth.
anonymous/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
api-keys
Package apikeys provides API key authentication, lifecycle management, and resolution into GoModularAuth Core Principal semantics.
Package apikeys provides API key authentication, lifecycle management, and resolution into GoModularAuth Core Principal semantics.
api-keys/cache
Package cache provides caching and brute force prevention abstractions for the API keys module.
Package cache provides caching and brute force prevention abstractions for the API keys module.
api-keys/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
audit
Package audit provides structured security audit logging capabilities (reserved module).
Package audit provides structured security audit logging capabilities (reserved module).
audit/migrations
Package migrations contains SQL schema migrations for the audit plugin.
Package migrations contains SQL schema migrations for the audit plugin.
audit/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
bearer
Package bearer implements opaque bearer token issuance, transport extraction, and stateful token revocation for GoModularAuth.
Package bearer implements opaque bearer token issuance, transport extraction, and stateful token revocation for GoModularAuth.
bearer/cache
Package cache provides performance acceleration for bearer token validation using GoModularAuth's core cache adapter.
Package cache provides performance acceleration for bearer token validation using GoModularAuth's core cache adapter.
bearer/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
device-authorization
Package deviceauth provides RFC 8628 OAuth 2.0 Device Authorization Grant capabilities (reserved module).
Package deviceauth provides RFC 8628 OAuth 2.0 Device Authorization Grant capabilities (reserved module).
device-authorization/cache
Package cache provides rate limiting and temporary throttle helpers for device authorization.
Package cache provides rate limiting and temporary throttle helpers for device authorization.
device-authorization/events
Package events re-exports device authorization audit event identifiers and payload types.
Package events re-exports device authorization audit event identifiers and payload types.
device-authorization/migrations
Package migrations contains SQL schema migrations for the device-authorization plugin.
Package migrations contains SQL schema migrations for the device-authorization plugin.
device-authorization/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
email-otp
Package emailotp provides time-bound, single-use one-time passwords delivered via email.
Package emailotp provides time-bound, single-use one-time passwords delivered via email.
email-otp/cache
Package cache provides rate limiting, cooldown, and failure-policy abstractions for Email OTP.
Package cache provides rate limiting, cooldown, and failure-policy abstractions for Email OTP.
email-otp/plugins
Package plugins exposes the capability aliases for GoModularAuth plugins.
Package plugins exposes the capability aliases for GoModularAuth plugins.
jwt
Package jwt provides stateless, signed JSON Web Token (JWT) issuance and verification with support for HMAC, RSA, and ECDSA key suites.
Package jwt provides stateless, signed JSON Web Token (JWT) issuance and verification with support for HMAC, RSA, and ECDSA key suites.
jwt/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
lastlogin
Package lastlogin provides last login tracking capabilities (reserved module).
Package lastlogin provides last login tracking capabilities (reserved module).
magic-link
Package magiclink provides passwordless authentication via signed, expiring URLs delivered by email.
Package magiclink provides passwordless authentication via signed, expiring URLs delivered by email.
magic-link/cache
Package cache provides rate limiting and throttling abstractions for the magic link plugin.
Package cache provides rate limiting and throttling abstractions for the magic link plugin.
magic-link/plugins
Package plugins exposes the capability aliases for GoModularAuth plugins.
Package plugins exposes the capability aliases for GoModularAuth plugins.
multisession
Package multisession enriches Core sessions with device metadata, user-agent parsing, and multi-device session management and remote revocation.
Package multisession enriches Core sessions with device metadata, user-agent parsing, and multi-device session management and remote revocation.
multisession/plugins
Package plugins exposes the capability aliases for GoModularAuth plugins.
Package plugins exposes the capability aliases for GoModularAuth plugins.
oauth
Package oauth implements OAuth 2.0 client authentication and social account linking for Google, GitHub, and custom providers with PKCE support.
Package oauth implements OAuth 2.0 client authentication and social account linking for Google, GitHub, and custom providers with PKCE support.
oauth-provider
Package oauthprovider implements an RFC 6749 and RFC 7636 compliant OAuth 2.1 Authorization Server and OpenID Connect identity provider.
Package oauthprovider implements an RFC 6749 and RFC 7636 compliant OAuth 2.1 Authorization Server and OpenID Connect identity provider.
oauth-provider/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
oauth/plugins
Package plugins exposes strongly-typed capability aliases for GoModularAuth plugins.
Package plugins exposes strongly-typed capability aliases for GoModularAuth plugins.
oauth/provider
Package provider defines the contracts and models for OAuth 2.0 / OIDC identity providers.
Package provider defines the contracts and models for OAuth 2.0 / OIDC identity providers.
oidc
Package oidc provides OpenID Connect (OIDC) relying-party authentication and identity integration for GoModularAuth.
Package oidc provides OpenID Connect (OIDC) relying-party authentication and identity integration for GoModularAuth.
oidc-provider
Package oidcprovider provides OpenID Connect Provider capabilities (reserved module).
Package oidcprovider provides OpenID Connect Provider capabilities (reserved module).
oidc/migrations
Package migrations contains SQL schema migrations for the oidc plugin.
Package migrations contains SQL schema migrations for the oidc plugin.
oidc/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
one-time-token
Package ott provides one-time token authentication capabilities (reserved module).
Package ott provides one-time token authentication capabilities (reserved module).
openapi
Package openapi provides OpenAPI schema generation capabilities (reserved module).
Package openapi provides OpenAPI schema generation capabilities (reserved module).
organizations
Package organizations provides performance acceleration for organization and membership lookups using GoModularAuth's core cache adapter.
Package organizations provides performance acceleration for organization and membership lookups using GoModularAuth's core cache adapter.
organizations/migrations
Package migrations contains SQL schema migrations for the organizations plugin.
Package migrations contains SQL schema migrations for the organizations plugin.
organizations/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
password-policy
Package passwordpolicy provides configurable password-strength, complexity, reuse prevention, and compromised-password detection through Core authentication hooks in GoModularAuth.
Package passwordpolicy provides configurable password-strength, complexity, reuse prevention, and compromised-password detection through Core authentication hooks in GoModularAuth.
password-policy/migrations
Package migrations embeds SQL migrations for the Password Policy plugin.
Package migrations embeds SQL migrations for the Password Policy plugin.
phone
Package phone provides phone number verification and SMS-based OTP authentication.
Package phone provides phone number verification and SMS-based OTP authentication.
phone/plugins
Package plugins exposes strongly typed capability aliases for GoModularAuth plugins.
Package plugins exposes strongly typed capability aliases for GoModularAuth plugins.
polar
Package polar integrates Polar.sh monetization, licensing, and subscription synchronization.
Package polar integrates Polar.sh monetization, licensing, and subscription synchronization.
policy
Package policy provides composable policy-based and attribute-based access control (ABAC) for GoModularAuth applications, evaluating Principal, User, Organization, Resource, Action, and Context attributes without requiring proprietary policy languages.
Package policy provides composable policy-based and attribute-based access control (ABAC) for GoModularAuth applications, evaluating Principal, User, Organization, Resource, Action, and Context attributes without requiring proprietary policy languages.
policy/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
rate-limit
Package ratelimit provides distributed rate limiting capabilities (reserved module).
Package ratelimit provides distributed rate limiting capabilities (reserved module).
rate-limit/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
rbac
Package rbac provides decoupled role-based access control (RBAC) authorization for GoModularAuth applications, operating over Core Principal identities independently of authentication protocols and transport mechanisms.
Package rbac provides decoupled role-based access control (RBAC) authorization for GoModularAuth applications, operating over Core Principal identities independently of authentication protocols and transport mechanisms.
rbac/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
saml
Package saml provides enterprise SAML 2.0 Service Provider identity federation and authentication for GoModularAuth.
Package saml provides enterprise SAML 2.0 Service Provider identity federation and authentication for GoModularAuth.
saml-provider
Package samlprovider provides SAML 2.0 Identity Provider capabilities (reserved module).
Package samlprovider provides SAML 2.0 Identity Provider capabilities (reserved module).
saml/migrations
Package migrations provides embedded SQL migrations for the SAML plugin.
Package migrations provides embedded SQL migrations for the SAML plugin.
saml/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
scim
Package scim provides SCIM 2.0 protocol provisioning capabilities (reserved module).
Package scim provides SCIM 2.0 protocol provisioning capabilities (reserved module).
service-accounts
Package serviceaccounts provides service account management capabilities (reserved module).
Package serviceaccounts provides service account management capabilities (reserved module).
sso
Package sso provides enterprise Single Sign-On (SSO) configuration, domain discovery, and identity federation over OpenID Connect (OIDC) and SAML 2.0 for GoModularAuth.
Package sso provides enterprise Single Sign-On (SSO) configuration, domain discovery, and identity federation over OpenID Connect (OIDC) and SAML 2.0 for GoModularAuth.
sso/migrations
Package migrations exposes embedded SQL migration assets for the SSO plugin.
Package migrations exposes embedded SQL migration assets for the SSO plugin.
sso/oidc
Package oidc implements the OpenID Connect protocol connector for enterprise SSO.
Package oidc implements the OpenID Connect protocol connector for enterprise SSO.
sso/plugins
Package plugins exposes capability aliases for GoModularAuth plugins.
Package plugins exposes capability aliases for GoModularAuth plugins.
sso/saml
Package saml implements SAML 2.0 Service Provider functionality for enterprise SSO.
Package saml implements SAML 2.0 Service Provider functionality for enterprise SSO.
stripe
Package stripe implements Stripe billing, customer portal access, and subscription lifecycle management.
Package stripe implements Stripe billing, customer portal access, and subscription lifecycle management.
twofactor
Package twofactor implements RFC 6238 TOTP two-factor authentication and recovery codes.
Package twofactor implements RFC 6238 TOTP two-factor authentication and recovery codes.
twofactor/plugins
Package plugins exposes the capability aliases for GoModularAuth plugins.
Package plugins exposes the capability aliases for GoModularAuth plugins.
username
Package username enables username-based registration and authentication alongside email.
Package username enables username-based registration and authentication alongside email.
passkeys module
Package schema defines the declarative, schema-driven data model for GoModularAuth.
Package schema defines the declarative, schema-driven data model for GoModularAuth.
Package session defines the Session entity: an opaque, server-side persisted authentication session.
Package session defines the Session entity: an opaque, server-side persisted authentication session.
Package store defines the persistence contracts of GoModularAuth.
Package store defines the persistence contracts of GoModularAuth.
sqltx
Package sqltx provides the shared database/sql transaction context used by every SQL store adapter of GoModularAuth (core and plugins).
Package sqltx provides the shared database/sql transaction context used by every SQL store adapter of GoModularAuth (core and plugins).
Package user defines the User entity: the identity that authenticates.
Package user defines the User entity: the identity that authenticates.
Package verification defines the VerificationToken primitive: a secure, expiring, single-use token reusable by the core (email verification, password reset) and by plugins (magic link, OTP, one-time token, ...).
Package verification defines the VerificationToken primitive: a secure, expiring, single-use token reusable by the core (email verification, password reset) and by plugins (magic link, OTP, one-time token, ...).

Jump to

Keyboard shortcuts

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