only run prisma admin middleware if enable_admin

This commit is contained in:
Max Leiter 2022-11-14 18:49:58 -08:00
parent aef1788747
commit 2c3e271df1

View file

@ -35,27 +35,28 @@ const updateDates = (input: any) => {
} }
} }
export const prisma = export const prisma =
global.prisma || global.prisma ||
new PrismaClient({ new PrismaClient({
log: ["query"] log: ["query"]
}) })
// a prisma middleware for capturing the first user and making them an admin if (config.enable_admin) {
prisma.$use(async (params, next) => { // a prisma middleware for capturing the first user and making them an admin
const result = await next(params) prisma.$use(async (params, next) => {
if (params.model === "User" && params.action === "create") { const result = await next(params)
const users = await prisma.user.findMany() if (params.model === "User" && params.action === "create") {
if (users.length === 1) { const users = await prisma.user.findMany()
await prisma.user.update({ if (users.length === 1) {
where: { id: users[0].id }, await prisma.user.update({
data: { role: "admin" } where: { id: users[0].id },
}) data: { role: "admin" }
})
}
} }
} return result
return result })
}) }
// prisma.$use(async (params, next) => { // prisma.$use(async (params, next) => {
// const result = await next(params) // const result = await next(params)
@ -123,7 +124,7 @@ export const getUserById = async (userId: User["id"]) => {
email: true, email: true,
// displayName: true, // displayName: true,
role: true, role: true,
displayName: true, displayName: true
} }
}) })
@ -160,10 +161,6 @@ export const createUser = async (
throw new Error("Wrong registration password") throw new Error("Wrong registration password")
} }
const isUserAdminByDefault =
config.enable_admin && (await prisma.user.count()) === 0
const userRole = isUserAdminByDefault ? "admin" : "user"
return { return {
// user, // user,
// token // token
@ -189,7 +186,7 @@ export const getPostById = async (
? { ? {
select: { select: {
id: true, id: true,
displayName: true, displayName: true
} }
} }
: false : false
@ -230,8 +227,8 @@ export const getAllUsers = async () => {
role: true, role: true,
displayName: true, displayName: true,
posts: true, posts: true,
createdAt: true, createdAt: true
}, }
}) })
return users as UserWithPosts[] return users as UserWithPosts[]