sb logoToday I Learned

What you should know about the live_session macro

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:

  1. session - name of the session
  2. on_mount - callback function
  3. 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 :adminUserHook

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
defmodule ExampleWeb.AdminLayoutView do
  @moduledoc false
  use ExampleWeb, :view

  def render("root.html", assigns) do
    <!DOCTYPE html>
    <html lang="en">
        <title>Admin Layout</title> 
          <%= @inner_content %>