| 1 |
|
defmodule DaProductApp.Accounts.User do |
| 2 |
|
use Ecto.Schema |
| 3 |
|
import Ecto.Changeset |
| 4 |
|
|
| 5 |
|
alias DaProductApp.Accounts.{Organization, Role} |
| 6 |
|
|
| 7 |
:-( |
schema "users" do |
| 8 |
|
field :email, :string |
| 9 |
|
field :name, :string |
| 10 |
|
field :password, :string, virtual: true |
| 11 |
|
field :password_hash, :string |
| 12 |
|
field :is_active, :boolean, default: true |
| 13 |
|
|
| 14 |
|
belongs_to :organization, Organization |
| 15 |
|
belongs_to :role, Role |
| 16 |
|
|
| 17 |
|
timestamps() |
| 18 |
|
end |
| 19 |
|
|
| 20 |
|
@doc false |
| 21 |
|
def changeset(user, attrs) do |
| 22 |
|
user |
| 23 |
|
|> cast(attrs, [:email, :name, :password, :organization_id, :role_id, :is_active]) |
| 24 |
|
|> validate_required([:email, :name]) |
| 25 |
|
|> validate_format(:email, ~r/^[^\s]+@[^\s]+\.[^\s]+$/) |
| 26 |
|
|> unique_constraint(:email) |
| 27 |
:-( |
|> put_password_hash() |
| 28 |
|
end |
| 29 |
|
|
| 30 |
|
defp put_password_hash(changeset) do |
| 31 |
:-( |
case get_change(changeset, :password) do |
| 32 |
:-( |
nil -> changeset |
| 33 |
|
pw -> |
| 34 |
:-( |
hash = Bcrypt.hash_pwd_salt(pw) |
| 35 |
:-( |
put_change(changeset, :password_hash, hash) |
| 36 |
|
end |
| 37 |
|
end |
| 38 |
|
end |