Add functions to add admins

This commit is contained in:
João Gilberto Balsini Moura 2020-09-12 21:37:05 -03:00
parent 33029dae04
commit bda3f949b8
3 changed files with 46 additions and 1 deletions

View file

@ -79,6 +79,24 @@ defmodule RealEstate.Accounts do
|> Repo.insert() |> Repo.insert()
end end
@doc """
Registers an admin.
## Examples
iex> register_admin(%{field: value})
{:ok, %User{}}
iex> register_admin(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def register_admin(attrs) do
%User{}
|> User.admin_registration_changeset(attrs)
|> Repo.insert()
end
@doc """ @doc """
Returns an `%Ecto.Changeset{}` for tracking user changes. Returns an `%Ecto.Changeset{}` for tracking user changes.

View file

@ -34,6 +34,15 @@ defmodule RealEstate.Accounts.User do
|> validate_password() |> validate_password()
end end
@doc """
A user changeset for registering admins.
"""
def admin_registration_changeset(user, attrs) do
user
|> registration_changeset(attrs)
|> prepare_changes(&set_admin_role/1)
end
defp validate_email(changeset) do defp validate_email(changeset) do
changeset changeset
|> validate_required([:email]) |> validate_required([:email])
@ -61,6 +70,11 @@ defmodule RealEstate.Accounts.User do
|> delete_change(:password) |> delete_change(:password)
end end
defp set_admin_role(changeset) do
changeset
|> put_change(:role, :admin)
end
@doc """ @doc """
A user changeset for changing the email. A user changeset for changing the email.

View file

@ -83,13 +83,26 @@ defmodule RealEstate.AccountsTest do
assert "has already been taken" in errors_on(changeset).email assert "has already been taken" in errors_on(changeset).email
end end
test "registers users with a hashed password" do test "registers users with a hashed password and sets role to :user" do
email = unique_user_email() email = unique_user_email()
{:ok, user} = Accounts.register_user(%{email: email, password: valid_user_password()}) {:ok, user} = Accounts.register_user(%{email: email, password: valid_user_password()})
assert user.email == email assert user.email == email
assert is_binary(user.hashed_password) assert is_binary(user.hashed_password)
assert is_nil(user.confirmed_at) assert is_nil(user.confirmed_at)
assert is_nil(user.password) assert is_nil(user.password)
assert user.role == :user
end
end
describe "register_admin/1" do
test "registers users with a hashed password and sets role to :admin" do
email = unique_user_email()
{:ok, user} = Accounts.register_admin(%{email: email, password: valid_user_password()})
assert user.email == email
assert is_binary(user.hashed_password)
assert is_nil(user.confirmed_at)
assert is_nil(user.password)
assert user.role == :admin
end end
end end