61 lines
1.2 KiB
TypeScript
61 lines
1.2 KiB
TypeScript
import { auth } from "@/auth";
|
|
import { db } from "./db";
|
|
|
|
export default async function fetchUserWithImpersonation(req: Request) {
|
|
const session = await auth()
|
|
|
|
if (session) {
|
|
const user = fetch(session.user.id)
|
|
if (user) {
|
|
return user
|
|
}
|
|
}
|
|
|
|
const token = req.headers?.get('x-api-key')
|
|
if (!token)
|
|
return null
|
|
|
|
const key = await db.apiKey.findFirst({
|
|
where: {
|
|
id: token as string
|
|
}
|
|
})
|
|
|
|
if (!key)
|
|
return null
|
|
|
|
return fetch(key.userId)
|
|
}
|
|
|
|
const fetch = async (userId: string) => {
|
|
const user = await db.user.findFirst({
|
|
where: {
|
|
id: userId
|
|
}
|
|
})
|
|
|
|
if (!user) return null
|
|
|
|
// Only admins can impersonate others.
|
|
if (user.role == "ADMIN") {
|
|
const impersonation = await db.impersonation.findFirst({
|
|
where: {
|
|
sourceId: userId
|
|
}
|
|
})
|
|
|
|
if (impersonation) {
|
|
const copied = await db.user.findFirst({
|
|
where: {
|
|
id: impersonation.targetId
|
|
}
|
|
})
|
|
|
|
if (copied) {
|
|
return copied
|
|
}
|
|
}
|
|
}
|
|
|
|
return user
|
|
} |