cassette_plug v1.1.0 Cassette.Controller
A helper module to quickly validate roles and get the current user
To use in your controller, add as a plug restricting the actions:
defmodule MyApp.MyController do
use MyApp.Web, :controller
use Cassette.Controller
plug :require_role!, "ADMIN" when action in [:edit, :update, :new, :create]
def update(conn, %{"id" => id}) do
something = Repo.get!(Something, id)
changeset = Something.changeset(something)
render(conn, "edit.html", something: something, changeset: changeset)
end
end
You can also customize how a forbidden situation is handled:
defmodule MyApp.MyController do
use MyApp.Web, :controller
use Cassette.Controller, on_forbidden: fn(conn) ->
redirect(conn, to: "/403.html")
end
plug :require_role!("VIEWER")
def index(conn, _params) do
render(conn, "index.html")
end
end
You can use one of your controller functions as well:
defmodule MyApp.MyController do
use MyApp.Web, :controller
use Cassette.Controller, on_forbidden: &MyApp.MyController.forbidden/1
plug :require_role!("VIEWER")
def index(conn, _params) do
render(conn, "index.html")
end
end
Or since require_role!/2
halts the connection you may do the following for simple actions.
defmodule MyApp.MyController do
use MyApp.Web, :controller
use Cassette.Controller
def index(conn, _params) do
conn
|> require_role!("VIEWER")
|> render("index.html")
end
end
You can also write your own plugs using the “softer” has_role?/2
or has_raw_role?/2
:
defmodule MyApp.MyController do
use MyApp.web, :controller
use Cassette.Controller
plug :check_authorization
def index(conn, _params) do
render(conn, "index.html")
end
def check_authorization(conn, _params) do
if has_role?("viewer") do
conn
else
conn |> render("forbidden.html") |> halt
end
end
end