towerops/lib/towerops_web/live/agent_live/edit.ex
Graham McIntire c066399e18
Allow superadmins to view and edit any agent regardless of org
The admin agents page links to /agents/:id but the show and edit
pages were scoped to the current user's organization, causing 404s
for agents belonging to other orgs.
2026-02-10 12:19:20 -06:00

62 lines
1.8 KiB
Elixir

defmodule ToweropsWeb.AgentLive.Edit do
@moduledoc false
use ToweropsWeb, :live_view
use Gettext, backend: ToweropsWeb.Gettext
import ToweropsWeb.GettextHelpers
alias Towerops.Agents
alias Towerops.Agents.AgentToken
@impl true
def mount(%{"id" => id}, _session, socket) do
organization = socket.assigns.current_scope.organization
current_user = socket.assigns.current_scope.user
# Superadmins can edit any agent; regular users only their org's agents
agent_token =
if current_user.is_superuser do
Towerops.Repo.get!(AgentToken, id)
else
Towerops.Repo.get_by!(AgentToken, id: id, organization_id: organization.id)
end
changeset = AgentToken.update_changeset(agent_token, %{})
{:ok,
socket
|> assign(:page_title, "Edit #{agent_token.name}")
|> assign(:timezone, socket.assigns.current_scope.timezone)
|> assign(:agent_token, agent_token)
|> assign(:form, to_form(changeset))}
end
@impl true
def handle_params(_params, _url, socket) do
{:noreply, socket}
end
@impl true
def handle_event("validate", %{"agent_token" => agent_params}, socket) do
changeset =
socket.assigns.agent_token
|> AgentToken.update_changeset(agent_params)
|> Map.put(:action, :validate)
{:noreply, assign(socket, :form, to_form(changeset))}
end
@impl true
def handle_event("save", %{"agent_token" => agent_params}, socket) do
case Agents.update_agent_token(socket.assigns.agent_token, agent_params) do
{:ok, agent_token} ->
{:noreply,
socket
|> put_flash(:info, t_equipment("Agent updated successfully"))
|> push_navigate(to: ~p"/agents/#{agent_token.id}")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :form, to_form(changeset))}
end
end
end