prop/lib/microwaveprop/accounts/user.ex
Graham McIntire 316fb2fbc7
Fix low-severity bugs and re-enable Credo checks
- Bug #12: Lower rate limit to 15/min
- Bug #13: Wrap model loading in Task.start
- Bug #14: Fix classify_time_period guard gap at -3.0
- Bug #15: Not applicable (Elixir has no ?? operator)
- Bug #16: Remove fallback Repo.get for station preload
- Bug #17: Extract cache_key() in ContactMapController
- Bug #18: Add has_many :contacts and :beacons to User schema
- A&D #4: Move serve_markdown_if_requested after secure headers
- Config #1: Move signing_salt to runtime.exs env var
- Config #2: Use --check-unused instead of --unused
- Config #3: Re-enable UnsafeToAtom Credo check
- Config #5: Re-enable LeakyEnvironment Credo check
- Add @spec annotations to fix re-enabled Specs violations
- Replace String.to_atom with to_existing_atom where guarded
2026-05-29 17:29:22 -05:00

371 lines
12 KiB
Elixir

defmodule Microwaveprop.Accounts.User do
@moduledoc false
use Ecto.Schema
import Ecto.Changeset
alias Microwaveprop.Radio.Maidenhead
@admin_email "graham@mcintire.me"
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "users" do
field :callsign, :string
field :name, :string
field :email, :string
field :password, :string, virtual: true, redact: true
field :hashed_password, :string, redact: true
field :confirmed_at, :utc_datetime
field :is_admin, :boolean, default: false
field :authenticated_at, :utc_datetime, virtual: true
field :home_grid, :string
field :home_lat, :float
field :home_lon, :float
field :home_elevation_m, :integer
has_many :contacts, Microwaveprop.Radio.Contact
has_many :beacons, Microwaveprop.Propagation.Beacon
timestamps(type: :utc_datetime)
end
@type t :: %__MODULE__{}
@doc """
Returns the email address that is automatically granted admin
privileges on registration.
"""
@spec admin_email() :: String.t()
def admin_email, do: @admin_email
@doc """
A user changeset for registering a new user.
Requires callsign, name, email, and password with confirmation.
Sets `confirmed_at` so the account is usable immediately after
password-based registration (there is no magic link confirmation flow).
## Options
* `:hash_password` - Hashes the password so it can be stored securely.
Defaults to `true`. Set to `false` for form validations in LiveView.
* `:validate_unique` - Set to false to skip uniqueness validation.
Defaults to `true`.
"""
@spec registration_changeset(t() | Ecto.Changeset.t(), map(), keyword()) :: Ecto.Changeset.t()
def registration_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:callsign, :name, :email, :password])
|> validate_callsign(opts)
|> validate_name()
|> validate_email(opts)
|> validate_confirmation(:password, message: "does not match password")
|> validate_password(opts)
|> maybe_grant_admin()
end
defp maybe_grant_admin(changeset) do
case get_field(changeset, :email) do
nil -> changeset
email -> if String.downcase(email) == @admin_email, do: put_change(changeset, :is_admin, true), else: changeset
end
end
@doc """
Admin-only changeset for editing another user's profile fields
and admin flag. Does not touch the password.
"""
@spec admin_changeset(t() | Ecto.Changeset.t(), map()) :: Ecto.Changeset.t()
def admin_changeset(user, attrs) do
user
|> cast(attrs, [:callsign, :name, :email, :is_admin])
|> update_change(:callsign, fn cs -> cs && cs |> String.trim() |> String.upcase() end)
|> validate_required([:callsign, :name, :email])
|> validate_format(:callsign, ~r/^[A-Z0-9]{3,10}$/, message: "must be 3-10 letters and digits")
|> validate_length(:name, min: 1, max: 100)
|> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/, message: "must have the @ sign and no spaces")
|> validate_length(:email, max: 160)
|> unsafe_validate_unique(:callsign, Microwaveprop.Repo)
|> unique_constraint(:callsign)
|> unsafe_validate_unique(:email, Microwaveprop.Repo)
|> unique_constraint(:email)
end
defp validate_callsign(changeset, opts) do
changeset =
changeset
|> update_change(:callsign, &String.upcase(&1 || ""))
|> validate_required([:callsign])
|> validate_format(:callsign, ~r/^[A-Z0-9]{3,10}$/, message: "must be 3-10 letters and digits")
if Keyword.get(opts, :validate_unique, true) do
changeset
|> unsafe_validate_unique(:callsign, Microwaveprop.Repo)
|> unique_constraint(:callsign)
else
changeset
end
end
defp validate_name(changeset) do
changeset
|> validate_required([:name])
|> validate_length(:name, min: 1, max: 100)
end
@doc """
A user changeset for 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`.
"""
@spec email_changeset(t() | Ecto.Changeset.t(), map(), keyword()) :: Ecto.Changeset.t()
def email_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:email])
|> validate_email(opts)
|> validate_email_changed()
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, Microwaveprop.Repo)
|> unique_constraint(:email)
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`.
"""
@spec password_changeset(t() | Ecto.Changeset.t(), map(), keyword()) :: Ecto.Changeset.t()
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: 8, 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`.
"""
@spec confirm_changeset(t() | Ecto.Changeset.t()) :: Ecto.Changeset.t()
def confirm_changeset(user) do
now = DateTime.utc_now(:second)
change(user, confirmed_at: now)
end
@doc """
Changeset for the rover-page "home QTH" fields.
Accepts either a Maidenhead grid or an explicit lat/lon. When only the
grid is given, lat/lon are derived from its centre; when only lat/lon
are given, a 10-character grid is computed from the coordinate pair so
callers always end up with both fields populated. An empty `home_grid`
paired with explicit nil lat/lon clears all home fields (used by the
"clear home" affordance on /rover).
"""
@spec change_home_qth(t() | Ecto.Changeset.t(), map()) :: Ecto.Changeset.t()
def change_home_qth(user, attrs) do
user
|> cast(attrs, [:home_grid, :home_lat, :home_lon, :home_elevation_m])
|> normalize_home_grid()
|> validate_home_grid_format()
|> derive_home_latlon_from_grid()
|> derive_home_grid_from_latlon()
|> validate_home_latlon_range()
|> require_home_qth_pair()
end
defp normalize_home_grid(changeset) do
case get_change(changeset, :home_grid) do
nil ->
changeset
"" ->
put_change(changeset, :home_grid, nil)
grid when is_binary(grid) ->
put_change(changeset, :home_grid, normalize_grid(grid))
end
end
defp normalize_grid(grid) do
trimmed = String.trim(grid)
case String.length(trimmed) do
4 -> String.upcase(trimmed)
6 -> String.upcase(String.slice(trimmed, 0, 4)) <> String.downcase(String.slice(trimmed, 4, 2))
_ -> trimmed
end
end
defp validate_home_grid_format(changeset) do
case get_field(changeset, :home_grid) do
nil ->
changeset
grid ->
if Maidenhead.valid?(grid),
do: changeset,
else: add_error(changeset, :home_grid, "must be a 4 or 6 character Maidenhead locator")
end
end
defp derive_home_latlon_from_grid(changeset) do
cond do
not changeset.valid? ->
changeset
get_change(changeset, :home_lat) || get_change(changeset, :home_lon) ->
changeset
grid = get_change(changeset, :home_grid) ->
case Maidenhead.to_latlon(grid) do
{:ok, {lat, lon}} ->
changeset
|> put_change(:home_lat, lat)
|> put_change(:home_lon, lon)
:error ->
changeset
end
true ->
changeset
end
end
# If lat/lon were provided without a grid, encode a 10-char Maidenhead
# grid from the coordinates so the UI always has a human-readable label
# to render and downstream callers can rely on `home_grid` being set
# whenever the QTH is set. Skipped on invalid changesets (lat/lon range
# check has not run yet) and when both fields aren't numeric.
defp derive_home_grid_from_latlon(changeset) do
lat = get_field(changeset, :home_lat)
lon = get_field(changeset, :home_lon)
cond do
not changeset.valid? ->
changeset
not (is_number(lat) and is_number(lon)) ->
changeset
get_field(changeset, :home_grid) not in [nil, ""] ->
changeset
true ->
put_change(changeset, :home_grid, Maidenhead.from_latlon(lat * 1.0, lon * 1.0, 10))
end
end
defp validate_home_latlon_range(changeset) do
changeset
|> validate_number(:home_lat, greater_than_or_equal_to: -90.0, less_than_or_equal_to: 90.0)
|> validate_number(:home_lon, greater_than_or_equal_to: -180.0, less_than_or_equal_to: 180.0)
end
defp require_home_qth_pair(changeset) do
if home_qth_satisfied?(changeset),
do: changeset,
else: add_error(changeset, :home_grid, "must provide a grid or lat/lon")
end
defp home_qth_satisfied?(changeset) do
grid = get_field(changeset, :home_grid)
lat = get_field(changeset, :home_lat)
lon = get_field(changeset, :home_lon)
cond do
is_binary(grid) and grid != "" -> true
is_number(lat) and is_number(lon) -> true
is_nil(grid) and is_nil(lat) and is_nil(lon) -> any_home_change?(changeset)
true -> false
end
end
defp any_home_change?(changeset) do
Enum.any?([:home_grid, :home_lat, :home_lon], &Map.has_key?(changeset.changes, &1))
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.
"""
@spec valid_password?(t() | nil, String.t()) :: boolean()
def valid_password?(%Microwaveprop.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