From 18d69034ffab6c06111bd73c7c5004e3ecf9a0fa Mon Sep 17 00:00:00 2001 From: shibao Date: Fri, 10 Sep 2021 00:19:28 -0400 Subject: [PATCH] add autoadmin on first registered user --- lib/cannery/accounts.ex | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/lib/cannery/accounts.ex b/lib/cannery/accounts.ex index b185874..941bb9f 100644 --- a/lib/cannery/accounts.ex +++ b/lib/cannery/accounts.ex @@ -4,7 +4,7 @@ defmodule Cannery.Accounts do """ import Ecto.Query, warn: false - alias Cannery.Repo + alias Cannery.{Repo} alias Cannery.Accounts.{User, UserToken, UserNotifier} ## Database getters @@ -74,9 +74,13 @@ defmodule Cannery.Accounts do """ def register_user(attrs) do - %User{} - |> User.registration_changeset(attrs) - |> Repo.insert() + # if no registered users, make first user an admin + attrs = + if Repo.one!(from u in User, select: count(u.id), distinct: true) == 0, + do: attrs |> Map.put("role", "admin"), + else: attrs + + %User{} |> User.registration_changeset(attrs) |> Repo.insert() end @doc """ @@ -107,6 +111,20 @@ defmodule Cannery.Accounts do User.email_changeset(user, attrs) end + @doc """ + Returns an `%Ecto.Changeset{}` for changing the user role. + + ## Examples + + iex> change_user_role(user) + %Ecto.Changeset{data: %User{}} + + """ + @spec change_user_role(User.t(), atom()) :: Ecto.Changeset.t() + def change_user_role(user, role) do + User.role_changeset(user, role) + end + @doc """ Emulates that the email will change without actually changing it in the database.