2022-03-29 00:25:24 +00:00
|
|
|
import { NextMiddleware } from "next-api-middleware";
|
2022-03-30 12:17:55 +00:00
|
|
|
|
2022-04-07 23:59:04 +00:00
|
|
|
import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys";
|
2022-03-29 00:25:24 +00:00
|
|
|
import prisma from "@calcom/prisma";
|
2022-03-28 22:27:14 +00:00
|
|
|
|
2022-04-08 16:08:26 +00:00
|
|
|
// 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) {
|
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-04-08 16:08:26 +00:00
|
|
|
// This verifies the API key and sets the user if it is valid.
|
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-04-08 16:08:26 +00:00
|
|
|
|
2022-04-13 00:12:16 +00:00
|
|
|
const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "pt_secret_", "");
|
2022-04-07 23:59:04 +00:00
|
|
|
const hashedKey = hashAPIKey(strippedApiKey);
|
2022-04-08 16:08:26 +00:00
|
|
|
|
|
|
|
await prisma.apiKey
|
|
|
|
.findUnique({ where: { hashedKey } })
|
|
|
|
.then(async (apiKey) => {
|
|
|
|
if (!apiKey) {
|
|
|
|
res.status(401).json({ error: "You did not provide an api key" });
|
|
|
|
throw new Error("No api key found");
|
|
|
|
}
|
2022-04-13 00:12:16 +00:00
|
|
|
if (apiKey.userId) res.setHeader("X-Calcom-User-ID", apiKey.userId);
|
2022-04-08 16:08:26 +00:00
|
|
|
if (apiKey.expiresAt && apiKey.userId && dateInPast(today, apiKey.expiresAt)) await next();
|
|
|
|
})
|
|
|
|
.catch((error) => {
|
|
|
|
res.status(401).json({ error: "Your api key is not valid" });
|
|
|
|
});
|
2022-03-29 00:25:24 +00:00
|
|
|
};
|