towerops/lib/towerops_web/plugs/graphql_auth.ex
Graham McIntire 701ce12f08 perf+refactor: codebase-wide query and antipattern audit
Performance:
- schedule_live: preload page once instead of get_schedule!/1 per row
- alert_live + alerts: DB-side status filter; Repo.aggregate counts replace length/Enum.count over 500-row fetches on every event
- dashboard_live: drop duplicate get_device_status_counts; cap active alerts to 20 + use count_active_alerts/1
- maintenance.active_windows_for_device: 3 round-trips collapsed into one query (per-site-id branch keeps Postgres parameter types unambiguous)
- sites.build_site_tree: O(N^2) -> O(N) via group_by(parent_site_id)
- accounts.sole_owner_organizations: single group_by + having instead of per-org Repo.aggregate loop
- agents + agent_live (org + admin): count_assigned_devices_batch/1 + count_agent_polling_targets/1 (no preloads)
- alert_digest_worker: list_alerts_by_ids/1 batches digest fetch
- gaiia: distinct: true at DB; limit 50 on bidirectional ilike

Indexes:
- maintenance_windows(organization_id, starts_at, ends_at) WHERE suppress_alerts = true
- alerts(check_id) WHERE resolved_at IS NULL

Antipatterns:
- agents.delete_agent_token: PubSub.broadcast moved outside Repo.transaction so a rollback no longer leaves subscribers acting on a non-existent deletion
- integrations_controller.to_atom_keys: replaced String.to_existing_atom on user-controlled JSON keys with explicit allowlist
- 9 Task.start callsites converted to Task.Supervisor.start_child(Towerops.TaskSupervisor, ...) so background DB writes survive shutdown (test-mode discovery shims left as-is for sandbox semantics)
2026-04-28 16:58:51 -05:00

78 lines
2.1 KiB
Elixir

defmodule ToweropsWeb.Plugs.GraphQLAuth do
@moduledoc """
Plug for authenticating GraphQL requests using either API tokens or mobile session tokens.
Accepts two token types via Authorization: Bearer <token>:
- API tokens (prefixed with "towerops_") → sets current_organization_id + current_user
- Mobile session tokens → sets current_user only (no org_id)
Returns 401 Unauthorized if neither token type is valid.
"""
import Phoenix.Controller, only: [json: 2]
import Plug.Conn
alias Towerops.Accounts
alias Towerops.ApiTokens
alias Towerops.MobileSessions
def init(opts), do: opts
def call(conn, _opts) do
case get_req_header(conn, "authorization") do
["Bearer " <> token] ->
authenticate(conn, token)
_ ->
unauthorized(conn, "Missing or invalid Authorization header")
end
end
defp authenticate(conn, "towerops_" <> _ = token) do
case ApiTokens.verify_token(token) do
{:ok, organization_id, user} ->
conn
|> assign(:current_organization_id, organization_id)
|> assign(:current_user, user)
{:error, :invalid_token} ->
unauthorized(conn, "Invalid or expired API token")
end
end
defp authenticate(conn, token) do
with {:ok, session} <- validate_mobile_session(token),
{:ok, user} <- get_user(session.user_id) do
_ =
Task.Supervisor.start_child(Towerops.TaskSupervisor, fn ->
MobileSessions.touch_session(session)
end)
assign(conn, :current_user, user)
else
{:error, _reason} ->
unauthorized(conn, "Invalid or expired authentication token")
end
end
defp validate_mobile_session(token) do
case MobileSessions.get_session_by_token(token) do
nil -> {:error, :invalid_token}
session -> {:ok, session}
end
end
defp get_user(user_id) do
case Accounts.get_user(user_id) do
nil -> {:error, :user_not_found}
user -> {:ok, user}
end
end
defp unauthorized(conn, message) do
conn
|> put_status(:unauthorized)
|> json(%{error: message})
|> halt()
end
end