DEV Community

Cover image for What you should know about the live_session macro
Herminio Torres
Herminio Torres

Posted on

4

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 :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
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️