add require role plug and restrict router routes

This commit is contained in:
shibao 2021-09-10 00:24:54 -04:00 committed by oliviasculley
parent fd5ebcce67
commit c20d1c1f5a
2 changed files with 39 additions and 23 deletions

View File

@ -139,6 +139,21 @@ defmodule CanneryWeb.UserAuth do
end
end
@doc """
Used for routes that require the user to be an admin.
"""
def require_role(conn, role: role_atom) do
if conn.assigns[:current_user] && conn.assigns.current_user.role == role_atom do
conn
else
conn
|> put_flash(:error, "You are not authorized to view this page.")
|> maybe_store_return_to()
|> redirect(to: Routes.home_path(conn, :index))
|> halt()
end
end
defp maybe_store_return_to(%{method: "GET"} = conn) do
put_session(conn, :user_return_to, current_path(conn))
end

View File

@ -1,6 +1,6 @@
defmodule CanneryWeb.Router do
use CanneryWeb, :router
import Phoenix.LiveDashboard.Router
import CanneryWeb.UserAuth
pipeline :browser do
@ -13,6 +13,10 @@ defmodule CanneryWeb.Router do
plug :fetch_current_user
end
pipeline :require_admin do
plug :require_role, role: :admin
end
pipeline :api do
plug :accepts, ["json"]
end
@ -20,23 +24,7 @@ defmodule CanneryWeb.Router do
scope "/", CanneryWeb do
pipe_through :browser
live "/", PageLive, :index
end
# Enables LiveDashboard only for development
#
# If you want to use the LiveDashboard in production, you should put
# it behind authentication and allow only admins to access it.
# If your application does not have an admins-only section yet,
# you can use Plug.BasicAuth to set up some basic authentication
# as long as you are also using SSL (which you should anyway).
if Mix.env() in [:dev, :test] do
import Phoenix.LiveDashboard.Router
scope "/" do
pipe_through :browser
live_dashboard "/dashboard", metrics: CanneryWeb.Telemetry, ecto_repos: [Cannery.Repo]
end
live "/", HomeLive, :index
end
## Authentication routes
@ -90,6 +78,19 @@ defmodule CanneryWeb.Router do
live "/ammo_groups/:id/show/edit", AmmoGroupLive.Show, :edit
end
scope "/", CanneryWeb do
pipe_through [:browser, :require_authenticated_user, :require_admin]
live_dashboard "/dashboard", metrics: CanneryWeb.Telemetry, ecto_repos: [Cannery.Repo]
live "/invites", InviteLive.Index, :index
live "/invites/new", InviteLive.Index, :new
live "/invites/:id/edit", InviteLive.Index, :edit
live "/invites/:id", InviteLive.Show, :show
live "/invites/:id/show/edit", InviteLive.Show, :edit
end
scope "/", CanneryWeb do
pipe_through [:browser]