Created
February 16, 2021 23:59
-
-
Save carlyleec/7e5779b96f6f5fbad481dc5c80ef6b21 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
@derive {Inspect, except: [:password]} | |
schema "users" do | |
field :email, :string | |
field :password, :string, virtual: true | |
field :hashed_password, :string | |
field :confirmed_at, :naive_datetime | |
timestamps() | |
end | |
... | |
def registration_changeset(user, attrs, opts \\ []) do | |
user | |
|> cast(attrs, [:email, :password]) | |
|> validate_email() | |
|> validate_password(opts) | |
end | |
defp validate_email(changeset) 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, Cam.Repo) | |
|> unique_constraint(:email) | |
end | |
defp validate_password(changeset, opts) do | |
changeset | |
|> validate_required([:password]) | |
|> validate_length(:password, min: 12, max: 80) | |
# |> 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 | |
|> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password)) | |
|> delete_change(:password) | |
else | |
changeset | |
end | |
end | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment