View Source Bodyguard (Bodyguard v2.4.3)

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 returns a boolean.

Filter a query down to user-accessible items.

Types

@type action() :: atom() | String.t()
@type opts() :: keyword() | %{optional(atom()) => any()}

Functions

Link to this function

permit(policy, action, user, params \\ [])

View Source
@spec permit(policy :: module(), action :: action(), user :: any(), params :: any()) ::
  :ok | {:error, any()} | no_return()

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.

Link to this function

permit!(policy, action, user, params \\ [], opts \\ [])

View Source
@spec permit!(
  policy :: module(),
  action :: action(),
  user :: any(),
  params :: any(),
  opts :: opts()
) :: :ok | no_return()

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

Returns :ok on success.

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.

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)
Link to this function

permit?(policy, action, user, params \\ [])

View Source
@spec permit?(policy :: module(), action :: action(), user :: any(), params :: any()) ::
  boolean()

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

Link to this function

scope(query, user, params \\ [], opts \\ [])

View Source
@spec scope(query :: any(), user :: any(), params :: any(), opts :: opts()) :: 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

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

Options

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