Files
chess-endgame-trainer/lib/chesstrainer_web/live/user_live/registration.ex
T
owenrees 7cb7298236 Add user accounts, roles, and admin gating
- Scaffold password auth (email or username) with phx.gen.auth; no magic links
- Add role (member/moderator/admin/super_admin) and plan (free/premium) enums
- Gate /admin behind admin-or-above via plug + on_mount; hide the nav link
- Add mix accounts.promote for CLI role changes
- Disable email confirmation by confirming accounts at registration

Closes #3
2026-11-03 15:48:50 +01:00

105 lines
3.1 KiB
Elixir

defmodule ChesstrainerWeb.UserLive.Registration do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.User
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash} current_scope={@current_scope}>
<div class="mx-auto max-w-sm">
<div class="text-center">
<.header>
Register for an account
<:subtitle>
Already registered?
<.link navigate={~p"/users/log-in"} class="font-semibold text-brand hover:underline">
Log in
</.link>
to your account now.
</:subtitle>
</.header>
</div>
<.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
/>
<.button phx-disable-with="Creating account..." class="btn btn-primary w-full">
Create an account
</.button>
</.form>
</div>
</Layouts.app>
"""
end
@impl true
def mount(_params, _session, %{assigns: %{current_scope: %{user: user}}} = socket)
when not is_nil(user) do
{:ok, redirect(socket, to: ChesstrainerWeb.UserAuth.signed_in_path(socket))}
end
def mount(_params, _session, socket) do
changeset = Accounts.change_user_registration(%User{}, %{}, validate_unique: false)
{:ok, assign_form(socket, changeset), temporary_assigns: [form: nil]}
end
@impl true
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.register_user(user_params) do
{:ok, _user} ->
{:noreply,
socket
|> put_flash(:info, "Account created successfully. Please log in.")
|> push_navigate(to: ~p"/users/log-in")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign_form(socket, changeset)}
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 assign_form(socket, %Ecto.Changeset{} = changeset) do
form = to_form(changeset, as: "user")
assign(socket, form: form)
end
end