61 lines
1.3 KiB
Elixir
61 lines
1.3 KiB
Elixir
defmodule SsoBsn.Accounts.User do
|
|
use Ecto.Schema
|
|
import Ecto.Changeset
|
|
|
|
alias SsoBsn.Accounts.UserKey
|
|
|
|
schema "users" do
|
|
field :username, :string
|
|
field :confirmed_at, :naive_datetime
|
|
|
|
has_many :keys, UserKey
|
|
|
|
timestamps(type: :utc_datetime)
|
|
end
|
|
|
|
@doc """
|
|
A user changeset for registration.
|
|
"""
|
|
def registration_changeset(user, attrs, _opts \\ []) do
|
|
user
|
|
|> cast(attrs, [:username])
|
|
|> validate_username()
|
|
end
|
|
|
|
def validate_username(changeset) do
|
|
changeset
|
|
|> validate_format(:username, ~r/^[a-zA-Z_0-9.-]+$/)
|
|
|> validate_length(:username, min: 3, max: 128)
|
|
|> unique_constraint(:username)
|
|
end
|
|
|
|
@doc """
|
|
A user changeset for changing the username.
|
|
|
|
It requires the username to change otherwise an error is added.
|
|
"""
|
|
def username_changeset(user, attrs, _opts \\ []) do
|
|
user
|
|
|> cast(attrs, [:username])
|
|
|> validate_username()
|
|
|> case do
|
|
%{changes: %{username: _}} = changeset -> changeset
|
|
%{} = changeset -> add_error(changeset, :username, "did not change")
|
|
end
|
|
end
|
|
|
|
@doc """
|
|
Confirms the account by setting `confirmed_at`.
|
|
"""
|
|
def confirm_changeset(user) do
|
|
now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
|
|
change(user, confirmed_at: now)
|
|
end
|
|
|
|
|
|
def add_key_changeset(user) do
|
|
user
|
|
|> Ecto.build_assoc(:keys)
|
|
end
|
|
end
|