Bodyguard v2.4.0 Bodyguard.Plug.Authorize

Perform authorization in a Plug pipeline.

Options

  • :policy required - the policy (or context) module
  • :action required - the action, or a getter
  • :user - the user getter
  • :params - the params, or a getter, to pass to the authorization callbacks
  • :fallback - a fallback controller or plug to handle authorization failure. If specified, the plug is called and then the pipeline is halted. If not specified, then Bodyguard.NotAuthorizedError raises directly to the router.

Option Getters

The options :action, :user, and :params can accept getter functions that are either:

  • an anonymous 1-arity function that accepts the conn and returns a value
  • a {module, function_name} tuple specifying an existing function with that same signature

Default Plug Options

Application-wide defaults for the above options can be specified in the application config. For example, if you're using Phoenix with Pow for authentication, you might want to specify:

config :bodyguard, Bodyguard.Plug.Authorize,
  action: {Phoenix.Controller, :action_name},
  user: {Pow.Plug, :current_user}

Examples

# Raise on failure
plug Bodyguard.Plug.Authorize,
  policy: MyApp.Blog,
  action: &action_name/1,
  user: {MyApp.Authentication, :current_user}

# Fallback on failure
plug Bodyguard.Plug.Authorize,
  policy: MyApp.Blog,
  action: &action_name/1,
  user: {MyApp.Authentication, :current_user},
  fallback: MyAppWeb.FallbackController

# Params as a function
plug Bodyguard.Plug.Authorize,
  policy: MyApp.Blog,
  action: &action_name/1,
  user: {MyApp.Authentication, :current_user},
  params: &get_params/1

Link to this section Summary

Functions

Callback implementation for Plug.call/2.

Callback implementation for Plug.init/1.

Link to this section Functions

Link to this function

call(conn, arg)

Callback implementation for Plug.call/2.

Link to this function

init(opts \\ [])

Callback implementation for Plug.init/1.

Link to this function

valid_getter?(fun)