1.4 KiB · text History 44bc4f7
defmodule CartosnapAppWeb.Api.Auth do
  @moduledoc """
  Bearer-key authentication for `/api/v1`, the Android app's API.

  Reads `Authorization: Bearer <key>` (a paired device's key, from
  `CartosnapApp.Accounts.create_api_token/2`) and assigns `:current_scope`,
  as the browser pipeline does, so controllers call the contexts just as
  the LiveViews do; and `:current_api_token_id`, the device's own key.
  Anything else is a 401 in the API's error shape.
  """

  import Plug.Conn

  alias CartosnapApp.Accounts
  alias CartosnapApp.Accounts.Scope
  alias CartosnapAppWeb.Api.ErrorJSON

  def init(opts), do: opts

  def call(conn, _opts) do
    with [header] <- get_req_header(conn, "authorization"),
         {:ok, token} <- parse_bearer(header),
         {user, token_id} <- Accounts.fetch_user_by_api_token(token) do
      conn
      |> assign(:current_scope, Scope.for_user(user))
      |> assign(:current_api_token_id, token_id)
    else
      _ ->
        conn
        |> put_status(:unauthorized)
        |> Phoenix.Controller.json(ErrorJSON.error(:unauthenticated))
        |> halt()
    end
  end

  # The scheme is case-insensitive (RFC 9110 §11.1).
  defp parse_bearer(header) do
    case String.split(header, " ", parts: 2) do
      [scheme, token] when token != "" ->
        if String.downcase(scheme) == "bearer", do: {:ok, String.trim(token)}, else: :error

      _ ->
        :error
    end
  end
end