clacks/lib/clacks/user.ex

49 lines
1.2 KiB
Elixir

defmodule Clacks.User do
use Ecto.Schema
import Ecto.Changeset
alias Clacks.Repo
@type t() :: %__MODULE__{}
schema "users" do
field :username, :string
field :private_key, :string
field :password, :string, virtual: true
field :password_hash, :string
has_one :actor, Clacks.Actor
timestamps()
end
def changeset(%__MODULE__{} = schema, attrs) do
schema
|> 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))
end
def get_by_username(username) do
Repo.get_by(__MODULE__, username: username)
end
end