From 96f7bcb7e27273ef52f17c5959354ff9bc0f7bb2 Mon Sep 17 00:00:00 2001 From: Atridad Lahiji Date: Thu, 5 Oct 2023 00:58:00 -0600 Subject: [PATCH] Changed middleware --- middleware.ts | 79 +++++++++++++-------------------------------------- 1 file changed, 19 insertions(+), 60 deletions(-) diff --git a/middleware.ts b/middleware.ts index d1a3bd7..347520f 100644 --- a/middleware.ts +++ b/middleware.ts @@ -15,74 +15,33 @@ const rateLimit = new Ratelimit({ }); export default authMiddleware({ + ignoredRoutes: ["/"], publicRoutes: [ - "/", "/api/external/public/(.*)", "/api/webhooks", "/api/webhooks/(.*)", ], - afterAuth: async (auth, req) => { - if (!auth.userId && auth.isPublicRoute) { - const { success } = await rateLimit.limit(req.ip || ""); - if (success) { - return NextResponse.next(); + apiRoutes: ["/api/external/private/(.*)", "/api/internal/(.*)"], + beforeAuth: async (req) => { + const { success } = await rateLimit.limit(req.ip || ""); + if (success) { + if (req.nextUrl.pathname.includes("/api/external/private")) { + const isValid = await validateRequest(req); + + if (!isValid) { + return new NextResponse("UNAUTHORIZED", { + status: 403, + statusText: "Unauthorized!", + }); + } } - return new NextResponse("TOO MANY REQUESTS", { - status: 429, - statusText: "Too many requests!", - }); + return NextResponse.next(); } - if (req.nextUrl.pathname.includes("/api/internal")) { - const { success } = await rateLimit.limit(req.ip || ""); - - if (!success) { - return new NextResponse("TOO MANY REQUESTS", { - status: 429, - statusText: "Too many requests!", - }); - } - - if (auth.userId) { - return NextResponse.next(); - } else { - return new NextResponse("UNAUTHORIZED", { - status: 403, - statusText: "Unauthorized!", - }); - } - } - - if (req.nextUrl.pathname.includes("/api/external/private")) { - const { success } = await rateLimit.limit(req.ip || ""); - - if (!success) { - return new NextResponse("TOO MANY REQUESTS", { - status: 429, - statusText: "Too many requests!", - }); - } - - const isValid = await validateRequest(req); - - if (isValid) { - return NextResponse.next(); - } else { - return new NextResponse("UNAUTHORIZED", { - status: 403, - statusText: "Unauthorized!", - }); - } - } - - if (!auth.userId && !auth.isPublicRoute) { - if (req.nextUrl.pathname.includes("/api")) { - return NextResponse.next(); - } - // This is annoying... - // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any - return redirectToSignIn({ returnBackUrl: req.url }); - } + return new NextResponse("TOO MANY REQUESTS", { + status: 429, + statusText: "Too many requests!", + }); }, });