Gardien v1.0.0 Gardien

Simple authorization functions that rely on Gardien.Policy protocol for verifying whether user is allowed to perform some action on a given resource. (see Gardien.Policy for more information on policy implementation details).

Gardien consists of several modules:

Configuration

user - optional

By default Gardien will try to extract user from conn.assigns using current_user key. In case you want to change this behaviour you can configure user as follows:

# specify key that can be used to extract user from `conn.assigns`, e.g
# %Plug.Conn{assigns: %{admin: user}}
config :gardien,
  user: :admin

# or
config :gardien,
  user: {MyHelpers, :gardien_user}
# where `gardien_user` is a function that takes `conn` as an argument

unauthorized_handler - function responsible for handling unauthorized actions.

Gardien comes with default handler that will raise Gardien.AuthorizationError in case user is not authorized to perform some action. It’s recommended to overwrite default handler as follows:

config :gardien,
  unauthorized_handler: {MyHelpers, :unauthorized_handler}
# where `:unauthorized_handler` is a function that takes `conn` and authorization `context` as arguments

Summary

Functions

Authorize user action on a given resource

Similiar to authorize/3 but returns :ok when user is authorized and raises Gardien.AuthorizationError otherwise

Functions

authorize(resource, conn, opts \\ [])

Authorize user action on a given resource

user (current user perfoming some action) is extracted from conn based on user configuration (see configuration section in Gardien module docs). It’s possible to overwrite user configuration by passing user as an option to authorization function.

By default Gardien infers policy action from controller action. In case controller action and policy action don’t match it’s possible to overwrite this behaviour by passing action as an option.

Returns {:ok, resource} when user is authorized and {:error, context} otherwise.

authorize!(resource, conn, opts \\ [])

Similiar to authorize/3 but returns :ok when user is authorized and raises Gardien.AuthorizationError otherwise.