this is a really good first commit
This commit is contained in:
@ -8,20 +8,9 @@ defmodule SomethingErlang.Accounts.User do
|
||||
field :hashed_password, :string, redact: true
|
||||
field :confirmed_at, :naive_datetime
|
||||
|
||||
field :bbuserid, :string
|
||||
field :bbpassword, :string
|
||||
|
||||
timestamps()
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for SA data.
|
||||
"""
|
||||
def sadata_changeset(user, attrs, _opts \\ []) do
|
||||
user
|
||||
|> cast(attrs, [:bbuserid, :bbpassword])
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for registration.
|
||||
|
||||
@ -38,21 +27,26 @@ defmodule SomethingErlang.Accounts.User do
|
||||
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`.
|
||||
|
||||
* `:validate_email` - Validates the uniqueness of the email, in case
|
||||
you don't want to validate the uniqueness of the email (like when
|
||||
using this changeset for validations on a LiveView form before
|
||||
submitting the form), this option can be set to `false`.
|
||||
Defaults to `true`.
|
||||
"""
|
||||
def registration_changeset(user, attrs, opts \\ []) do
|
||||
user
|
||||
|> cast(attrs, [:email, :password])
|
||||
|> validate_email()
|
||||
|> validate_email(opts)
|
||||
|> validate_password(opts)
|
||||
end
|
||||
|
||||
defp validate_email(changeset) do
|
||||
defp validate_email(changeset, opts) do
|
||||
changeset
|
||||
|> validate_required([:email])
|
||||
|> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces")
|
||||
|> validate_length(:email, max: 160)
|
||||
|> unsafe_validate_unique(:email, SomethingErlang.Repo)
|
||||
|> unique_constraint(:email)
|
||||
|> maybe_validate_unique_email(opts)
|
||||
end
|
||||
|
||||
defp validate_password(changeset, opts) do
|
||||
@ -80,15 +74,25 @@ defmodule SomethingErlang.Accounts.User do
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_validate_unique_email(changeset, opts) do
|
||||
if Keyword.get(opts, :validate_email, true) do
|
||||
changeset
|
||||
|> unsafe_validate_unique(:email, SomethingErlang.Repo)
|
||||
|> unique_constraint(:email)
|
||||
else
|
||||
changeset
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for changing the email.
|
||||
|
||||
It requires the email to change otherwise an error is added.
|
||||
"""
|
||||
def email_changeset(user, attrs) do
|
||||
def email_changeset(user, attrs, opts \\ []) do
|
||||
user
|
||||
|> cast(attrs, [:email])
|
||||
|> validate_email()
|
||||
|> validate_email(opts)
|
||||
|> case do
|
||||
%{changes: %{email: _}} = changeset -> changeset
|
||||
%{} = changeset -> add_error(changeset, :email, "did not change")
|
||||
|
Reference in New Issue
Block a user