defmodule AshHqWeb.Pages.UserSettings do
@moduledoc "User settings page"
use Surface.LiveComponent
alias AshHqWeb.Router.Helpers, as: Routes
alias Surface.Components.Form
alias Surface.Components.Form.{ErrorTag, Field, Label, PasswordInput, Submit, TextInput}
prop current_user, :map, required: true
data email_form, :map
data password_form, :map
def render(assigns) do
~F"""
{#if !@current_user.confirmed_at}
{/if}
"""
end
@impl true
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign_forms()}
end
defp assign_forms(socket) do
assign(socket,
email_form:
AshPhoenix.Form.for_update(
socket.assigns.current_user,
:deliver_update_email_instructions,
as: "update_email",
api: AshHq.Accounts,
actor: socket.assigns.current_user
),
password_form:
AshPhoenix.Form.for_update(socket.assigns.current_user, :change_password,
as: "change_password",
api: AshHq.Accounts,
actor: socket.assigns.current_user
)
)
end
@impl true
def handle_event("validate_update_email", %{"update_email" => params}, socket) do
{:noreply,
assign(socket,
email_form: AshPhoenix.Form.validate(socket.assigns.email_form, params)
)}
end
@impl true
def handle_event("save_update_email", %{"update_email" => params}, socket) do
params =
Map.put(
params,
"update_url_fun",
&Routes.user_settings_url(AshHqWeb.Endpoint, :confirm_email, &1)
)
case AshPhoenix.Form.submit(socket.assigns.email_form, params: params) do
{:ok, _result} ->
{:noreply,
socket
|> put_flash(:info, "Check your email to confirm your new address.")
|> push_redirect(to: "/users/settings")}
{:error, email_form} ->
{:noreply, assign(socket, email_form: email_form)}
end
end
@impl true
def handle_event("validate_password", %{"change_password" => params}, socket) do
{:noreply,
assign(socket,
password_form: AshPhoenix.Form.validate(socket.assigns.password_form, params)
)}
end
@impl true
def handle_event("save_password", %{"change_password" => params}, socket) do
case AshPhoenix.Form.submit(socket.assigns.password_form, params: params) do
{:ok, _result} ->
{:noreply,
socket
|> put_flash(:info, "Password has been successfully changed.")
|> push_redirect(to: "/")}
{:error, password_form} ->
{:noreply, assign(socket, password_form: password_form)}
end
end
@impl true
def handle_event("resend_confirmation_instructions", _, socket) do
socket.assigns.current_user
|> Ash.Changeset.for_update(
:deliver_user_confirmation_instructions,
%{
confirmation_url_fun: &Routes.user_confirmation_url(AshHqWeb.Endpoint, :confirm, &1)
},
actor: socket.assigns.current_user
)
|> AshHq.Accounts.update!()
{:noreply, socket}
end
end