Plugins and hooks

This page explains the two ways to add behavior to Behemoth: plugins, which add features, and hooks, which run your code at fixed points in Behemoth's work. Read How Behemoth fits together first.

Plugins add, hooks react. A plugin brings new tables, routes, and flows. A hook lets your code take part in a flow that already exists. You often need only a hook.

Plugins #

A plugin is a Go type that implements core.Plugin. Behemoth has no authentication features outside plugins. Even sign-up and sign-in with an email address come from one.

A plugin can contribute the following:

  • Tables, which Behemoth includes in the migrations it generates
  • Routes, mounted on your router
  • Hook points that other code can hook into
  • Hook handlers that run at points other plugins declared
  • Token kinds for single-use tokens, such as the one in a sign-in link
  • Permissions that its flows require. See Callers and permissions.
  • Rate-limit rules for its routes and flows

Built-in plugins #

Behemoth includes the following plugins:

PluginWhat it addsNeeds
Email and passwordSign-up, sign-in, sign-out, and password reset
UsernameA unique username and sign-in with itEmail and password
Phone numberA confirmed phone number, and sign-in or password reset with a code sent by text messageEmail and password, and an SMS sender
Magic linkSign-in with a link sent by emailA mail sender
Email verificationConfirmation that a user controls an email addressA mail sender
OAuth (experimental)Sign-in and account linking through an OpenID Connect provider, Google, or GitHubA callback page of your own that receives the provider's redirect
Two-factorA second factor at sign-in: an authenticator app code, or a code sent by email or text message

Pass the plugins you want to Prepare. Behemoth orders them by their dependencies, so the order of your list does not matter.

What a plugin implements #

Each method of core.Plugin runs at a fixed moment, which is why Behemoth starts in two phases:

MethodRuns inPurpose
Meta and VersionPrepareGive the plugin's name, the plugins it depends on, and the path its routes mount under
DeclarePrepareDeclare tables, hook points, token kinds, permissions, and rate-limit rules
RegisterBootRegister hook handlers
InitBootReceive the AuthContext and keep it for later

A plugin that serves routes also implements httpapi.Plugin, which adds Routes and Middlewares. The following skeleton is a plugin that does nothing yet:

go
type HelloPlugin struct {
    ac *core.AuthContext
}

func (p *HelloPlugin) Meta() core.PluginMeta {
    return core.PluginMeta{Name: "hello"}
}

func (p *HelloPlugin) Version() string {
    return "0.1.0"
}

func (p *HelloPlugin) Declare(ic *core.PluginInitContext) error {
    // Declare tables, hook points, tokens, and rate limits here.
    return nil
}

func (p *HelloPlugin) Register(reg core.HookRegistry) error {
    // Register hook handlers here.
    return nil
}

func (p *HelloPlugin) Init(ac *core.AuthContext) error {
    p.ac = ac
    return nil
}

The examples/init directory in the repository has a complete plugin. It declares a table, registers hooks, and serves a route.

When to write a plugin #

Write a plugin when your feature needs its own tables or routes, or when you want to reuse it across applications. For anything smaller, register hook handlers with BootConfig.Hooks and declare your tables with PrepareConfig.Schema. Your application takes part in the same way as a plugin, so you give up nothing.

Hooks #

A hook point is a named place in Behemoth's work, such as auth.signUp.after or data.user.beforeCreate. A hook handler is your function, registered on a point. When Behemoth reaches the point, it runs the handlers registered there.

Phases #

Every point has one phase, which says when it fires relative to its operation:

PhaseFiresA handler can
BeforeBefore the operationInspect or change the data, or stop the operation by returning an error
AfterAfter the operation succeedsReact to the result
FailedWhen the operation is rejected, for example for a wrong passwordBe told about it. A failed handler cannot change the outcome.

Tiers #

Points also belong to one of two tiers. The tier decides what a handler can safely do, so pick it before you pick the point.

Data hooksFlow hooks
Exampledata.user.afterCreateauth.signUp.after
FiresAround every write to one table, whatever caused itAround a whole flow, such as sign-up
RunsInside the write's database transactionOutside any transaction
An error from an after handlerFails the write and rolls it backIs logged, and the operation still succeeds
Use it forData that belongs with the row, such as a profile row for each new userEverything else, such as emails, webhooks, and calls to other systems

If a rollback of the database transaction would undo everything your handler did, use a data hook. If not, use a flow hook. A welcome email is the usual example of the second case: the user can still be rolled back after a data hook returns, but auth.signUp.after fires once the user is saved.

Register a handler #

A before handler receives the data and returns the data to continue with. Return an error to stop the operation. Return one of the types from the errs package, so that the client gets a sensible HTTP status.

go
func requireCompanyEmail(
    hctx *core.HookContext,
    payload behemoth.M,
) (behemoth.M, error) {
    email, _ := payload[models.UserEmail].(string)
    if !strings.HasSuffix(email, "@example.com") {
        return nil, errs.NewValidationError(
            "requireCompanyEmail",
            "users",
            errors.New("only example.com addresses may register"),
        )
    }
    return payload, nil
}

Register the handler in BootConfig.Hooks. A plugin registers its handlers in its Register method instead.

go
ac, err := engine.Boot(
    ctx,
    app,
    db,
    engine.BootConfig{
        Crypto: cryptoCfg,
        Hooks: func(reg core.HookRegistry) error {
            return reg.OnBefore(
                hooks.HookUserBeforeCreate,
                requireCompanyEmail,
                nil,
            )
        },
    },
)
if err != nil {
    log.Fatal(err)
}

In this example, cryptoCfg is your crypto.Config. The point constants come from the core/hooks package. Use OnAfter and OnFailed for the other two phases.

Choose a hook point #

The following table maps common tasks to a point. The Hooks reference lists every point and the data each one carries.

You want toUse
Refuse a user for every way a user is createdA before handler on data.user.beforeCreate
Refuse an email and password sign-up onlyA before handler on auth.signUp.before
Create a row that belongs with the new userAn after handler on data.user.afterCreate
Send a welcome emailAn after handler on auth.signUp.after or data.user.created
Record a rejected sign-inA failed handler on auth.signIn.failed

Handler order #

Several handlers can share a point. Behemoth works out their order once, at Boot:

  1. Handlers with a lower priority value run first. Use PriorityHighest for checks that need to see the raw input, and PriorityLowest for logging that needs to see the final result.
  2. Among handlers of the same priority, the Before and After options of core.HookOptions name the plugins a handler must run before or after.
  3. Handlers with no constraint between them run in plugin boot order. Your application comes last.

How plugins and hooks work together #

Plugins use hooks to extend each other. A plugin declares the points of its own flows, and any other plugin or your application can hook into them without a change to the first plugin.

The two-factor plugin shows the pattern. Every sign-in passes the point auth.signIn.credentialsVerified after it checks the first factor. The two-factor plugin handles that point and holds the sign-in until the user presents a second factor. Because it hooks a point and not a plugin, it works with a password, a magic link, a phone code, or any other first factor.

A plugin can also declare points for its own flows and fire them, so that other code can hook into the plugin in the same way. The Hooks reference describes how.

Limits #

Keep the following rules in mind when you write handlers:

  • One handler per owner per point. A plugin, or your application, can register one handler on a given point. A second registration fails at Boot. Put both steps in one function.
  • Handlers are fixed at Boot. You cannot add or remove a handler while the application runs.
  • A panic in a handler is caught and logged. In a before handler, it stops the operation.
Data hooks hold the transaction open

A data hook runs inside the database transaction of the write. A slow handler holds the transaction's locks for as long as it runs, and on SQLite it blocks every other writer. The transaction can also be rolled back after your handler returns, and a rollback does not undo emails, webhooks, key-value writes, or writes through ac.Store and ac.DB. Do that work in a flow hook or an after-commit point such as data.user.created.

Next steps #

To go deeper, read the following pages: