feat: add CheckPagePermission plug for page-level authorization
- Plug checks PermissionSets page list; redirects unauthorized to profile or sign-in. - Router: add plug to :browser pipeline; LiveHelpers: check_page_permission_on_params for client-side navigation (push_patch).
This commit is contained in:
parent
d7f6d1c03c
commit
b10b9c893c
3 changed files with 355 additions and 1 deletions
|
|
@ -5,15 +5,18 @@ defmodule MvWeb.LiveHelpers do
|
|||
## on_mount Hooks
|
||||
- `:default` - Sets the user's locale from session (defaults to "de")
|
||||
- `:ensure_user_role_loaded` - Ensures current_user has role relationship loaded
|
||||
- `:check_page_permission_on_params` - Attaches handle_params hook to enforce page permission on client-side navigation (push_patch)
|
||||
|
||||
## Usage
|
||||
Add to LiveView modules via:
|
||||
```elixir
|
||||
on_mount {MvWeb.LiveHelpers, :default}
|
||||
on_mount {MvWeb.LiveHelpers, :ensure_user_role_loaded}
|
||||
on_mount {MvWeb.LiveHelpers, :check_page_permission_on_params}
|
||||
```
|
||||
"""
|
||||
import Phoenix.Component
|
||||
alias MvWeb.Plugs.CheckPagePermission
|
||||
|
||||
def on_mount(:default, _params, session, socket) do
|
||||
locale = session["locale"] || "de"
|
||||
|
|
@ -26,6 +29,40 @@ defmodule MvWeb.LiveHelpers do
|
|||
{:cont, socket}
|
||||
end
|
||||
|
||||
def on_mount(:check_page_permission_on_params, _params, _session, socket) do
|
||||
{:cont,
|
||||
Phoenix.LiveView.attach_hook(
|
||||
socket,
|
||||
:check_page_permission,
|
||||
:handle_params,
|
||||
&check_page_permission_handle_params/3
|
||||
)}
|
||||
end
|
||||
|
||||
defp check_page_permission_handle_params(_params, uri, socket) do
|
||||
path = uri |> URI.parse() |> Map.get(:path, "/") || "/"
|
||||
|
||||
if CheckPagePermission.public_path?(path) do
|
||||
{:cont, socket}
|
||||
else
|
||||
user = socket.assigns[:current_user]
|
||||
host = uri |> URI.parse() |> Map.get(:host) || "localhost"
|
||||
|
||||
if CheckPagePermission.user_can_access_page?(user, path, router: MvWeb.Router, host: host) do
|
||||
{:cont, socket}
|
||||
else
|
||||
redirect_to = CheckPagePermission.redirect_target_for_user(user)
|
||||
|
||||
socket =
|
||||
socket
|
||||
|> Phoenix.LiveView.put_flash(:error, "You don't have permission to access this page.")
|
||||
|> Phoenix.LiveView.push_navigate(to: redirect_to)
|
||||
|
||||
{:halt, socket}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp ensure_user_role_loaded(socket) do
|
||||
user = socket.assigns[:current_user]
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue