From 62996d883dc19b7e257a34704da2025cbb918a28 Mon Sep 17 00:00:00 2001 From: Carsten Date: Tue, 21 Apr 2026 22:51:41 +0200 Subject: [PATCH] feat(server): router pipelines + live_auth hook for authenticated dashboard --- server/lib/server_web/live_auth.ex | 14 ++++++++++++++ server/lib/server_web/router.ex | 27 ++++++++++++++++++++------- 2 files changed, 34 insertions(+), 7 deletions(-) create mode 100644 server/lib/server_web/live_auth.ex diff --git a/server/lib/server_web/live_auth.ex b/server/lib/server_web/live_auth.ex new file mode 100644 index 0000000..1889d93 --- /dev/null +++ b/server/lib/server_web/live_auth.ex @@ -0,0 +1,14 @@ +defmodule ServerWeb.LiveAuth do + @moduledoc "on_mount hook for LiveView sessions requiring authentication." + + import Phoenix.LiveView + import Phoenix.Component, only: [assign: 3] + + def on_mount(:require_authenticated, _params, session, socket) do + if session["authenticated"] do + {:cont, assign(socket, :authenticated, true)} + else + {:halt, redirect(socket, to: "/login")} + end + end +end diff --git a/server/lib/server_web/router.ex b/server/lib/server_web/router.ex index af8415e..bffd6f2 100644 --- a/server/lib/server_web/router.ex +++ b/server/lib/server_web/router.ex @@ -10,14 +10,33 @@ defmodule ServerWeb.Router do plug :put_secure_browser_headers end + pipeline :require_auth do + plug ServerWeb.Plugs.RequireAuth + end + pipeline :api do plug :accepts, ["json"] end + # Public login/logout scope "/", ServerWeb do pipe_through :browser - get "/", PageController, :home + get "/login", AuthController, :login + post "/login", AuthController, :create + delete "/logout", AuthController, :delete + end + + # Authenticated dashboard (LiveView) + scope "/", ServerWeb do + pipe_through [:browser, :require_auth] + + live_session :authenticated, on_mount: {ServerWeb.LiveAuth, :require_authenticated} do + live "/", OverviewLive, :index + live "/hosts/:name", HostDetailLive, :show + live "/vms", VmSearchLive, :index + live "/admin/hosts", AdminHostsLive, :index + end end scope "/api", ServerWeb do @@ -26,13 +45,7 @@ defmodule ServerWeb.Router do get "/hosts/:name", HostController, :show end - # Enable LiveDashboard in development if Application.compile_env(:server, :dev_routes) do - # If you want to use the LiveDashboard in production, you should put - # it behind authentication and allow only admins to access it. - # If your application does not have an admins-only section yet, - # you can use Plug.BasicAuth to set up some basic authentication - # as long as you are also using SSL (which you should anyway). import Phoenix.LiveDashboard.Router scope "/dev" do