lib/server: move making 1st user admin to next auth event

This commit is contained in:
Max Leiter 2022-12-25 20:52:32 -08:00
parent 604f5d64d0
commit 6aa5301d89
2 changed files with 28 additions and 17 deletions

View file

@ -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) {

View file

@ -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)