Bodyguard v2.1.1 Bodyguard

Authorize actions at the boundary of a context

Please see the README.

Summary

Functions

Authorize a user’s action

The same as permit/4, but raises Bodyguard.NotAuthorizedError on authorization failure

The same as permit/4, but returns a boolean

Filter a query down to user-accessible items

Types

opts()
opts() :: keyword

Functions

permit(policy, action, user, params \\ [])
permit(policy :: module, action :: atom, user :: any, params :: any) :: Bodyguard.Policy.auth_result

Authorize a user’s action.

Returns :ok on success, and {:error, reason} on failure.

If params is a keyword list, it is converted to a map before passing down to the Bodyguard.Policy.authorize/3 callback. Otherwise, params is not changed.

permit!(policy, action, user, opts \\ [])
permit!(policy :: module, action :: atom, user :: any, opts :: opts) :: :ok

The same as permit/4, but raises Bodyguard.NotAuthorizedError on authorization failure.

Returns :ok on success.

Options

  • error_message – a string to describe the error (default “not authorized”)
  • error_status – the HTTP status code to raise with the error (default 403)

The remaining opts are converted into a params map and passed to the Bodyguard.Policy.authorize/3 callback.

permit?(policy, action, user, opts \\ [])
permit?(policy :: module, action :: atom, user :: any, opts :: opts) :: boolean

The same as permit/4, but returns a boolean.

scope(query, user, opts \\ [])
scope(query :: any, user :: any, opts :: keyword) :: any

Filter a query down to user-accessible items.

The query is introspected by Bodyguard in an attempt to automatically determine the schema type. To succeed, query must be an atom (schema module name), an Ecto.Query, or a list of structs.

This function exists primarily as a helper to import into a context and gain access to scoping for all schemas.

defmodule MyApp.Blog do
  import Bodyguard

  def list_user_posts(user) do
    Blog.Post
    |> scope(user)          # <-- defers to MyApp.Blog.Post.scope/3
    |> where(draft: false)
    |> Repo.all
  end
end

Options

  • schema - if the schema of the query cannot be determined, you must manually specify the schema here

The remaining opts are converted to a params map and passed to the Bodyguard.Schema.scope/3 callback on that schema.