cal.pub0.org/lib/helpers/verifyApiKey.ts

27 lines
955 B
TypeScript
Raw Normal View History

import { NextMiddleware } from "next-api-middleware";
2022-03-30 12:17:55 +00:00
// import { nanoid } from "nanoid";
import prisma from "@calcom/prisma";
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;
}
};
const today = new Date();
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
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) {
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.userId) {
res.setHeader("X-Calcom-User-ID", apiKey.userId);
}
2022-04-04 20:29:45 +00:00
if (apiKey.expiresAt && apiKey.userId && dateInPast(today, apiKey.expiresAt)) {
2022-03-30 12:17:55 +00:00
await next();
} else res.status(401).json({ error: "Your api key is not valid" });
};