Dictator v1.1.0 Dictator View Source

Plug that checks if your users are authorised to access the resource.

You can use it at the router or controller level:

# lib/my_app_web/controllers/post_controller.ex
defmodule MyApp.PostController do
  plug Dictator

  def show(conn, params) do
    # ...
  end
end

# lib/my_app_web/router.ex
defmodule MyAppWeb.Router do
  pipeline :authorised do
    plug Dictator
  end
end

Requires Phoenix (or at least conn.private[:phoenix_action] to be set). To load resources from the database, requires Ecto. See Dictator.Policies.EctoSchema.

Dictator assumes your policies are in lib/my_app_web/policies/ and follow the MyAppWeb.Policies.Name naming convention. As an example, for posts, MyAppWeb.Policies.Post would be defined in lib/my_app_web/policies/post.ex.

It is also assumed the current user is loaded and available on conn.assigns. By default, it is assumed to be under conn.assigns[:current_user], although this option can be overriden.

Plug Options

Options that you can pass to the module, when plugging it (e.g. plug Dictator, only: [:create, :update]). None of the following options are required.

  • only: limits the actions to perform authorisation on to the provided list.
  • except: limits the actions to perform authorisation on to exclude the provided list.
  • policy: policy to apply. See above to understand how policies are inferred.
  • key: key under which the current user is placed in conn.assigns or the session. Defaults to :current_user.
  • fetch_strategy: Strategy to be used to get the current user. Can be either Dictator.FetchStrategies.Assigns to fetch it from conn.assigns or Dictator.FetchStrategies.Session to fetch it from the session. You can also implement your own strategy and pass it in this option or set it in the config. Defaults to Dictator.FetchStrategies.Assigns.

Configuration options

Options that you can place in your config/*.exs files.

  • key: Same as the :key parameter in the plug option section. The plug option takes precedence, meaning you can place it in a config and then override it in specific controllers or pipelines.
  • unauthorized_handler: Handler to be called when the user is not authorised to access the resource. Defaults to Dictator.UnauthorizedHandlers.Default.