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

41 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-04-22 01:36:33 +00:00
import type { IncomingMessage } from "http";
import { NextMiddleware } from "next-api-middleware";
2022-03-30 12:17:55 +00:00
import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys";
import prisma from "@calcom/prisma";
2022-04-22 01:36:33 +00:00
/** @todo figure how to use the one from `@calcom/types`fi */
declare module "next" {
export interface NextApiRequest extends IncomingMessage {
userId: number;
}
}
2022-04-23 00:26:35 +00:00
// Used to check if the apiKey is not expired, could be extracted if reused. but not for now.
export const dateNotInPast = function (date: Date) {
const now = new Date();
2022-04-23 01:46:53 +00:00
if (now.setHours(0, 0, 0, 0) >= date.setHours(0, 0, 0, 0)) {
2022-03-30 12:17:55 +00:00
return true;
}
};
2022-04-23 00:26:35 +00:00
// This verifies the apiKey and sets the user if it is valid.
2022-04-22 14:05:31 +00:00
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
2022-04-23 00:26:35 +00:00
if (!req.query.apiKey) return res.status(401).json({ message: "No apiKey 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_", "");
// Hash the key again before matching against the database records.
const hashedKey = hashAPIKey(strippedApiKey);
// Check if the hashed api key exists in database.
2022-04-22 01:36:33 +00:00
const apiKey = await prisma.apiKey.findUnique({ where: { hashedKey } });
// If we cannot find any api key. Throw a 401 Unauthorized.
2022-04-23 00:26:35 +00:00
if (!apiKey) return res.status(401).json({ error: "Your apiKey is not valid" });
if (apiKey.expiresAt && dateNotInPast(apiKey.expiresAt)) {
2022-04-23 00:26:35 +00:00
return res.status(401).json({ error: "This apiKey is expired" });
2022-04-22 01:36:33 +00:00
}
2022-04-23 00:26:35 +00:00
if (!apiKey.userId) return res.status(404).json({ error: "No user found for this apiKey" });
2022-04-22 01:36:33 +00:00
/* We save the user id in the request for later use */
req.userId = apiKey.userId;
await next();
};