6.9 KiB · text 5af55d9
defmodule GitGud.Accounts.User do
use Ecto.Schema
import Ecto.Changeset
@handle_format ~r/\A[a-z0-9][a-z0-9_\-]{0,59}\z/
schema "users" do
field :email, :string
field :password, :string, virtual: true, redact: true
field :hashed_password, :string, redact: true
field :confirmed_at, :utc_datetime
field :authenticated_at, :utc_datetime, virtual: true
field :is_admin, :boolean, default: false
field :editor_theme, :string
field :handle, :string
field :display_name, :string
field :bio, :string
field :url, :string
field :location, :string
field :company, :string
field :public_email, :string
field :timezone, :string
field :socials, :map, default: %{"items" => []}
# AES-256-GCM components. NULL = no TOTP secret stored yet.
field :totp_key_id, :string
field :totp_ciphertext, :binary
field :totp_iv, :binary
field :totp_tag, :binary
field :totp_enabled_at, :utc_datetime
timestamps(type: :utc_datetime)
end
@doc "Has the user finished TOTP enrollment?"
def totp_enabled?(%__MODULE__{totp_enabled_at: t}), do: not is_nil(t)
@doc "Promote or demote an admin."
def admin_changeset(user, value) when is_boolean(value),
do: Ecto.Changeset.change(user, is_admin: value)
@doc "Change the user's editor / syntax-highlight theme."
def editor_theme_changeset(user, theme) when is_binary(theme) or is_nil(theme),
do: Ecto.Changeset.change(user, editor_theme: theme)
@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)
|> maybe_seed_handle()
|> unique_constraint(:handle)
end
@doc """
Profile-only changeset — the display name, bio, url, location, company,
public email, timezone, and socials block. Doesn't touch email or
handle.
"""
def profile_changeset(user, attrs) do
user
|> cast(attrs, [
:display_name,
:bio,
:url,
:location,
:company,
:public_email,
:timezone,
:socials
])
|> validate_length(:display_name, max: 120)
|> validate_length(:bio, max: 1_000)
|> validate_length(:url, max: 200)
|> validate_length(:location, max: 120)
|> validate_length(:company, max: 120)
|> validate_length(:public_email, max: 160)
|> validate_length(:timezone, max: 60)
end
@doc "Display name with a fallback chain — display_name → handle → email."
def display(%__MODULE__{display_name: d}) when is_binary(d) and d != "", do: d
def display(%__MODULE__{handle: h}) when is_binary(h) and h != "", do: h
def display(%__MODULE__{email: e}) when is_binary(e), do: e |> String.split("@") |> hd()
def display(_), do: "(unknown)"
# When a user is being registered (no handle yet), seed one from the
# email local-part. Collisions are caught by the unique constraint;
# callers can retry with a suffix.
defp maybe_seed_handle(changeset) do
case get_field(changeset, :handle) do
nil ->
email = get_field(changeset, :email)
if is_binary(email) do
base = email |> String.split("@") |> hd() |> String.downcase()
if String.match?(base, @handle_format) do
put_change(changeset, :handle, base)
else
changeset
end
else
changeset
end
_existing ->
changeset
end
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, GitGud.Repo)
|> unique_constraint(:email)
|> validate_email_changed()
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?(%GitGud.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