hermes-web/lib/fetch-user-impersonation.ts

67 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-01-04 16:57:32 -05:00
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 === null || token === undefined)
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
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 {
id: copied.id,
username: copied.name,
role: copied.role
}
}
}
}
return {
id: user.id,
username: user.name,
role: user.role
}
}