clacks/lib/clacks/user.ex

44 lines
1.1 KiB
Elixir
Raw Normal View History

2019-09-29 22:30:59 +00:00
defmodule Clacks.User do
use Ecto.Schema
import Ecto.Changeset
@type t() :: %__MODULE__{}
schema "users" do
field :username, :string
field :private_key, :string
2019-10-02 21:04:56 +00:00
field :password, :string, virtual: true
field :password_hash, :string
2019-09-29 22:30:59 +00:00
has_one :actor, Clacks.Actor
timestamps()
end
def changeset(%__MODULE__{} = schema, attrs) do
schema
2019-10-02 21:04:56 +00:00
|> cast(attrs, [:username, :private_key, :password_hash])
|> validate_required([:username, :private_key, :password_hash])
end
def registration_changeset(%__MODULE__{} = schema, attrs) do
schema
|> cast(attrs, [:username, :private_key, :password])
|> validate_length(:password, min: 8)
|> put_password_hash()
end
def change_password_changeset(%__MODULE__{} = schema, attrs) do
schema
|> cast(attrs, [:password])
|> validate_length(:password, min: 8)
|> put_password_hash()
end
defp put_password_hash(
%Ecto.Changeset{valid?: true, changes: %{password: password}} = changeset
) do
change(changeset, Bcrypt.add_hash(password))
2019-09-29 22:30:59 +00:00
end
end