defmodule ChesstrainerWeb.UserLive.Registration do use ChesstrainerWeb, :live_view alias Chesstrainer.Accounts alias Chesstrainer.Accounts.User alias Chesstrainer.MailingList @impl true def render(assigns) do ~H"""

Register for an account

Already registered? <.link navigate={~p"/users/log-in"} class="font-semibold text-primary-text hover:underline" > Log in to your account now

<.form for={@form} id="registration_form" phx-submit="save" phx-change="validate"> <.input field={@form[:username]} type="text" label="Username" autocomplete="username" spellcheck="false" required phx-mounted={JS.focus()} /> <.input field={@form[:email]} type="email" label="Email" autocomplete="email" spellcheck="false" required /> <.input field={@form[:password]} type="password" label="Password" autocomplete="new-password" spellcheck="false" required /> <.input field={@form[:password_confirmation]} type="password" label="Confirm password" autocomplete="new-password" spellcheck="false" required /> <.input field={@form[:mailing_list]} type="checkbox" label="Send me occasional endgame tips and site news by email" /> <.button phx-disable-with="Creating account..." variant="primary" class="w-full"> Create an account
""" end @impl true def mount(_params, _session, socket) do if prelaunch?() do {:ok, redirect(socket, to: ~p"/")} else do_mount(socket) end end @impl true def handle_event("save", %{"user" => user_params}, socket) do if prelaunch?() do {:noreply, push_navigate(socket, to: ~p"/")} else save_registration(socket, user_params) end end def handle_event("validate", %{"user" => user_params}, socket) do changeset = Accounts.change_user_registration(%User{}, user_params, validate_unique: false) {:noreply, assign_form(socket, Map.put(changeset, :action, :validate))} end defp do_mount(%{assigns: %{current_scope: %{user: user}}} = socket) when not is_nil(user) do {:ok, redirect(socket, to: ChesstrainerWeb.UserAuth.signed_in_path(socket))} end defp do_mount(socket) do changeset = Accounts.change_user_registration(%User{}, %{}, validate_unique: false) {:ok, assign_form(socket, changeset), temporary_assigns: [form: nil]} end defp save_registration(socket, user_params) do case Accounts.register_user(user_params) do {:ok, user} -> if user.mailing_list, do: MailingList.subscribe_user(user) {:ok, _} = Accounts.deliver_user_confirmation_instructions( user, &url(~p"/users/confirm/#{&1}") ) {:noreply, socket |> put_flash( :info, "An email with instructions for how to confirm your email address has been sent to your inbox." ) |> push_navigate(to: ~p"/users/log-in")} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign_form(socket, changeset)} end end defp prelaunch?, do: Application.get_env(:chesstrainer, :prelaunch, false) defp assign_form(socket, %Ecto.Changeset{} = changeset) do form = to_form(changeset, as: "user") assign(socket, form: form) end end