- Add @type definitions to all schema modules: - User, UserCredential, Membership, Invitation - Organization, Site, AgentAssignment - InterfaceStat, SensorReading, Alert - Fix all compilation warnings with stronger Elixir types: - Remove unused require Logger in log_filter.ex - Remove unused parse_float(nil) clause - Add pin operators (^) for variables in binary pattern matches - Fix Dialyzer errors (25 → 0): - Remove unreachable pattern match clauses - Fix unmatched return values with _ = prefix - Update @spec for deliver_alert_notification/1 - Properly handle all Phoenix.PubSub.subscribe and Task.start return values - Explicitly ignore if statement return values where needed All files now pass mix compile --warnings-as-errors and mix dialyzer.
62 lines
1.7 KiB
Elixir
62 lines
1.7 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.start(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 -> {: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 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
|