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.
|
2022-04-18 21:24:57 +00:00
|
|
|
export const dateInPast = function (date: Date) {
|
|
|
|
const now = new Date();
|
|
|
|
if (now.setHours(0, 0, 0, 0) <= date.setHours(0, 0, 0, 0)) {
|
2022-03-30 12:17:55 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
};
|
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-04-18 21:24:57 +00:00
|
|
|
if (!req.query.apiKey) res.status(401).json({ message: "No api key provided" });
|
|
|
|
// We remove the prefix from the user provided api_key. If no env set default to "cal_"
|
2022-04-14 19:46:26 +00:00
|
|
|
const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "cal_", "");
|
2022-04-18 21:24:57 +00:00
|
|
|
// Hash the key again before matching against the database records.
|
2022-04-07 23:59:04 +00:00
|
|
|
const hashedKey = hashAPIKey(strippedApiKey);
|
2022-04-18 21:24:57 +00:00
|
|
|
// Check if the hashed api key exists in database.
|
|
|
|
await prisma.apiKey.findUnique({ where: { hashedKey } }).then(async (apiKey) => {
|
|
|
|
// If we cannot find any api key. Throw a 401 Unauthorized.
|
|
|
|
if (!apiKey) res.status(401).json({ error: "Your api key is not valid" });
|
|
|
|
if (apiKey && apiKey.expiresAt && dateInPast(apiKey.expiresAt) && apiKey.userId) {
|
|
|
|
// Right now API Keys are user centric, we only allow resources related to this userId throughout the application.
|
|
|
|
// if the api key is not expired, and the user id is present in the database.
|
|
|
|
// Set the user in the request. as x-calcom-user-id.
|
2022-04-19 11:44:24 +00:00
|
|
|
if (apiKey.userId) res.setHeader("X-Calcom-User-ID", apiKey.userId);
|
|
|
|
|
2022-04-18 21:24:57 +00:00
|
|
|
// Pass the request to the next middleware.
|
|
|
|
await next();
|
|
|
|
}
|
|
|
|
});
|
2022-03-29 00:25:24 +00:00
|
|
|
};
|