add autoadmin on first registered user

This commit is contained in:
shibao 2021-09-10 00:19:28 -04:00 committed by oliviasculley
parent b1c4d824bc
commit 18d69034ff

View File

@ -4,7 +4,7 @@ defmodule Cannery.Accounts do
""" """
import Ecto.Query, warn: false import Ecto.Query, warn: false
alias Cannery.Repo alias Cannery.{Repo}
alias Cannery.Accounts.{User, UserToken, UserNotifier} alias Cannery.Accounts.{User, UserToken, UserNotifier}
## Database getters ## Database getters
@ -74,9 +74,13 @@ defmodule Cannery.Accounts do
""" """
def register_user(attrs) do def register_user(attrs) do
%User{} # if no registered users, make first user an admin
|> User.registration_changeset(attrs) attrs =
|> Repo.insert() 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 end
@doc """ @doc """
@ -107,6 +111,20 @@ defmodule Cannery.Accounts do
User.email_changeset(user, attrs) User.email_changeset(user, attrs)
end 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 """ @doc """
Emulates that the email will change without actually changing Emulates that the email will change without actually changing
it in the database. it in the database.