From 40dd22bd2f136f2c0cb5dfd1fbd0f71d9bcb68af Mon Sep 17 00:00:00 2001 From: Dawid Machoczek Date: Sun, 23 Jun 2024 14:51:58 +0200 Subject: [PATCH] [RSN-74] - Add middleware for handling protected routes (#68) --- Client/reasn-client/apps/web/middleware.ts | 36 ++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Client/reasn-client/apps/web/middleware.ts diff --git a/Client/reasn-client/apps/web/middleware.ts b/Client/reasn-client/apps/web/middleware.ts new file mode 100644 index 0000000..55effad --- /dev/null +++ b/Client/reasn-client/apps/web/middleware.ts @@ -0,0 +1,36 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { getSession } from "@/lib/session"; +import { UserRole } from "@reasn/common/src/enums/schemasEnums"; + +export const middleware = (req: NextRequest) => { + const session = getSession(); + const path = req.nextUrl.pathname; + + const isAuthPath = path.startsWith("/login") || path.startsWith("/register"); + + if (!session.isAuthenticated()) { + if (isAuthPath) return NextResponse.next(); + return NextResponse.redirect(new URL("/login", req.url)); + } + + if (isAuthPath) { + return NextResponse.redirect(new URL("/me", req.url)); + } + + if (path.startsWith("/events") && session.user?.role === UserRole.USER) { + return NextResponse.redirect(new URL("/events", req.url)); + } +}; + +export const config = { + matcher: [ + "/events/new", + "/events/(.*)/(.*)", + "/me", + "/me/(.*)", + "/login", + "/register", + "/register/(.*)", + ], +};