2022-03-29 00:25:24 +00:00
|
|
|
import { NextMiddleware } from "next-api-middleware";
|
2022-03-30 12:17:55 +00:00
|
|
|
|
2022-03-29 00:25:24 +00:00
|
|
|
// import { nanoid } from "nanoid";
|
|
|
|
import prisma from "@calcom/prisma";
|
2022-03-28 22:27:14 +00:00
|
|
|
|
2022-03-29 00:25:24 +00:00
|
|
|
const dateInPast = function (firstDate: Date, secondDate: Date) {
|
2022-03-30 12:17:55 +00:00
|
|
|
if (firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0)) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
};
|
2022-03-29 00:25:24 +00:00
|
|
|
const today = new Date();
|
2022-03-28 22:27:14 +00:00
|
|
|
|
2022-03-29 00:25:24 +00:00
|
|
|
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
|
2022-03-30 14:56:24 +00:00
|
|
|
if (!req.query.apiKey) res.status(401).json({ message: "No API key provided" });
|
2022-03-30 12:17:55 +00:00
|
|
|
const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.apiKey as string } });
|
|
|
|
if (!apiKey) {
|
2022-03-30 14:56:24 +00:00
|
|
|
res.status(401).json({ error: "Your api key is not valid" });
|
2022-03-30 12:17:55 +00:00
|
|
|
throw new Error("No api key found");
|
|
|
|
}
|
|
|
|
if (apiKey.expiresAt && apiKey.userId && dateInPast(apiKey.expiresAt, today)) {
|
|
|
|
res.setHeader("Calcom-User-ID", apiKey.userId);
|
|
|
|
await next();
|
2022-03-30 14:56:24 +00:00
|
|
|
} else res.status(401).json({ error: "Your api key is not valid" });
|
2022-03-29 00:25:24 +00:00
|
|
|
};
|