WebAuthN auth

This commit is contained in:
bluepython508
2023-11-05 01:12:02 +00:00
parent 45e4e9f5da
commit 092930a24f
33 changed files with 1123 additions and 463 deletions

View File

@@ -0,0 +1,60 @@
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