An authorization libriary for Phoenix application inspired by CanCan, Canary, and others. It follows Convention over Configuration design, yet allowing full customizations.
- Add
sphinx
to 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
:repo
in yourconfig.exs
:
```elixir
config :sphinx, :repo, MyApp.Repo
```
Say you want to authorize your PostController
:
- Create
web/authorizers/post_authorizer.ex
and 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 :authorize
inside yourPostController
. You may want toimport Sphinx.Plugs
in yourweb.ex
for controller scope. -
You can now access post in your controller actions like:
conn.assigns.resource
if authorization passes, and user gets 403 view if it fails. -
Profit!
See plug docs for more options.
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]
MIT License, Copyright (c) 2016 Almas Sapargali