2023-02-16 21:01:40 +00:00
|
|
|
import type { NextMiddleware } from "next-api-middleware";
|
2022-06-08 16:52:25 +00:00
|
|
|
|
2022-06-22 03:49:24 +00:00
|
|
|
import { CONSOLE_URL } from "@calcom/lib/constants";
|
2023-09-19 21:02:57 +00:00
|
|
|
import { customPrisma } from "@calcom/prisma";
|
2022-06-08 16:52:25 +00:00
|
|
|
|
2022-12-05 21:16:58 +00:00
|
|
|
const LOCAL_CONSOLE_URL = process.env.NEXT_PUBLIC_CONSOLE_URL || CONSOLE_URL;
|
2022-12-02 22:22:56 +00:00
|
|
|
|
2022-12-05 21:16:58 +00:00
|
|
|
// This replaces the prisma client for the custom one if the key is valid
|
2022-06-08 16:52:25 +00:00
|
|
|
export const customPrismaClient: NextMiddleware = async (req, res, next) => {
|
|
|
|
const {
|
2022-06-17 21:23:28 +00:00
|
|
|
query: { key },
|
2023-05-19 17:38:19 +00:00
|
|
|
} = req;
|
2022-06-08 16:52:25 +00:00
|
|
|
// If no custom api Id is provided, attach to request the regular cal.com prisma client.
|
2022-06-17 21:23:28 +00:00
|
|
|
if (!key) {
|
2023-09-19 21:02:57 +00:00
|
|
|
req.prisma = customPrisma();
|
2022-06-08 16:52:25 +00:00
|
|
|
await next();
|
2022-06-23 22:26:40 +00:00
|
|
|
return;
|
2022-06-23 22:42:22 +00:00
|
|
|
}
|
2022-12-03 01:39:30 +00:00
|
|
|
|
2022-06-23 22:42:22 +00:00
|
|
|
// If we have a key, we check if the deployment matching the key, has a databaseUrl value set.
|
2022-12-05 21:16:58 +00:00
|
|
|
const databaseUrl = await fetch(`${LOCAL_CONSOLE_URL}/api/deployments/database?key=${key}`)
|
2022-06-23 22:42:22 +00:00
|
|
|
.then((res) => res.json())
|
|
|
|
.then((res) => res.databaseUrl);
|
2022-06-21 21:02:43 +00:00
|
|
|
|
2022-06-23 22:42:22 +00:00
|
|
|
if (!databaseUrl) {
|
|
|
|
res.status(400).json({ error: "no databaseUrl set up at your instance yet" });
|
|
|
|
return;
|
|
|
|
}
|
2023-09-19 21:02:57 +00:00
|
|
|
req.prisma = customPrisma({ datasources: { db: { url: databaseUrl } } });
|
2022-06-23 22:42:22 +00:00
|
|
|
/* @note:
|
2022-06-23 17:16:12 +00:00
|
|
|
In order to skip verifyApiKey for customPrisma requests,
|
|
|
|
we pass isAdmin true, and userId 0, if we detect them later,
|
|
|
|
we skip verifyApiKey logic and pass onto next middleware instead.
|
|
|
|
*/
|
2022-06-23 22:42:22 +00:00
|
|
|
req.isAdmin = true;
|
2022-09-07 16:18:43 +00:00
|
|
|
req.isCustomPrisma = true;
|
2023-01-25 21:14:43 +00:00
|
|
|
// We don't need the key from here and on. Prevents unrecognized key errors.
|
|
|
|
delete req.query.key;
|
2022-06-08 16:52:25 +00:00
|
|
|
await next();
|
2023-02-09 02:29:58 +00:00
|
|
|
await req.prisma.$disconnect();
|
2023-02-09 02:56:41 +00:00
|
|
|
// @ts-expect-error testing
|
|
|
|
delete req.prisma;
|
2022-06-08 16:52:25 +00:00
|
|
|
};
|