RobertoSchneiders

RobertoSchneiders

I’m trying to get a centralized authentication/authorization system working by using the LiveView on_mount hook, not the handle_params.

This app has pages with different levels of authorization:

  • public: can be accessed by anyone, no need to be authenticated
  • require authentication: need authenticated users
  • require a specific user role: only users with specific roles can access (i.e :admin)

The users can live navigate through those pages, so an unauthenticated user may be able to click a button that navigates to a live view where authentication is required. So the objectives are pretty simple:

  • If an unauthenticated user is trying to (live) navigate to a LiveView that requires authentication, we redirect to login.
  • after logging in the user is redirected back to the page he wanted to access in the first place (important bit).
  • if the user is authenticated but not authorized, we just redirect to home and show a flash message.

I have a module that handles the app authorization based on the URI:

MyApp.authorized(user, uri)

My router:

  live_session :default,
    on_mount: [
      {MyAppWeb.UserAuth, :mount_current_user},
      {MyAppWeb.UserAuth, :ensure_authorized}
    ] do
...

How do I get or build the URI in the on_mount stage? I saw several forum posts and GitHub issues talking about using the handle_params instead. However, that creates several issues in my existing live views because the LiveViews on_mount are executing before authentication/authorization is done. Ideally, I would like to only run the LiveView code once authorization is done. I saw we use to have a few routing helpers (live_path) that would allow me to create the URI based on the live view module (socket.view) and params but that doesn’t exist anymore.

  def on_mount(:ensure_authorized, _params, _session, socket) do
    uri =  "" # <- how to get or build the URI at this stage???

    %{assigns: %{current_user: current_user}} = socket

    case Authorization.authorized(current_user, uri) do
      true ->
        socket
        |> Phoenix.Component.assign(:live_url, uri)
        |> cont()

      {:error, :not_authorized} ->
        socket
        |> Phoenix.LiveView.put_flash(:error, "Not Authorized")
        |> Phoenix.LiveView.redirect(to: ~p"/")
        |> halt()

      {:error, :requires_login} ->
        socket
        |> Phoenix.LiveView.put_flash(:error, "You must log in to access this page.")
        |> Phoenix.LiveView.redirect(to: ~p"/users/log_in?#{%{return_to: uri}}")
        |> halt()
    end
  end

Showing Posts 1 to 6

krasenyp

krasenyp

I’m not sure your idea would work because when you live navigate, the LiveView you’re navigating to doesn’t get mounted, only handle_params gets run.

Schultzer

Schultzer

Yup, he would have to do both, I’ve built SSO authentication with assent and phoenix token that way, actually not only do you have to auth on mount and handle_params but also on regular plug. It can pay divided to centralize all this is in an Auth module that act as on_mount hook and a plug.

RobertoSchneiders

RobertoSchneiders OP

I’m not sure I got it, can you elaborate? For me, every time I navigate from one LiveView to another, mount (and on_mount) is called. I think the only time when mount is not called is when you navigate using live_patch to the same LiveView, just changing URL parameters.

RobertoSchneiders

RobertoSchneiders OP

Right, I’m definitely doing authentication/authorization on regular plug as well, which is way easier. Running the authorization layer in handle_params is also a non-issue since the URI is available, the problem is the on_mount, which doesn’t have the URI and I’m struggling to find a way to redirect to login and then back to the desired live view using on_mount.

mudspot

mudspot

Below is what I do in my codeset. Modify the track_page definition, (which has the url) to your liking - put your authorization codes there.

defmodule CheckDWeb.Pipelines.PageTracker do
  use CheckDWeb, :live_view

  def on_mount(
        _default,
        _params,
        _session,
        socket
      ) do
    if connected?(socket) do
      socket =
        socket
        |> attach_hook(:page_tracker, :handle_params, &track_page/3)

      {:cont, socket}
    else
      {:cont, socket}
    end
  end

  def track_page(_params, url, socket) do
    %{path: request_path} = URI.parse(url)

    {:cont, socket |> assign(:request_path, request_path)}
  end
end

In my router

  scope "/", CheckDWeb do
    pipe_through [:browser]

    live_session :default,
      on_mount: [CheckDWeb.Pipelines.PageTracker] do
      live "/create-profile", Live.MyData.CreateProfile
      live "/settings", Live.MyData.Settings, :main
Schultzer

Schultzer

If the URL is dynamic, store it in the session and put the logic in a session controller, then your redirect in your mount will be generic.

mount sucks for these kind of operations, since it’s only handle_params that contain the URL as you state, so your only bet is to store in the session and handle_params assign the return_url when session expires for long lived live view, to this date there is no rock solid way to handle this, and you will have to duplicate work. In the end this comes down to LV design and since we’re at 1.0.0 I’m not sure there will ever be an ergonomic solution in mount.

You can always store it in a table in the database, but that is not ideal either.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews