2.7 KiB · text History bbb2a48
defmodule VigilWeb.Api.Auth do
  @moduledoc """
  `Authorization: Bearer <token>` for `/api/0/`, as sentry-cli sends it
  (`Vigil.ApiTokens`). Assigns `current_scope` with the token's user and
  scopes; the organization comes later, per request (`put_org/2`).

  With no Authorization header the request goes on unauthenticated
  (`GET /api/0/` answers that way, as GlitchTip's does); with a bad one it
  is refused here.
  """
  @behaviour Plug

  import Plug.Conn

  alias Vigil.Accounts.Scope
  alias Vigil.{ApiTokens, Organizations}

  @impl Plug
  def init(opts), do: opts

  @impl Plug
  def call(conn, _opts) do
    case get_req_header(conn, "authorization") do
      [] ->
        assign(conn, :current_scope, nil)

      ["Bearer " <> raw | _] ->
        case ApiTokens.fetch_by_raw(String.trim(raw)) do
          nil ->
            unauthorized(conn)

          token ->
            scope = token.user |> Scope.for_user() |> Scope.with_token(token, token.scopes)
            assign(conn, :current_scope, scope)
        end

      _ ->
        unauthorized(conn)
    end
  end

  @doc """
  Resolves `{org}` for the signed-in token: the scope gains the
  organization and membership, or the request ends 404 (as for an
  organization that doesn't exist, so membership isn't disclosed).
  """
  def put_org(conn, slug) do
    with %Scope{user: user} = scope <- conn.assigns[:current_scope],
         {org, member} <- Organizations.get_membership(user, slug) do
      {:ok, assign(conn, :current_scope, Scope.put_organization(scope, org, member))}
    else
      _ -> {:error, not_found(conn)}
    end
  end

  @doc "Ends the request 403 unless the scope has `api_scope` in its organization."
  def require_scope(conn, api_scope) do
    if Scope.can?(conn.assigns.current_scope, api_scope),
      do: {:ok, conn},
      else: {:error, json_error(conn, 403, "You do not have permission to perform this action.")}
  end

  @doc """
  Ends the request 403 unless the scope has one of `api_scopes`, as
  Sentry's `scope_map` lists several per method (`project:read`,
  `project:write` or `project:admin` may each read a project).
  """
  def require_any_scope(conn, api_scopes) do
    if Enum.any?(api_scopes, &Scope.can?(conn.assigns.current_scope, &1)),
      do: {:ok, conn},
      else: {:error, forbidden(conn)}
  end

  def forbidden(conn),
    do: json_error(conn, 403, "You do not have permission to perform this action.")

  def unauthorized(conn), do: json_error(conn, 401, "Invalid token")
  def not_found(conn), do: json_error(conn, 404, "Not found")

  def json_error(conn, status, detail) do
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(status, Jason.encode!(%{detail: detail}))
    |> halt()
  end
end