AshAuthentication.Phoenix.Plug.RequireTotp (ash_authentication_phoenix v3.0.0-rc.6)

View Source

A plug that enforces TOTP two-factor authentication for routes.

This plug checks if the current user has TOTP configured and can optionally redirect users who haven't set up TOTP to the setup page.

Behaviour When No User Is Present

When there is no authenticated user (i.e., conn.assigns[:current_user] is nil), this plug passes through without modification. It does not redirect or halt the request.

This design allows the plug to be used in pipelines that may or may not have an authenticated user. For routes that require authentication, use this plug after your authentication plug (e.g., :require_authenticated) to ensure a user exists before checking TOTP configuration.

Usage

In your router, add the plug to a pipeline:

pipeline :require_totp do
  plug AshAuthentication.Phoenix.Plug.RequireTotp,
    resource: MyApp.Accounts.User,
    on_missing: :redirect_to_setup,
    setup_path: "/auth/totp/setup"
end

scope "/secure", MyAppWeb do
  pipe_through [:browser, :require_auth, :require_totp]
  # Protected routes that require 2FA
end

Options

  • :resource - Required. The user resource module that has the TOTP strategy.

  • :strategy - Optional. The name of the TOTP strategy. Defaults to the first TOTP strategy found on the resource.

  • :on_missing - What to do when TOTP is not configured. Options:

    • :halt - Return a 403 forbidden response (default)
    • :redirect_to_setup - Redirect to the TOTP setup page
    • {:redirect, path} - Redirect to a custom path
  • :setup_path - The path to redirect to for TOTP setup. Defaults to "/auth/totp/setup". Only used when :on_missing is :redirect_to_setup.

  • :current_user_assign - The assign key for the current user. Defaults to :current_user.

  • :error_message - The flash message to show when redirecting. Defaults to "Two-factor authentication required".

Examples

Require TOTP, redirect to setup if not configured

plug AshAuthentication.Phoenix.Plug.RequireTotp,
  resource: MyApp.Accounts.User,
  on_missing: :redirect_to_setup

Require TOTP, return 403 if not configured

plug AshAuthentication.Phoenix.Plug.RequireTotp,
  resource: MyApp.Accounts.User,
  on_missing: :halt

Custom redirect path

plug AshAuthentication.Phoenix.Plug.RequireTotp,
  resource: MyApp.Accounts.User,
  on_missing: {:redirect, "/settings/security"}