Raxol.Policy behaviour (Raxol v2.6.0)

View Source

Policy definition framework for Raxol.

Provides a DSL for defining resource-based access control policies.

Example

defmodule DocumentPolicy do
  use Raxol.Policy

  def can?(:read, user, document) do
    document.owner_id == user.id or
    user.role == :admin or
    document.public?
  end

  def can?(:write, user, document) do
    document.owner_id == user.id and
    not document.locked?
  end
end

# Usage
if DocumentPolicy.can?(:read, user, document) do
  show_document(document)
end

Summary

Callbacks

Callback for checking if an action is allowed.

Functions

Use this module to define a policy.

Authorize an action, returning a result tuple.

Authorize an action, raising if not allowed.

Filter a list of resources to only those the user can access.

Callbacks

can?(action, user, resource)

@callback can?(action :: atom(), user :: map(), resource :: any()) :: boolean()

Callback for checking if an action is allowed.

Functions

__using__(opts)

(macro)

Use this module to define a policy.

Example

defmodule MyPolicy do
  use Raxol.Policy

  def can?(:read, user, resource) do
    # Your authorization logic
    true
  end
end

authorize(policy, action, user, resource)

@spec authorize(module(), atom(), map(), any()) :: :ok | {:error, :unauthorized}

Authorize an action, returning a result tuple.

Example

case Raxol.Policy.authorize(MyPolicy, :read, user, resource) do
  :ok -> show_resource(resource)
  {:error, :unauthorized} -> show_error()
end

authorize!(policy, action, user, resource)

@spec authorize!(module(), atom(), map(), any()) :: :ok | no_return()

Authorize an action, raising if not allowed.

Example

Raxol.Policy.authorize!(MyPolicy, :read, user, resource)

filter(policy, action, user, resources)

@spec filter(module(), atom(), map(), list()) :: list()

Filter a list of resources to only those the user can access.

Example

readable_docs = Raxol.Policy.filter(DocumentPolicy, :read, user, documents)