dotfiles/app/lib/prymn_web/live/user_confirmation_live.ex
2023-11-23 15:45:33 +02:00

99 lines
3.1 KiB
Elixir

defmodule PrymnWeb.UserConfirmationLive do
use PrymnWeb, :live_view
alias Prymn.Accounts
@impl true
def render(%{live_action: :edit} = assigns) do
~H"""
<div class="mx-auto max-w-sm">
<.header class="text-center">Email Confirm</.header>
<.simple_form for={@form} id="confirmation_form" phx-submit="confirm_account">
<.input field={@form[:token]} type="hidden" />
<:actions>
<Button.primary phx-disable-with="Confirming..." class="w-full">
Confirm my email
</Button.primary>
</:actions>
</.simple_form>
</div>
"""
end
@impl true
def render(%{live_action: :new} = assigns) do
~H"""
<div class="mx-auto max-w-sm">
<.header class="text-center">
No confirmation instructions received?
<:subtitle>We'll send a new email confirmation link to your inbox.</:subtitle>
</.header>
<.simple_form for={@form} id="confirmation_form" phx-submit="send_instructions">
<.input field={@form[:email]} type="email" placeholder="Email" required />
<:actions>
<Button.primary phx-disable-with="Sending..." class="w-full">
Resend confirmation instructions
</Button.primary>
</:actions>
</.simple_form>
<div class="mt-4 flex justify-center divide-x text-sm">
<.link href={~p"/auth/register"} class="px-3">Register</.link>
<.link href={~p"/auth/log_in"} class="px-3">Log in</.link>
</div>
</div>
"""
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