feat(server): router pipelines + live_auth hook for authenticated dashboard

This commit is contained in:
Carsten 2026-04-21 22:51:41 +02:00
parent 4538945b85
commit 62996d883d
2 changed files with 34 additions and 7 deletions

View file

@ -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

View file

@ -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