defmodule PlausibleWeb.Live.Plugins.API.Settings do @moduledoc """ LiveView allowing listing, creating and revoking Plugins API tokens. """ use Phoenix.LiveView use Phoenix.HTML alias Plausible.Sites alias Plausible.Plugins.API.Tokens def mount( _params, %{"domain" => domain, "current_user_id" => user_id} = session, socket ) do socket = socket |> assign_new(:site, fn -> Sites.get_for_user!(user_id, domain, [:owner, :admin, :super_admin]) end) |> assign_new(:displayed_tokens, fn %{site: site} -> Tokens.list(site) end) {:ok, assign(socket, domain: domain, add_token?: not is_nil(session["new_token"]), token_description: String.capitalize(session["new_token"] || ""), current_user_id: user_id )} end def render(assigns) do ~H""" <.live_component id="embedded_liveview_flash" module={PlausibleWeb.Live.Flash} flash={@flash} /> <%= if @add_token? do %> <%= live_render( @socket, PlausibleWeb.Live.Plugins.API.TokenForm, id: "token-form", session: %{ "current_user_id" => @current_user_id, "domain" => @domain, "token_description" => @token_description, "rendered_by" => self() } ) %> <% end %>
+ Add Token
<%= for token <- @displayed_tokens do %> <% end %>
Description Hint Last used Revoke
<%= token.description %> **********<%= token.hint %> <%= Plausible.Plugins.API.Token.last_used_humanize(token) %>
""" end def handle_event("add-token", _params, socket) do {:noreply, assign(socket, :add_token?, true)} end def handle_event("revoke-token", %{"token-id" => token_id}, socket) do :ok = Tokens.delete(socket.assigns.site, token_id) displayed_tokens = Enum.reject(socket.assigns.displayed_tokens, &(&1.id == token_id)) {:noreply, assign(socket, add_token?: false, displayed_tokens: displayed_tokens)} end def handle_info(:cancel_add_token, socket) do {:noreply, assign(socket, add_token?: false)} end def handle_info({:token_added, token}, socket) do displayed_tokens = [token | socket.assigns.displayed_tokens] socket = put_flash(socket, :success, "Plugins API Token created successfully") Process.send_after(self(), :clear_flash, 5000) {:noreply, assign(socket, displayed_tokens: displayed_tokens, add_token?: false, token_description: "" )} end def handle_info(:clear_flash, socket) do {:noreply, clear_flash(socket)} end end