From bda3f949b8f3e081d395a6938a4db2922331b0c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Gilberto=20Balsini=20Moura?= Date: Sat, 12 Sep 2020 21:37:05 -0300 Subject: [PATCH] Add functions to add admins --- lib/real_estate/accounts.ex | 18 ++++++++++++++++++ lib/real_estate/accounts/user.ex | 14 ++++++++++++++ test/real_estate/accounts_test.exs | 15 ++++++++++++++- 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/lib/real_estate/accounts.ex b/lib/real_estate/accounts.ex index 6c5e3f8b..b7d3a592 100644 --- a/lib/real_estate/accounts.ex +++ b/lib/real_estate/accounts.ex @@ -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. diff --git a/lib/real_estate/accounts/user.ex b/lib/real_estate/accounts/user.ex index d53a15a1..2a4e2868 100644 --- a/lib/real_estate/accounts/user.ex +++ b/lib/real_estate/accounts/user.ex @@ -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. diff --git a/test/real_estate/accounts_test.exs b/test/real_estate/accounts_test.exs index 6f683a75..3c37fbcd 100644 --- a/test/real_estate/accounts_test.exs +++ b/test/real_estate/accounts_test.exs @@ -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