feat: successfully protected all endpoints with next-api-middleware for verifyApiKey

This commit is contained in:
Agusti Fernandez Pardo committed 2022-03-29 02:25:24 +02:00
1 parent 752a61c756
commit ec8fe36930
8 files changed
+167 -89

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
import { NextMiddleware } from "next-api-middleware";
import { nanoid } from "nanoid";
export const addRequestId: NextMiddleware = async (_req, res, next) => {
// Apply header
res.setHeader("X-Response-ID", nanoid());
// Let remaining middleware and API route execute
await next();
};
-47
View File
@@ -1,47 +0,0 @@
import { label, NextMiddleware } from "next-api-middleware";
import * as Sentry from "@sentry/nextjs";
import nanoid from "nanoid";
// 1 – Create middleware functions
const captureErrors: NextMiddleware = async (req, res, next) => {
try {
// Catch any errors that are thrown in remaining
// middleware and the API route handler
await next();
} catch (err) {
const eventId = Sentry.captureException(err);
res.status(500);
res.json({ error: err });
}
};
const addRequestId: NextMiddleware = async (req, res, next) => {
// Let remaining middleware and API route execute
await next();
// Apply header
res.setHeader("X-Response-ID", nanoid());
};
// 2 – Use `label` to assemble all middleware
const withMiddleware = label(
{
addRequestId,
sentry: captureErrors, // <-- Optionally alias middleware
},
["sentry"] // <-- Provide a list of middleware to call automatically
);
// 3 – Define your API route handler
const apiRouteHandler = async (req, res) => {
res.status(200);
res.send("Hello world!");
};
// 4 – Choose middleware to invoke for this API route
export default withMiddleware("addRequestId")(apiRouteHandler);
+16
View File
@@ -0,0 +1,16 @@
import { NextMiddleware } from "next-api-middleware";
import * as Sentry from "@sentry/nextjs";
export const captureErrors: NextMiddleware = async (_req, res, next) => {
try {
// Catch any errors that are thrown in remaining
// middleware and the API route handler
await next();
} catch (err) {
const eventId = Sentry.captureException(err);
console.log(eventId)
res.status(500);
res.json({ error: err });
}
};
+18 -34
View File
@@ -1,36 +1,20 @@
// https://github.com/htunnicliff/next-api-middleware
// import prisma from "@calcom/prisma";
import { NextMiddleware } from "next-api-middleware";
// import { nanoid } from "nanoid";
import prisma from "@calcom/prisma";
// import { User } from "@calcom/prisma/client";
// import type { NextApiRequest, NextApiResponse } from "next";
const dateInPast = function (firstDate: Date, secondDate: Date) {
if (firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0)) {
return true;
}
}
const today = new Date();
// type ResponseData = {
// data?: User[];
// error?: unknown;
// };
// const dateInPast = function (firstDate: Date, secondDate: Date) {
// if (firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0)) {
// return true;
// }
// return false;
// };
// const today = new Date();
// export default async function user(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
// const apiKey = req.query.apiKey as string;
// const apiInDb = await prisma.apiKey.findUnique({ where: { id: apiKey } });
// if (!apiInDb) throw new Error('API key not found');
// const { expiresAt } = apiInDb;
// // if (!apiInDb) res.status(400).json({ error: 'Your api key is not valid' });
// if (expiresAt && dateInPast(expiresAt, today)) {
// try {
// const data = await prisma.user.findMany();
// res.status(200).json({ data });
// } catch (error) {
// // FIXME: Add zod for validation/error handling
// res.status(400).json({ error: error });
// }
// } else res.status(400).json({ error: 'Your api key is not valid' });
// }
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.apiKey as string } });
if (!apiKey) {
res.status(400).json({ error: 'Your api key is not valid' });
throw new Error('No api key found');
}
if (apiKey.expiresAt && dateInPast(apiKey.expiresAt, today)) await next();
else res.status(400).json({ error: 'Your api key is not valid' });
};
+15
View File
@@ -0,0 +1,15 @@
import { label } from "next-api-middleware";
import { addRequestId } from "./addRequestid";
import { captureErrors } from "./captureErrors";
import { verifyApiKey } from "./verifyApiKey";
const withMiddleware = label(
{
addRequestId,
verifyApiKey,
sentry: captureErrors, // <-- Optionally alias middleware
},
["sentry","verifyApiKey"] // <-- Provide a list of middleware to call automatically
);
export default withMiddleware;