From 6aa5301d8948d0bd4c7fae2ff9400dcdb6b78d80 Mon Sep 17 00:00:00 2001 From: Max Leiter Date: Sun, 25 Dec 2022 20:52:32 -0800 Subject: [PATCH] lib/server: move making 1st user admin to next auth event --- src/lib/server/auth.ts | 28 ++++++++++++++++++++++++++++ src/lib/server/prisma.ts | 17 ----------------- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/src/lib/server/auth.ts b/src/lib/server/auth.ts index 77c1ae8a..8caba58e 100644 --- a/src/lib/server/auth.ts +++ b/src/lib/server/auth.ts @@ -139,6 +139,34 @@ export const authOptions: NextAuthOptions = { error: "/signin" }, providers: providers(), + events: { + createUser: async ({ user }) => { + const totalUsers = await prisma.user.count() + console.log('totalUsers', totalUsers) + if (config.enable_admin && totalUsers === 1) { + await prisma.user.update({ + where: { + id: user.id, + }, + data: { + role: "admin" + } + }) + } + + if (!user.username) { + await prisma.user.update({ + where: { + id: user.id + }, + data: { + username: user.name, + displayName: user.name, + } + }) + } + } + }, callbacks: { async session({ token, session }) { if (token) { diff --git a/src/lib/server/prisma.ts b/src/lib/server/prisma.ts index b7ff2c9b..6f896056 100644 --- a/src/lib/server/prisma.ts +++ b/src/lib/server/prisma.ts @@ -13,23 +13,6 @@ export const prisma = log: ["query"] }) -if (config.enable_admin) { - // a prisma middleware for capturing the first user and making them an admin - prisma.$use(async (params, next) => { - const result = await next(params) - if (params.model === "User" && params.action === "create") { - const users = await prisma.user.findMany() - if (users.length === 1) { - await prisma.user.update({ - where: { id: users[0].id }, - data: { role: "admin" } - }) - } - } - return result - }) -} - // prisma.$use(async (params, next) => { // const result = await next(params) // return updateDates(result)