Files
chess-endgame-trainer/lib/chesstrainer/accounts/user.ex
T
owenrees 80cb033077 Add theme slugs, kinds and link provenance (#192)
* add function for upgrading a user's plan in interactive Elixir

* Add theme slugs, kinds and link provenance

Themes gain a stable slug, an optional description and a kind so the app can
tell material, motif and technique labels apart. Slugs are generated from the
name on first save and keep their value when the theme is renamed, so links to
a theme stay valid.

Endgame-to-theme links now record their source (derived, curated or community)
and creation time. Existing links are backfilled as curated. A derived pass can
therefore replace only its own links, leaving human work untouched.

The admin index shows each theme's kind and its coverage across the library.
Creating a theme name requires the manage_themes capability, and members get an
unauthorized error instead, ahead of the suggestion flow.

Closes #185
2026-11-17 20:46:43 +01:00

231 lines
7.2 KiB
Elixir

defmodule Chesstrainer.Accounts.User do
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "users" do
field :email, :string
field :username, :string
field :password, :string, virtual: true, redact: true
field :hashed_password, :string, redact: true
field :role, Ecto.Enum, values: [:member, :moderator, :admin, :super_admin], default: :member
field :plan, Ecto.Enum, values: [:free, :premium], default: :free
field :rating, :float, default: 1500.0
field :rating_deviation, :float, default: 350.0
field :confirmed_at, :utc_datetime
field :authenticated_at, :utc_datetime, virtual: true
field :mailing_list, :boolean, virtual: true, default: false
timestamps(type: :utc_datetime)
end
@type t :: %__MODULE__{}
@doc """
A user changeset for registration.
It requires an email, a username and a password, and sets no role or plan:
those are programmatic values that only the promote task may change.
## Options
* `:validate_unique` - Set to false if you don't want to validate the
uniqueness of the email and username, useful when displaying live
validations. Defaults to `true`.
* `:hash_password` - Hashes the password when true. Defaults to `true`.
"""
def registration_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:email, :username, :password, :mailing_list])
|> validate_email(opts)
|> validate_username(opts)
|> validate_confirmation(:password, message: "does not match password")
|> validate_password(opts)
end
@doc """
A user changeset for changing the role.
The role is programmatic and must never be cast from user-supplied params.
"""
def role_changeset(user, attrs) do
user
|> cast(attrs, [:role])
|> validate_required([:role])
end
@doc """
A user changeset for changing the plan.
The plan is programmatic and must never be cast from user-supplied params.
"""
def plan_changeset(user, attrs) do
user
|> cast(attrs, [:plan])
|> validate_required([:plan])
end
@doc """
A user changeset for an admin-created invitation.
The account is created without a password and marked confirmed, so the
recipient can choose a password from the emailed invitation link and log in
immediately afterwards. Role and plan are applied separately by
`admin_changeset/2` after the caller has checked the policy.
"""
def invite_changeset(user, attrs) do
user
|> cast(attrs, [:email, :username])
|> validate_email([])
|> validate_username([])
|> put_change(:confirmed_at, DateTime.utc_now(:second))
end
@doc """
A user changeset for the fields an administrator may edit.
These values are programmatic, so this changeset is only used by the scoped
admin functions in `Chesstrainer.Accounts`.
"""
def admin_changeset(user, attrs) do
cast(user, attrs, [:role, :plan])
end
@doc """
A user changeset for registering or changing the email.
It requires the email to change otherwise an error is added.
## Options
* `:validate_unique` - Set to false if you don't want to validate the
uniqueness of the email, useful when displaying live validations.
Defaults to `true`.
"""
def email_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:email])
|> validate_email(opts)
end
defp validate_email(changeset, opts) do
changeset =
changeset
|> validate_required([:email])
|> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/,
message: "must have the @ sign and no spaces"
)
|> validate_length(:email, max: 160)
if Keyword.get(opts, :validate_unique, true) do
changeset
|> unsafe_validate_unique(:email, Chesstrainer.Repo)
|> unique_constraint(:email)
|> validate_email_changed()
else
changeset
end
end
defp validate_username(changeset, opts) do
changeset =
changeset
|> validate_required([:username])
|> validate_length(:username, min: 3, max: 30)
|> validate_format(:username, ~r/\A[a-zA-Z0-9_]+\z/,
message: "only letters, numbers and underscores"
)
if Keyword.get(opts, :validate_unique, true) do
changeset
|> unsafe_validate_unique(:username, Chesstrainer.Repo)
|> unique_constraint(:username)
else
changeset
end
end
defp validate_email_changed(changeset) do
if get_field(changeset, :email) && get_change(changeset, :email) == nil do
add_error(changeset, :email, "did not change")
else
changeset
end
end
@doc """
A user changeset for changing the password.
It is important to validate the length of the password, as long passwords may
be very expensive to hash for certain algorithms.
## Options
* `:hash_password` - Hashes the password so it can be stored securely
in the database and ensures the password field is cleared to prevent
leaks in the logs. If password hashing is not needed and clearing the
password field is not desired (like when using this changeset for
validations on a LiveView form), this option can be set to `false`.
Defaults to `true`.
"""
def password_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:password])
|> validate_confirmation(:password, message: "does not match password")
|> validate_password(opts)
end
defp validate_password(changeset, opts) do
changeset
|> validate_required([:password])
|> validate_length(:password, min: 12, max: 72)
# Examples of additional password validation:
# |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character")
# |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character")
# |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character")
|> maybe_hash_password(opts)
end
defp maybe_hash_password(changeset, opts) do
hash_password? = Keyword.get(opts, :hash_password, true)
password = get_change(changeset, :password)
if hash_password? && password && changeset.valid? do
changeset
# If using Bcrypt, then further validate it is at most 72 bytes long
|> validate_length(:password, max: 72, count: :bytes)
# Hashing could be done with `Ecto.Changeset.prepare_changes/2`, but that
# would keep the database transaction open longer and hurt performance.
|> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password))
|> delete_change(:password)
else
changeset
end
end
@doc """
Confirms the account by setting `confirmed_at`.
"""
def confirm_changeset(user) do
now = DateTime.utc_now(:second)
change(user, confirmed_at: now)
end
@doc """
Verifies the password.
If there is no user or the user doesn't have a password, we call
`Bcrypt.no_user_verify/0` to avoid timing attacks.
"""
def valid_password?(%Chesstrainer.Accounts.User{hashed_password: hashed_password}, password)
when is_binary(hashed_password) and byte_size(password) > 0 do
Bcrypt.verify_pass(password, hashed_password)
end
def valid_password?(_, _) do
Bcrypt.no_user_verify()
false
end
end