Current section

Files

Jump to
caravela priv templates auth_live_register.eex
Raw

priv/templates/auth_live_register.eex

defmodule <%= inspect @module %> do
@moduledoc """
Registration LiveView generated by Caravela from <%= inspect @domain_module %>.
Mounts the `<%= @component_ref %>` Svelte component via LiveSvelte.
Regenerate with `mix caravela.gen.auth <%= inspect @domain_module %>`.
Custom code placed below the `# --- CUSTOM ---` marker is preserved.
"""
use <%= @web_module_alias %>, :live_view
alias <%= inspect @auth_module %>, as: Auth
@impl true
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:errors, %{})
|> assign(:loading, false)
|> assign(:flash_message, nil)}
end
# --- CUSTOM :auth_live_register_mount ---
# --- END :auth_live_register_mount ---
@impl true
def handle_event("register", params, socket) do
socket = assign(socket, loading: true, errors: %{})
with :ok <- confirm_match(params),
{:ok, _user} <- Auth.register(params, request_context(socket)) do
{:noreply,
socket
|> assign(:loading, false)
|> put_flash(:info, "Account created. Check your email to confirm.")
|> push_navigate(to: "<%= @login_path %>")}
else
{:mismatch, _} ->
{:noreply,
socket
|> assign(:loading, false)
|> assign(:errors, %{password_confirmation: ["does not match"]})}
{:error, %Ecto.Changeset{} = cs} ->
{:noreply,
socket
|> assign(:loading, false)
|> assign(:errors, translate_errors(cs))}
{:error, reason} ->
{:noreply,
socket
|> assign(:loading, false)
|> assign(:errors, %{base: [to_string(reason)]})}
end
end
# --- CUSTOM :auth_live_register_handle_event ---
# --- END :auth_live_register_handle_event ---
@impl true
def render(assigns) do
~H"""
<LiveSvelte.svelte
name="<%= @component_ref %>"
props={%{
errors: @errors,
loading: @loading,
flash_message: @flash_message
}}
socket={@socket}
/>
"""
end
defp confirm_match(%{"password" => p, "password_confirmation" => p}), do: :ok
defp confirm_match(_), do: {:mismatch, :password_confirmation}
defp request_context(socket) do
%{
current_user: nil<%= if @multi_tenant do %>,
tenant_id: socket.assigns[:tenant_id]<% end %>
}
end
defp translate_errors(%Ecto.Changeset{} = cs) do
Ecto.Changeset.traverse_errors(cs, fn {msg, opts} ->
[
Enum.reduce(opts, msg, fn {k, v}, acc ->
String.replace(acc, "%{" <> Atom.to_string(k) <> "}", to_string(v))
end)
]
end)
end
<%= @custom_marker %>