Sphinx
An authorization libriary for Phoenix application inspired by CanCan, Canary, and others. It follows Convention over Configuration design, yet allowing full customizations.
Installation
-
Add
sphinxto your list of dependencies inmix.exs:
```elixir
def deps do
[{:sphinx, "~> 0.1.0"}]
end
```
Then run mix deps.get to fetch the dependencies.
-
Configure
:repoin yourconfig.exs:
```elixir
config :sphinx, :repo, MyApp.Repo
```Usage
Say you want to authorize your PostController:
-
Create
web/authorizers/post_authorizer.exand defineauthorize?functions for each action in controller like:
```elixir
defmodule MyApp.PostAuthorizer do
def authorize?(_, :index, Post), do: true
def authorize?(_, :show, %Post{}), do: true
def authorize?(%User{}, :create, Post), do: true
def authorize?(%User{id: id}, action, %Post{author_id: id}) when action in [:update, :delete], do: true
def authorize?(_, _, _), do: false
end
```Call
plug :authorizeinside yourPostController. You may want toimport Sphinx.Plugsin yourweb.exfor controller scope.You can now access post in your controller actions like:
conn.assigns.resourceif authorization passes, and user gets 403 view if it fails.Profit!
See plug docs for more options.
Ensuring authorization
If you want to make sure all your requests are authorized, add this in your pipelines:
import Sphinx.Plugs
plug :ensure_authorization
Now, if any your requests is about to return without going through authorization, Sphinx would rise Sphinx.AuthorizationNotPerformedError.
You can skip authorization for some of your actions in controller like:
plug :skip_authorization, only: [:index, :show]License
MIT License, Copyright (c) 2016 Almas Sapargali