some fixes on helpers/middlewares

pull/9078/head
Agusti Fernandez Pardo 2022-04-08 18:08:26 +02:00
parent fc3677631f
commit 9edc1dbd29
8 changed files with 29 additions and 47 deletions

1
.env.example Normal file
View File

@ -0,0 +1 @@
API_KEY_PREFIX=cal_

View File

@ -2,7 +2,7 @@ import { nanoid } from "nanoid";
import { NextMiddleware } from "next-api-middleware"; import { NextMiddleware } from "next-api-middleware";
export const addRequestId: NextMiddleware = async (_req, res, next) => { export const addRequestId: NextMiddleware = async (_req, res, next) => {
// Apply header // Apply header with unique ID to every request
res.setHeader("Calcom-Response-ID", nanoid()); res.setHeader("Calcom-Response-ID", nanoid());
// Let remaining middleware and API route execute // Let remaining middleware and API route execute
await next(); await next();

View File

@ -6,10 +6,9 @@ export const captureErrors: NextMiddleware = async (_req, res, next) => {
// Catch any errors that are thrown in remaining // Catch any errors that are thrown in remaining
// middleware and the API route handler // middleware and the API route handler
await next(); await next();
} catch (err) { } catch (error) {
Sentry.captureException(err); Sentry.captureException(error);
console.log(err); console.log(error);
res.status(400).json({ message: "Something went wrong", error: err }); res.status(400).json({ message: "Something went wrong", error });
// res.json({ error: err });
} }
}; };

View File

@ -1,29 +1,34 @@
import { NextMiddleware } from "next-api-middleware"; import { NextMiddleware } from "next-api-middleware";
import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys"; import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys";
// import { nanoid } from "nanoid";
import prisma from "@calcom/prisma"; import prisma from "@calcom/prisma";
const dateInPast = function (firstDate: Date, secondDate: Date) { // Used to check if the API key is not expired, could be extracted if reused. but not for now.
export const dateInPast = function (firstDate: Date, secondDate: Date) {
if (firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0)) { if (firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0)) {
return true; return true;
} }
}; };
const today = new Date(); const today = new Date();
// This verifies the API key and sets the user if it is valid.
export const verifyApiKey: NextMiddleware = async (req, res, next) => { export const verifyApiKey: NextMiddleware = async (req, res, next) => {
if (!req.query.apiKey) res.status(401).json({ message: "No API key provided" }); if (!req.query.apiKey) res.status(401).json({ message: "No API key provided" });
const strippedApiKey = `${req.query.apiKey}`.replace("cal_", "");
const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "cal_", "");
const hashedKey = hashAPIKey(strippedApiKey); const hashedKey = hashAPIKey(strippedApiKey);
const apiKey = await prisma.apiKey.findUnique({ where: { hashedKey } });
await prisma.apiKey
.findUnique({ where: { hashedKey } })
.then(async (apiKey) => {
if (!apiKey) { if (!apiKey) {
res.status(401).json({ error: "Your api key is not valid" }); res.status(401).json({ error: "You did not provide an api key" });
throw new Error("No api key found"); throw new Error("No api key found");
} }
if (apiKey.userId) { if (apiKey.userId) res.setHeader("X-Calcom-User-ID", apiKey?.userId);
res.setHeader("X-Calcom-User-ID", apiKey.userId); if (apiKey.expiresAt && apiKey.userId && dateInPast(today, apiKey.expiresAt)) await next();
} })
if (apiKey.expiresAt && apiKey.userId && dateInPast(today, apiKey.expiresAt)) { .catch((error) => {
await next(); res.status(401).json({ error: "Your api key is not valid" });
} else res.status(401).json({ error: "Your api key is not valid" }); });
}; };

View File

@ -1,23 +0,0 @@
// Make a middleware that adds a cost to running the request
// by calling stripeSubscription addCost() * pricePerBooking
// Initially to test out 0,5 cent per booking via API call
// withCost(5)(endpoint)
// Should add a charge of 0.5 cent per booking to the subscription of the user making the request
import { NextMiddleware } from "next-api-middleware";
export const withCost = (priceInCents: number): NextMiddleware => {
return async function (req, res, next) {
console.log(req.headers);
if (
priceInCents > 0
// && stripeCustomerId && stripeSubscriptionId
) {
console.log(priceInCents);
// if (req.method === allowedHttpMethod || req.method == "OPTIONS") {
await next();
} else {
res.status(405).json({ message: `We weren't able to process the payment for this transaction` });
res.end();
}
};
};

View File

@ -0,0 +1,3 @@
import { NextApiResponse } from "next";
export const getCalcomUserId = (res: NextApiResponse): number => res.getHeader("x-calcom-user-id") as number;

View File

@ -1,3 +0,0 @@
import { NextApiResponse } from "next";
export const getCalcomUserId = (res: NextApiResponse) => res.getHeader("x-calcom-user-id") as number;

View File

@ -4,7 +4,7 @@ import prisma from "@calcom/prisma";
import { withMiddleware } from "@lib/helpers/withMiddleware"; import { withMiddleware } from "@lib/helpers/withMiddleware";
import { AttendeeResponse, AttendeesResponse } from "@lib/types"; import { AttendeeResponse, AttendeesResponse } from "@lib/types";
import { getCalcomUserId } from "@lib/utils/getUserFromHeader"; import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
import { schemaAttendeeBodyParams, schemaAttendeePublic, withValidAttendee } from "@lib/validations/attendee"; import { schemaAttendeeBodyParams, schemaAttendeePublic, withValidAttendee } from "@lib/validations/attendee";
/** /**