Imagine you have a few endpoints and would like to group their authorization rules. With live_session/3, can achieve that!
live_session
has three options:
-
session
- name of the session -
on_mount
- callback function -
root_layout
- apply a different layout to the group
It is important to understand the Security Considerations of live_session
, especially for handling authentication and authorization in your LiveView.
In the following example, we use live_session to set a new root_layout only for admin users and authorize admins only in the :admin
UserHook
live_session :admins,
root_layout: {ExampleWeb.AdminLayoutView, :root},
on_mount: {ExampleWeb.UserHook, :admin} do
scope "/", ExampleWeb do
pipe_through [:browser, :auth]
live "/admin", HomeLive, :page
end
end
defmodule ExampleWeb.AdminLayoutView do
@moduledoc false
use ExampleWeb, :view
def render("root.html", assigns) do
~H"""
<!DOCTYPE html>
<html lang="en">
<head>
<title>Admin Layout</title>
</head>
<body>
<h1>Admin</h1>
<main>
<%= @inner_content %>
</main>
</body>
</html>
"""
end
end
Top comments (0)