Gardien v1.0.0 Gardien.Authorization
Authorization plug
For more information on how to configure Gardien refer to Configuration section in Gardien module docs.
By default policy action is infered from controller action. In case
policy action and controller action do not match you can overwrite default
behaviour by passing actions map (see example below).
It’s also possible to overwrite configured user and unauthorized_handler.
Available options:
resource- required
Example:
plug Gardien.Authorization, resource: :post
# `:post` is a key that is used to fetch resource from `conn.assigns`
plug Gardien.Authorization, resource: {__MODULE__, :fetch_post}
# where `fetch_post` is a function that takes `conn` as an argument
# and returns `resource` that needs to be authorized, e.g:
def fetch_post(conn) do
Map.get(conn.assigns, :post)
end
user- optional
user option can be used in case you want to overwrite user configuration
Example:
plug Gardien.Authorization, resource: :post, user: :admin
# `:admin` is a key that is used to fetch user from `conn.assigns`
plug Gardien.Authorization, resource: :post, user: {__MODULE__, :current_user}
# where `current_user` is a function that takes `conn` as an argument and returns user.
unauthorized_handler- optional
unauthorized_handler option can be used in case you want to overwrite
unauthorized_handler configuration.
unauthorized_handler should be a function that takes conn and context as arguments
Example:
plug Gardien.Authorization, resource: :post, unauthorized_handler: {__MODULE__, :unauthorized_handler}
# unauthorized_handler example:
def unauthorized_handler(conn, %{resource: resource, action: action, user: user}=context) do
conn
|> send_resp(403, "You're are not authorized to perform that action")
|> halt
end
actions- optional
actions - maps controller actions to policy actions.
Is usefull when controller action and policy action do not match.
Example:
plug Gardien.Authorization, resource: :post, actions: %{edit: :edit_post}