Weird middleware issues
This commit is contained in:
parent
4066e7afa5
commit
a2ba66a77b
3 changed files with 19 additions and 17 deletions
|
@ -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 = {
|
||||
|
|
6
src/pages/api/external/ping.ts
vendored
6
src/pages/api/external/ping.ts
vendored
|
@ -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) {
|
||||
console.log("Made it to the function!");
|
||||
res.status(200).json({ result: "Pong!" });
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
};
|
||||
|
|
Loading…
Add table
Reference in a new issue