berrypod/lib/berrypod_web/live/auth/registration.ex

91 lines
2.6 KiB
Elixir
Raw Normal View History

defmodule BerrypodWeb.Auth.Registration do
use BerrypodWeb, :live_view
2025-12-30 12:26:46 +00:00
alias Berrypod.Accounts
alias Berrypod.Accounts.User
2025-12-30 12:26:46 +00:00
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash} current_scope={@current_scope}>
<div class="mx-auto max-w-sm">
<div class="text-center">
<.header>
Register for an account
<:subtitle>
Already registered?
<.link navigate={~p"/users/log-in"} class="font-semibold text-brand hover:underline">
Log in
</.link>
to your account now.
</:subtitle>
</.header>
</div>
<.form for={@form} id="registration_form" phx-submit="save" phx-change="validate">
<.input
field={@form[:email]}
type="email"
label="Email"
autocomplete="username"
required
phx-mounted={JS.focus()}
/>
<.button phx-disable-with="Creating account..." variant="primary" class="w-full">
2025-12-30 12:26:46 +00:00
Create an account
</.button>
</.form>
</div>
</Layouts.app>
"""
end
@impl true
def mount(_params, _session, %{assigns: %{current_scope: %{user: user}}} = socket)
when not is_nil(user) do
{:ok, redirect(socket, to: BerrypodWeb.UserAuth.signed_in_path(socket))}
2025-12-30 12:26:46 +00:00
end
def mount(_params, _session, socket) do
# Admin exists (hook handles no-admin), registration is single-user only
{:ok,
socket
|> put_flash(:error, "Registration is closed")
|> redirect(to: ~p"/users/log-in")}
2025-12-30 12:26:46 +00:00
end
@impl true
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.register_user(user_params) do
{:ok, user} ->
{:ok, _} =
Accounts.deliver_login_instructions(
user,
&url(~p"/users/log-in/#{&1}")
)
{:noreply,
socket
|> put_flash(
:info,
"An email was sent to #{user.email}, please access it to confirm your account."
)
|> push_navigate(to: ~p"/users/log-in")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign_form(socket, changeset)}
end
end
def handle_event("validate", %{"user" => user_params}, socket) do
changeset = Accounts.change_user_email(%User{}, user_params, validate_unique: false)
{:noreply, assign_form(socket, Map.put(changeset, :action, :validate))}
end
defp assign_form(socket, %Ecto.Changeset{} = changeset) do
form = to_form(changeset, as: "user")
assign(socket, form: form)
end
end