Gardien v1.0.0 Gardien.Controller

Controller authorization functions.

Summary

Functions

Authorize user action on a given resource

Functions

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

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.

authorized_handler function is executed only if user is authorized. In case user is not authorized - action is handled by configured unauthorized_handler (see unauthorized_handler configuration examples in Gardien module docs). It’s possible to overwrite configured unauthorized_handler by passing unauthorized_handler as an option.

Example:

# in controller action
def show(conn, params) do
  post = Repo.get(Post, params["id"])

  authorize post, conn, fn ->   # <-------------- handle authorized user
    render conn, "show.html", post: post
  end
end

# in case you need to overwrite configured `unauthorized_handler`, `user` or assumed policy `action`
authorize post, conn, [unauthorized_handler: {__MODULE__, :unauthorized_handler}], fn ->
  render conn, "show.html", post: post
end

authorize post, conn, [user: user], fn ->
  render conn, "show.html", post: post
end

authorize post, conn, [action: :show_post], fn ->
  render conn, "show.html", post: post
end