5.7 KiB · text History 7bff5e7
defmodule VigilWeb.ApiTokenLive do
  @moduledoc """
  Personal API tokens for sentry-cli and other tools. A token is shown once,
  when it is made; only its hash is kept. Its scopes are narrowed in each
  organization to your role there.
  """
  use VigilWeb, :live_view

  alias Vigil.ApiTokens
  alias Vigil.Organizations.Roles

  # sentry-cli's release and sourcemap uploads need only this one.
  @default_scopes ["project:releases", "project:read", "org:read"]

  @impl true
  def mount(_params, _session, socket) do
    {:ok,
     socket
     |> assign(:page_title, "API tokens")
     |> assign(:form, new_form())
     |> assign(:new_token, nil)
     |> stream(:tokens, ApiTokens.list_tokens(socket.assigns.current_scope.user))}
  end

  defp new_form, do: to_form(ApiTokens.change_token(%{scopes: @default_scopes}), as: "token")

  @impl true
  def render(assigns) do
    assigns = assign(assigns, :all_scopes, Roles.all_scopes())

    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:tokens}>
      <div class="mx-auto max-w-3xl space-y-6">
        <.header>
          API tokens
          <:subtitle>
            For sentry-cli (<code class="font-mono">SENTRY_AUTH_TOKEN</code>) and other tools. In each
            organization a token can do only what your role there allows.
          </:subtitle>
        </.header>

        <div
          :if={@new_token}
          id="new-token"
          class="space-y-2 rounded-box border border-primary/40 bg-base-100 p-4"
        >
          <p class="text-sm font-medium">{@new_token.label}</p>
          <div class="join w-full">
            <input
              id="new-token-value"
              type="text"
              readonly
              value={@new_token.token}
              class="input input-sm join-item min-w-0 flex-1 font-mono text-xs"
              aria-label="Token"
            />
            <button
              id="copy-token"
              type="button"
              class="btn btn-sm btn-primary join-item"
              phx-click={JS.dispatch("phx:copy", to: "#new-token-value")}
            >
              <.icon name="hero-clipboard-document-micro" class="size-4" /> Copy
            </button>
          </div>
          <p class="text-xs text-warning">Copy it now: it won't be shown again.</p>
        </div>

        <.form
          for={@form}
          id="token-form"
          phx-submit="create"
          class="space-y-3 rounded-box border border-base-300 bg-base-200/60 p-4"
        >
          <.input field={@form[:label]} label="Label" placeholder="CI uploads" required />
          <fieldset>
            <legend class="mb-1 text-sm font-medium">Scopes</legend>
            <div class="grid grid-cols-2 gap-1 sm:grid-cols-4">
              <label :for={s <- @all_scopes} class="flex items-center gap-2 font-mono text-xs">
                <input
                  type="checkbox"
                  name="token[scopes][]"
                  value={s}
                  checked={s in (@form[:scopes].value || [])}
                  class="checkbox checkbox-xs"
                />
                {s}
              </label>
            </div>
            <p
              :for={msg <- Enum.map(@form[:scopes].errors, &translate_error/1)}
              class="mt-1 text-xs text-error"
            >
              {msg}
            </p>
          </fieldset>
          <.button class="btn btn-primary btn-sm" phx-disable-with="Creating…">Create token</.button>
        </.form>

        <ul
          id="tokens"
          phx-update="stream"
          class="divide-y divide-base-300 rounded-box border border-base-300"
        >
          <li id="tokens-empty" class="hidden p-4 text-center text-sm text-base-content/60 only:block">
            No tokens yet.
          </li>
          <li
            :for={{dom_id, t} <- @streams.tokens}
            id={dom_id}
            class="flex flex-wrap items-center gap-3 px-4 py-3"
          >
            <div class="min-w-0 flex-1">
              <p class="font-medium">
                {t.label} <span class="font-mono text-xs text-base-content/50">…{t.token_hint}</span>
              </p>
              <p class="font-mono text-xs text-base-content/60">{Enum.join(t.scopes, " ")}</p>
              <p class="text-xs text-base-content/50">
                {if t.last_used_at,
                  do: "last used #{Calendar.strftime(t.last_used_at, "%b %-d %H:%M")}",
                  else: "never used"}
              </p>
            </div>
            <button
              type="button"
              id={"revoke-#{dom_id}"}
              class="btn btn-ghost btn-xs text-error"
              phx-click="revoke"
              phx-value-id={t.id}
              data-confirm={"Revoke #{t.label}? Tools using it stop working."}
            >
              Revoke
            </button>
          </li>
        </ul>
      </div>
    </Layouts.app>
    """
  end

  @impl true
  def handle_event("create", %{"token" => params}, socket) do
    params = Map.put_new(params, "scopes", [])

    case ApiTokens.create_token(socket.assigns.current_scope.user, params) do
      {:ok, token} ->
        {:noreply,
         socket
         |> assign(:new_token, token)
         |> assign(:form, new_form())
         |> stream_insert(:tokens, token, at: 0)}

      {:error, changeset} ->
        {:noreply, assign(socket, :form, to_form(changeset, as: "token"))}
    end
  end

  def handle_event("revoke", %{"id" => id}, socket) do
    case ApiTokens.delete_token(socket.assigns.current_scope.user, id) do
      {:ok, token} ->
        {:noreply,
         socket
         |> update(:new_token, &if(&1 && &1.id == token.id, do: nil, else: &1))
         |> stream_delete(:tokens, token)}

      {:error, _} ->
        {:noreply, put_flash(socket, :error, "Couldn't revoke that token.")}
    end
  end
end