Add functions to add admins
This commit is contained in:
parent
33029dae04
commit
bda3f949b8
3 changed files with 46 additions and 1 deletions
|
@ -79,6 +79,24 @@ defmodule RealEstate.Accounts do
|
|||
|> Repo.insert()
|
||||
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 """
|
||||
Returns an `%Ecto.Changeset{}` for tracking user changes.
|
||||
|
||||
|
|
|
@ -34,6 +34,15 @@ defmodule RealEstate.Accounts.User do
|
|||
|> validate_password()
|
||||
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
|
||||
changeset
|
||||
|> validate_required([:email])
|
||||
|
@ -61,6 +70,11 @@ defmodule RealEstate.Accounts.User do
|
|||
|> delete_change(:password)
|
||||
end
|
||||
|
||||
defp set_admin_role(changeset) do
|
||||
changeset
|
||||
|> put_change(:role, :admin)
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for changing the email.
|
||||
|
||||
|
|
|
@ -83,13 +83,26 @@ defmodule RealEstate.AccountsTest do
|
|||
assert "has already been taken" in errors_on(changeset).email
|
||||
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()
|
||||
{:ok, user} = Accounts.register_user(%{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 == :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
|
||||
|
||||
|
|
Loading…
Reference in a new issue