calcom/apps/web/ee/lib/impersonation/ImpersonationProvider.ts
sean-brydon 1421b9c0af Feat/impersonate users (#2503)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: zomars <zomars@me.com>
2022-05-02 16:21:11 -06:00

62 lines
1.5 KiB
TypeScript

import CredentialsProvider from "next-auth/providers/credentials";
import { getSession } from "next-auth/react";
import prisma from "@lib/prisma";
const ImpersonationProvider = CredentialsProvider({
id: "impersonation-auth",
name: "Impersonation",
type: "credentials",
credentials: {
username: { label: "Username", type: "text " },
},
async authorize(creds, req) {
// @ts-ignore need to figure out how to correctly type this
const session = await getSession({ req });
if (session?.user.role !== "ADMIN") {
throw new Error("You do not have permission to do this.");
}
if (session?.user.username === creds?.username) {
throw new Error("You cannot impersonate yourself.");
}
const user = await prisma.user.findUnique({
where: {
username: creds?.username,
},
});
if (!user) {
throw new Error("This user does not exist");
}
// Log impersonations for audit purposes
await prisma.impersonations.create({
data: {
impersonatedBy: {
connect: {
id: session.user.id,
},
},
impersonatedUser: {
connect: {
id: user.id,
},
},
},
});
const obj = {
id: user.id,
username: user.username,
email: user.email,
name: user.name,
role: user.role,
impersonatedByUID: session?.user.id,
};
return obj;
},
});
export default ImpersonationProvider;