towerops/lib/towerops_web/plugs/mobile_auth.ex
Graham McIntire b252cb81b9 fix: 5 more high-severity bugs (H6, H8, H17, H18)
- H6: batch interface stats query in get_site_capacity_summary, replacing
  per-interface SELECT with a single grouped query
- H8: explicit expires_at check in MobileAuth and GraphQLAuth plugs as
  defense in depth — the query already filters expired rows, but a future
  refactor dropping the filter can't quietly re-enable revoked sessions
- H17: Reports LiveView (toggle/delete/run_now) now uses
  Reports.get_organization_report/2 to scope by organization_id, fixing
  IDOR where a user could manipulate other tenants' reports by ID
- H18: ToweropsWeb.Api.ParamFilter strips identity fields (id,
  organization_id, user_id, created_by_id, inserted_at, updated_at) from
  user-supplied API params; applied to devices, sites, checks, and
  escalation_policies create/update paths to prevent mass-assignment of
  tenant ownership fields if a changeset cast list ever drifts
2026-05-12 11:04:31 -05:00

81 lines
2.3 KiB
Elixir

defmodule ToweropsWeb.Plugs.MobileAuth do
@moduledoc """
Plug for authenticating mobile app requests using bearer tokens.
Expects an Authorization header with format: "Bearer <token>"
On success, assigns :current_user and :current_mobile_session to the conn.
On failure, returns 401 Unauthorized.
"""
import Phoenix.Controller, only: [json: 2]
import Plug.Conn
alias Towerops.Accounts
alias Towerops.MobileSessions
def init(opts), do: opts
def call(conn, _opts) do
with {:ok, token} <- extract_token(conn),
{:ok, session} <- validate_session(token),
{:ok, user} <- get_user(session.user_id) do
# Touch the session to update last_used_at
_ =
Task.Supervisor.start_child(Towerops.TaskSupervisor, fn ->
MobileSessions.touch_session(session)
end)
conn
|> assign(:current_user, user)
|> assign(:current_mobile_session, session)
else
{:error, reason} ->
conn
|> put_status(:unauthorized)
|> json(%{error: error_message(reason)})
|> halt()
end
end
defp extract_token(conn) do
case get_req_header(conn, "authorization") do
["Bearer " <> token] -> {:ok, token}
_ -> {:error, :missing_token}
end
end
defp validate_session(token) do
case MobileSessions.get_session_by_token(token) do
nil ->
{:error, :invalid_token}
session ->
# Defense in depth: the query already filters expired rows, but
# explicitly verifying here means a refactor that drops the filter
# can't quietly re-enable revoked sessions.
if session_expired?(session) do
{:error, :invalid_token}
else
{:ok, session}
end
end
end
defp session_expired?(%{expires_at: nil}), do: true
defp session_expired?(%{expires_at: expires_at}) do
DateTime.compare(expires_at, DateTime.utc_now()) != :gt
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 error_message(:missing_token), do: "Authorization header is missing or invalid"
defp error_message(:invalid_token), do: "Invalid or expired authentication token"
defp error_message(:user_not_found), do: "User not found"
end