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

61 lines
1.2 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)
2024-01-04 16:57:32 -05:00
return null
const key = await db.apiKey.findFirst({
where: {
id: token as string
}
})
if (!key)
return null
2024-01-04 16:57:32 -05:00
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.
2024-01-04 16:57:32 -05:00
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
2024-01-04 16:57:32 -05:00
}
}
}
return user
2024-01-04 16:57:32 -05:00
}