Weird middleware issues

This commit is contained in:
Atridad Lahiji 2023-08-17 16:40:09 -06:00
parent 2d83071f6f
commit 5ee4beb662
No known key found for this signature in database
3 changed files with 19 additions and 17 deletions

View file

@ -1,7 +1,19 @@
import { authMiddleware } from "@clerk/nextjs";
import { validateRequest } from "./server/unkey";
import { NextResponse } from "next/server";
export default authMiddleware({
publicRoutes: ["/", "/api/(.*)"],
beforeAuth: async (req) => {
if (req.nextUrl.pathname.startsWith("/api/external")) {
const isValid = await validateRequest(req);
console.log("Is Valid?: ", isValid);
if (isValid) {
return NextResponse.next();
}
return new NextResponse("UNAUTHORIZED", { status: 403 });
}
},
});
export const config = {

View file

@ -1,13 +1,9 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { validateRequest } from "~/server/unkey";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const isValid = await validateRequest(req, res);
if (isValid) {
res.status(200).json({ result: "Pong!" });
}
console.log("Made it to the function!");
res.status(200).json({ result: "Pong!" });
}

View file

@ -1,5 +1,5 @@
import { Unkey } from "@unkey/api";
import type { NextApiRequest, NextApiResponse } from "next";
import { NextRequest } from "next/server";
import { env } from "~/env.mjs";
export const unkey = new Unkey({ token: env.UNKEY_ROOT_KEY });
@ -15,22 +15,16 @@ export const validateApiKey = async (key: string) => {
}
};
export const validateRequest = async (
req: NextApiRequest,
res: NextApiResponse
) => {
export const validateRequest = async (req: NextRequest) => {
let isValidKey: boolean = false;
const authorization = req.headers.get("authorization");
// Get the auth bearer token if it exists
if (req.headers.authorization) {
const key = req.headers.authorization.split("Bearer ").at(1);
if (authorization) {
const key = authorization.split("Bearer ").at(1);
if (key) {
isValidKey = await validateApiKey(key);
}
}
if (!isValidKey) {
res.status(403).json({ error: "UNAUTHORIZED" });
}
return isValidKey;
};