2018-05-18 09:56:21 +02:00
|
|
|
defmodule Eventos.Actors.User do
|
2018-01-14 17:56:50 +01:00
|
|
|
@moduledoc """
|
|
|
|
Represents a local user
|
|
|
|
"""
|
2017-12-08 09:58:14 +01:00
|
|
|
use Ecto.Schema
|
|
|
|
import Ecto.Changeset
|
2018-05-18 09:56:21 +02:00
|
|
|
alias Eventos.Actors.{Actor, User}
|
2017-12-08 09:58:14 +01:00
|
|
|
|
|
|
|
schema "users" do
|
|
|
|
field :email, :string
|
2017-12-09 14:58:37 +01:00
|
|
|
field :password_hash, :string
|
2018-01-13 23:33:03 +01:00
|
|
|
field :password, :string, virtual: true
|
|
|
|
field :role, :integer, default: 0
|
2018-05-18 09:56:21 +02:00
|
|
|
belongs_to :actor, Actor
|
2018-01-13 23:33:03 +01:00
|
|
|
|
2017-12-08 09:58:14 +01:00
|
|
|
timestamps()
|
|
|
|
end
|
|
|
|
|
|
|
|
@doc false
|
|
|
|
def changeset(%User{} = user, attrs) do
|
|
|
|
user
|
2018-05-18 09:56:21 +02:00
|
|
|
|> cast(attrs, [:email, :role, :password_hash, :actor_id])
|
2017-12-09 14:58:37 +01:00
|
|
|
|> validate_required([:email])
|
|
|
|
|> unique_constraint(:email)
|
2017-12-08 09:58:14 +01:00
|
|
|
|> validate_format(:email, ~r/@/)
|
2017-12-09 14:58:37 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def registration_changeset(struct, params) do
|
|
|
|
struct
|
|
|
|
|> changeset(params)
|
|
|
|
|> cast(params, ~w(password)a, [])
|
|
|
|
|> validate_length(:password, min: 6, max: 100)
|
2018-01-26 11:02:11 +01:00
|
|
|
|> hash_password()
|
2017-12-09 14:58:37 +01:00
|
|
|
end
|
|
|
|
|
2018-01-26 11:02:11 +01:00
|
|
|
@doc """
|
|
|
|
Hash password when it's changed
|
|
|
|
"""
|
2017-12-09 14:58:37 +01:00
|
|
|
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 09:58:14 +01:00
|
|
|
end
|
|
|
|
end
|