Bodyguard.Plug.Authorize (Bodyguard v2.4.2) View Source
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 ishalt
ed. If not specified, thenBodyguard.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
You can provide default options for this plug by simply wrapping your own plug around it. For example, if you're using Phoenix with Pow for authentication, you might want to specify:
defmodule MyAppWeb.Authorize do
def init(opts) do
opts
|> Keyword.put_new(:action, {Phoenix.Controller, :action_name})
|> Keyword.put_new(:user, {Pow.Plug, :current_user})
|> Bodyguard.Plug.Authorize.init()
end
def call(conn, opts) do
Bodyguard.Plug.Authorize.call(conn, opts)
end
end
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