(last updated: )
Announcing LetMe
LetMe is a new authorization library for Elixir featuring an easy to use DSL.
The readme and documentation are pretty comprehensive, so let me just give you a quick example here.
The core will be your policy module:
defmodule MyApp.Policy do
use LetMe.Policy
object :article do
action :create do
allow role: :editor
allow role: :writer
end
action :read do
allow true
deny :banned
end
action :update do
allow role: :editor
allow [:own_resource, role: :writer]
end
action :delete do
allow role: :editor
end
end
end
The policy module is accompanied by a check module:
defmodule MyApp.Policy.Checks do
alias MyApp.Accounts.User
def banned(%User{banned: banned}, _, _), do: banned
def own_resource(%User{id: id}, %{user_id: id}, _opts) when is_binary(id), do: true
def own_resource(_, _, _), do: false
def role(%User{role: role}, _object, role), do: true
def role(_, _, _), do: false
end
And with that configured, you can use one of the authorize functions wherever you need to make an authorization decision:
alias MyApp.Policy
def create_article(params, %User{} = current_user) do
with :ok <- Policy.authorize(:article_create, current_user) do
%Article{}
|> Article.changeset(params)
|> Repo.insert()
end
end
Or you can use one of the introspection functions to retrieve the rules you defined:
iex> MyApp.Policy.list_rules()
[
%LetMe.Rule{
action: :create,
allow: [
[role: :admin],
[role: :writer]
],
deny: [],
description: nil,
name: :article_create,
object: :article,
pre_hooks: []
},
# ...
]
That is the core of the library. There is also a Schema behaviour for helping you with query scopes and field redactions.
You can find a lot more details in the readme and documentation.
As always, like and subscribe.