defmodule PrymnWeb.UserConfirmationLive do use PrymnWeb, :live_view alias Prymn.Accounts @impl true def render(%{live_action: :edit} = assigns) do ~H"""
<.header class="text-center">Email Confirm <.simple_form for={@form} id="confirmation_form" phx-submit="confirm_account"> <.input field={@form[:token]} type="hidden" /> <:actions> <.button phx-disable-with="Confirming..." class="w-full">Confirm my email
""" end @impl true def render(%{live_action: :new} = assigns) do ~H"""
<.header class="text-center"> No confirmation instructions received? <:subtitle>We'll send a new email confirmation link to your inbox. <.simple_form for={@form} id="confirmation_form" phx-submit="send_instructions"> <.input field={@form[:email]} type="email" placeholder="Email" required /> <:actions> <.button phx-disable-with="Sending..." class="w-full"> Resend confirmation instructions
<.link href={~p"/auth/register"} class="px-3">Register <.link href={~p"/auth/log_in"} class="px-3">Log in
""" end @impl true def mount(params, _session, socket) do {:ok, assign(socket, form: to_form(params, as: "user")), temporary_assigns: [form: nil]} end @impl true def handle_event("confirm_account", %{"user" => %{"token" => token}}, socket) do case Accounts.confirm_user(token) do {:ok, _} -> {:noreply, socket |> put_flash(:info, "Email confirmed successfully.") |> redirect(to: ~p"/")} :error -> # If there is a current user and the account was already confirmed, # then odds are that the confirmation link was already visited, either # by some automation or by the user themselves, so we redirect without # a warning message. case socket.assigns do %{current_user: %{confirmed_at: confirmed_at}} when not is_nil(confirmed_at) -> {:noreply, redirect(socket, to: ~p"/")} %{} -> {:noreply, socket |> put_flash(:error, "Email confirmation link is invalid or it has expired.") |> redirect(to: ~p"/")} end end end @impl true def handle_event("send_instructions", %{"user" => %{"email" => email}}, socket) do if user = Accounts.get_user_by_email(email) do Accounts.deliver_user_confirmation_instructions( user, &url(~p"/auth/confirm/#{&1}") ) end info = "If your email is in our system and it has not been confirmed yet, you will receive an email with instructions shortly." {:noreply, socket |> put_flash(:info, info) |> redirect(to: ~p"/")} end end