pollo/src/middleware.ts

37 lines
1 KiB
TypeScript
Raw Normal View History

2023-08-17 20:55:56 -06:00
import { authMiddleware, redirectToSignIn } from "@clerk/nextjs";
2023-08-17 16:40:09 -06:00
import { validateRequest } from "./server/unkey";
import { NextResponse } from "next/server";
2023-08-12 17:12:42 -06:00
export default authMiddleware({
2023-08-17 20:55:56 -06:00
publicRoutes: ["/", "/api/public/(.*)"],
afterAuth: async (auth, req) => {
if (!auth.userId && auth.isPublicRoute) {
console.log("1");
return NextResponse.next();
}
if (
req.nextUrl.pathname.includes("/api/webhooks") ||
req.nextUrl.pathname.includes("/api/private")
) {
console.log("2");
2023-08-17 16:40:09 -06:00
const isValid = await validateRequest(req);
console.log("Is Valid?: ", isValid);
if (isValid) {
return NextResponse.next();
2023-08-17 20:55:56 -06:00
} else {
return new NextResponse("UNAUTHORIZED", { status: 403 });
2023-08-17 16:40:09 -06:00
}
2023-08-17 20:55:56 -06:00
}
if (!auth.userId && !auth.isPublicRoute) {
console.log(req.nextUrl);
console.log("3");
return redirectToSignIn({ returnBackUrl: req.url });
2023-08-17 16:40:09 -06:00
}
},
2023-08-12 17:12:42 -06:00
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};