feat: dynamic prisma almost working

This commit is contained in:
Agusti Fernandez Pardo committed 2022-06-08 18:52:25 +02:00
1 parent e407a16766
commit 180e925bed
12 files changed
+226 -39

No files matched your search

-20
View File
@@ -1,20 +0,0 @@
import { NextMiddleware } from "next-api-middleware";
import prisma from "@calcom/prisma";
// This replaces the prisma client for the cusotm one if the customApiId is valid
export const customApiEndpoints: NextMiddleware = async (req, res, next) => {
const {
query: { customApiId },
} = req;
// If no custom api Id is provided, return the regular cal.com prisma client.
if (!customApiId) {
req.prisma = prisma();
await next();
}
// Hardcoded new database, this should be a dynamic call to console prisma/api?
const newDatabseUrl = process.env.DATABASE_PROD_URL;
req.prisma = prisma(newDatabseUrl);
await next();
};
+45
View File
@@ -0,0 +1,45 @@
import { hash } from "bcryptjs";
import cache from "memory-cache";
import { NextMiddleware } from "next-api-middleware";
import { prismaAdmin } from "@calcom/console/modules/common/utils/prisma";
import { asStringOrUndefined, asStringOrNull } from "@calcom/lib/asStringOrNull";
import { PRISMA_CLIENT_CACHING_TIME } from "@calcom/lib/constants";
import { prisma, customPrisma } from "@calcom/prisma";
// This replaces the prisma client for the cusotm one if the customCredentialsId is valid
export const customPrismaClient: NextMiddleware = async (req, res, next) => {
const {
query: { customCredentialsId },
} = req;
// If no custom api Id is provided, attach to request the regular cal.com prisma client.
if (!customCredentialsId) {
req.prisma = prisma;
await next();
} else {
const id = asStringOrUndefined(customCredentialsId);
// If we have a customCredentialsId, we check if it is valid.
const dataCredentials = await prismaAdmin.dataCredentials.findUnique({
where: { id },
});
if (!dataCredentials) {
res.status(400).json({ error: "Invalid custom credentials id" });
return;
}
const credentials = dataCredentials?.credentials;
const hashedUrl = await hash(credentials, 12);
const cachedPrisma = cache.get(hashedUrl);
if (!cachedPrisma) {
cache.put(
hashedUrl,
customPrisma({ datasources: { db: { url: credentials } } }),
PRISMA_CLIENT_CACHING_TIME // Cache the prisma client for 24 hours
);
}
req.prisma = cachedPrisma;
}
await next();
};
+4 -2
View File
@@ -3,14 +3,16 @@ import { NextMiddleware } from "next-api-middleware";
import type { PrismaClient } from ".prisma/client";
/** @todo figure how to use the one from `@calcom/types`fi */
/** @todo figure how to use the one from `@calcom/types` */
/** @todo: remove once `@calcom/types` is updated with it.*/
declare module "next" {
export interface NextApiRequest extends IncomingMessage {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
body: any;
userId: number;
method: string;
prisma: PrismaClient;
body: any;
session: { user: { id: number } };
query: { [key: string]: string | string[] };
}
}
+6 -12
View File
@@ -3,18 +3,6 @@ import { NextMiddleware } from "next-api-middleware";
import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys";
// // import prisma from "@calcom/prisma";
// /** @todo figure how to use the one from `@calcom/types`fi */
// /** @todo: remove once `@calcom/types` is updated with it.*/
// declare module "next" {
// export interface NextApiRequest extends IncomingMessage {
// userId: number;
// method: string;
// query: { [key: string]: string | string[] };
// }
// }
// Used to check if the apiKey is not expired, could be extracted if reused. but not for now.
export const dateNotInPast = function (date: Date) {
const now = new Date();
@@ -27,12 +15,18 @@ export const dateNotInPast = function (date: Date) {
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
const { prisma } = req;
if (!req.query.apiKey) return res.status(401).json({ message: "No apiKey provided" });
console.log("req.query.apiKey", req.query.apiKey);
// We remove the prefix from the user provided api_key. If no env set default to "cal_"
const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "cal_", "");
console.log("strippedApiKey", strippedApiKey);
// Hash the key again before matching against the database records.
const hashedKey = hashAPIKey(strippedApiKey);
console.log("hashedKey", hashedKey);
// Check if the hashed api key exists in database.
const apiKey = await prisma.apiKey.findUnique({ where: { hashedKey } });
// console.log("apiKey", apiKey);
// If we cannot find any api key. Throw a 401 Unauthorized.
if (!apiKey) return res.status(401).json({ error: "Your apiKey is not valid" });
if (apiKey.expiresAt && dateNotInPast(apiKey.expiresAt)) {
+4 -3
View File
@@ -2,7 +2,7 @@ import { label } from "next-api-middleware";
import { addRequestId } from "./addRequestid";
import { captureErrors } from "./captureErrors";
import { customApiEndpoints } from "./customApiEndpoints";
import { customPrismaClient } from "./customPrisma";
import { extendRequest } from "./extendRequest";
import {
HTTP_POST,
@@ -24,11 +24,12 @@ const withMiddleware = label(
HTTP_DELETE,
addRequestId,
verifyApiKey,
customApiEndpoints,
customPrismaClient,
extendRequest,
sentry: captureErrors,
},
["sentry", "customApiEndpoints", "verifyApiKey", "addRequestId", "extendRequest"] // <-- Provide a list of middleware to call automatically
// The order here, determines the order of execution, put customPrismaClient before verifyApiKey always.
["sentry", "customPrismaClient", "verifyApiKey", "addRequestId", "extendRequest"] // <-- Provide a list of middleware to call automatically
);
export { withMiddleware };
+1 -1
View File
@@ -3,6 +3,6 @@ import { UserPermissionRole } from "@prisma/client";
import prisma from "@calcom/prisma";
export const isAdminGuard = async (userId: number) => {
const user = await prisma().user.findUnique({ where: { id: userId } });
const user = await prisma.user.findUnique({ where: { id: userId } });
return user?.role === UserPermissionRole.ADMIN;
};