Skip to content

Instantly share code, notes, and snippets.

@blacksails
Created September 22, 2015 12:23
Show Gist options
  • Save blacksails/b8e21e11a5c327d536cc to your computer and use it in GitHub Desktop.
Save blacksails/b8e21e11a5c327d536cc to your computer and use it in GitHub Desktop.
defmodule Avalonia.User do
use Avalonia.Web, :model
import Comeonin.Password, only: [strong_password?: 2]
import Comeonin.Bcrypt, only: [hashpwsalt: 1]
schema "users" do
field :email, :string
field :password, :string, virtual: true
field :password_digest, :string
timestamps
end
@required_fields ~w(email)
@optional_fields ~w(password)
@doc """
Creates a changeset based on the `model` and `params`.
If no params are provided, an invalid changeset is returned
with no validation performed.
"""
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> unique_constraint(:email)
|> validate_change(:password, password_validator)
|> set_password_digest
end
@doc """
Reads the password from the `changeset` and genereates a hash from it.
The hash is saved as the password_digest in the User model.
Returns the updated changeset
"""
def set_password_digest(changeset) do
case fetch_change(changeset, :password) do
:error -> changeset
{:ok, password} ->
change(changeset, %{password_digest: hashpwsalt(password)})
end
end
defp password_validator() do
fn _, password ->
case strong_password? password, min_length: 12 do
true -> []
error -> [password: error]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment