PermissionEx

A simple Struct-based Permission system for Elixir. Created to be used with Phoenix but has no requirement or any real integration with it as this is designed to be entirely generic.

Installation

Available on Hex, the package can be installed by adding permission_ex to the list of dependencies in mix.exs:

def deps do
  [{:permission_ex, "~> 0.6.0"}]
end

Features

This is the current feature set of what is done, planned, and thought about. If any feature is not done yet or if any feature wants to be added that is not on this list then please open an issue and/or pull request to have it get done faster.

Usage

General usage will usually be something like reading either a tagged map or a specific permission set from, say, a database or elsewhere, then comparing it to a specific requirement.

For example, say you have this phoenix controller method:

def show(conn, _params) do
  conn
  |> render("index.html")
end

And if you have a permission set from the logged in user (or you can pre-fill an anonymous user permission set, or leave empty if anon should have no access to anything), say you have it on conn.assigns.perms and it is a tagged map, then you could test it like this:

def show(conn, _params) do
  if PermissionEx.test_tagged_permissions(MyApp.Perms.IndexPage{action: :show}, conn.assigns.perms) do
    conn
    |> render("index.html")
  else
    conn
    |> render("unauthorized.html")
  end
end

Examples

Please see PermissionEx for detailed examples.

All of the examples use these as the example structs:

defmodule PermissionEx.Test.Structs.User do
  @moduledoc false
  @derive [Poison.Encoder]
  defstruct name: nil
end

defmodule PermissionEx.Test.Structs.Page do
  @moduledoc false
  @derive [Poison.Encoder]
  defstruct action: nil
end

defmodule PermissionEx.Test.Structs.PageReq do
  @moduledoc false
  @derive [Poison.Encoder]
  defstruct action: nil
end

defmodule PermissionEx.Test.Structs.PagePerm do
  @moduledoc false
  @derive [Poison.Encoder]
  defstruct action: nil
end

Testing a specific permission: PermissionEx.test_permission/2

The required permission is the first argument, the allowed permission is on the right.

Testing a permission set against a requirement struct: PermissionEx.test_permissions/2

You can test a struct requirement against a permission map or list or maps or even against override values such as in:

Testing a tagged permission set against a requirement struct: PermissionEx.test_tagged_permissions/2

You can test a struct requirement against a map of permissions keyed on the requirement structs :__struct__ value.

There is also an override key of :admin, this is another tagged permission map or an override that is tested before the main permissions are tested.