defmodule Localiser.Domain.Schema.User do use Ecto.Schema import Ecto.Changeset schema "users" do field :username, :string field :password_hash, :string, redact: true field :password, :string, virtual: true, redact: true timestamps(type: :utc_datetime) end @doc false def changeset(user, attrs) do user |> cast(attrs, [:username, :password]) |> validate_required([:username, :password]) |> validate_length(:password, min: 8) |> unique_constraint(:username) |> hash_password() end defp hash_password(%Ecto.Changeset{valid?: true, changes: %{password: pw}} = changeset) do put_change(changeset, :password_hash, Argon2.hash_pwd_salt(pw)) end defp hash_password(changeset), do: changeset end