Current section

Files

Jump to
caravela priv templates auth_live_token_manager.eex
Raw

priv/templates/auth_live_token_manager.eex

defmodule <%= inspect @module %> do
@moduledoc """
API-token management LiveView generated by Caravela from
<%= inspect @domain_module %>.
Mount this LiveView behind an authenticated `live_session` — it
requires `current_user` to be assigned by the `on_mount` hook.
"""
use <%= @web_module_alias %>, :live_view
alias <%= inspect @auth_module %>, as: Auth
@impl true
def mount(_params, _session, socket) do
user = socket.assigns.current_user
tokens = Auth.list_api_tokens(user)
{:ok,
socket
|> assign(:tokens, tokens)
|> assign(:new_token, nil)
|> assign(:errors, %{})
|> assign(:loading, false)}
end
@impl true
def handle_event("create_token", %{"scope" => scope}, socket) do
user = socket.assigns.current_user
scope_atom = String.to_existing_atom(scope)
case Auth.create_api_token(user, scope_atom) do
{:ok, token, updated_user} ->
tokens = Auth.list_api_tokens(updated_user)
{:noreply,
socket
|> assign(:current_user, updated_user)
|> assign(:tokens, tokens)
|> assign(:new_token, token)
|> assign(:errors, %{})}
{:error, reason} ->
{:noreply, assign(socket, :errors, %{base: [inspect(reason)]})}
end
end
def handle_event("revoke_token", %{"id" => id}, socket) do
user = socket.assigns.current_user
case Auth.revoke_api_token(user, id) do
{:ok, updated_user} ->
tokens = Auth.list_api_tokens(updated_user)
{:noreply,
socket
|> assign(:current_user, updated_user)
|> assign(:tokens, tokens)
|> assign(:new_token, nil)}
{:error, _} ->
{:noreply, assign(socket, :errors, %{base: ["Could not revoke token"]})}
end
end
# --- CUSTOM :auth_live_token_manager ---
# --- END :auth_live_token_manager ---
@impl true
def render(assigns) do
~H"""
<LiveSvelte.svelte
name="<%= @component_ref %>"
props={%{
current_user: @current_user,
tokens: @tokens,
new_token: @new_token,
errors: @errors,
loading: @loading
}}
socket={@socket}
/>
"""
end
<%= @custom_marker %>