2023-10-12 03:03:10 +00:00
|
|
|
defmodule PhoenixPasskeysWeb.UserSettingsController do
|
|
|
|
use PhoenixPasskeysWeb, :controller
|
|
|
|
|
|
|
|
alias PhoenixPasskeys.Accounts
|
|
|
|
|
2023-10-15 02:46:30 +00:00
|
|
|
plug :assign_email_changesets
|
2023-10-12 03:03:10 +00:00
|
|
|
|
|
|
|
def edit(conn, _params) do
|
|
|
|
render(conn, :edit)
|
|
|
|
end
|
|
|
|
|
|
|
|
def update(conn, %{"action" => "update_email"} = params) do
|
2023-10-15 02:46:30 +00:00
|
|
|
%{"user" => user_params} = params
|
2023-10-12 03:03:10 +00:00
|
|
|
user = conn.assigns.current_user
|
|
|
|
|
2023-10-15 02:46:30 +00:00
|
|
|
case Accounts.apply_user_email(user, user_params) do
|
2023-10-12 03:03:10 +00:00
|
|
|
{:ok, applied_user} ->
|
|
|
|
Accounts.deliver_user_update_email_instructions(
|
|
|
|
applied_user,
|
|
|
|
user.email,
|
|
|
|
&url(~p"/users/settings/confirm_email/#{&1}")
|
|
|
|
)
|
|
|
|
|
|
|
|
conn
|
|
|
|
|> put_flash(
|
|
|
|
:info,
|
|
|
|
"A link to confirm your email change has been sent to the new address."
|
|
|
|
)
|
|
|
|
|> redirect(to: ~p"/users/settings")
|
|
|
|
|
|
|
|
{:error, changeset} ->
|
|
|
|
render(conn, :edit, email_changeset: changeset)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def confirm_email(conn, %{"token" => token}) do
|
|
|
|
case Accounts.update_user_email(conn.assigns.current_user, token) do
|
|
|
|
:ok ->
|
|
|
|
conn
|
|
|
|
|> put_flash(:info, "Email changed successfully.")
|
|
|
|
|> redirect(to: ~p"/users/settings")
|
|
|
|
|
|
|
|
:error ->
|
|
|
|
conn
|
|
|
|
|> put_flash(:error, "Email change link is invalid or it has expired.")
|
|
|
|
|> redirect(to: ~p"/users/settings")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-10-15 02:46:30 +00:00
|
|
|
defp assign_email_changesets(conn, _opts) do
|
2023-10-12 03:03:10 +00:00
|
|
|
user = conn.assigns.current_user
|
|
|
|
|
|
|
|
conn
|
|
|
|
|> assign(:email_changeset, Accounts.change_user_email(user))
|
|
|
|
end
|
|
|
|
end
|