2017-12-08 08:58:14 +00:00
|
|
|
defmodule Eventos.Accounts.User do
|
|
|
|
use Ecto.Schema
|
|
|
|
import Ecto.Changeset
|
2018-01-09 16:52:26 +00:00
|
|
|
alias Eventos.Accounts.{Account, User}
|
|
|
|
alias Eventos.Repo
|
2017-12-08 08:58:14 +00:00
|
|
|
|
2018-01-09 16:52:26 +00:00
|
|
|
import Logger
|
2017-12-08 08:58:14 +00:00
|
|
|
|
|
|
|
schema "users" do
|
|
|
|
field :email, :string
|
|
|
|
field :role, :integer, default: 0
|
2017-12-09 13:58:37 +00:00
|
|
|
field :password, :string, virtual: true
|
|
|
|
field :password_hash, :string
|
2018-01-09 16:52:26 +00:00
|
|
|
belongs_to :account, Account
|
2017-12-08 08:58:14 +00:00
|
|
|
timestamps()
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
@doc false
|
|
|
|
def changeset(%User{} = user, attrs) do
|
|
|
|
user
|
2018-01-09 16:52:26 +00:00
|
|
|
|> cast(attrs, [:email, :password_hash])
|
2017-12-09 13:58:37 +00:00
|
|
|
|> validate_required([:email])
|
|
|
|
|> unique_constraint(:email)
|
2017-12-08 08:58:14 +00:00
|
|
|
|> validate_format(:email, ~r/@/)
|
2017-12-09 13:58:37 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def registration_changeset(struct, params) do
|
|
|
|
struct
|
|
|
|
|> changeset(params)
|
|
|
|
|> cast(params, ~w(password)a, [])
|
|
|
|
|> validate_length(:password, min: 6, max: 100)
|
|
|
|
|> hash_password
|
|
|
|
end
|
|
|
|
|
|
|
|
defp hash_password(changeset) do
|
|
|
|
case changeset do
|
|
|
|
%Ecto.Changeset{valid?: true,
|
|
|
|
changes: %{password: password}} ->
|
|
|
|
put_change(changeset,
|
|
|
|
:password_hash,
|
|
|
|
Comeonin.Argon2.hashpwsalt(password))
|
|
|
|
_ ->
|
|
|
|
changeset
|
|
|
|
end
|
2017-12-08 08:58:14 +00:00
|
|
|
end
|
|
|
|
end
|