Skip to content

Commit

Permalink
[RSN-74] - Add middleware for handling protected routes (#68)
Browse files Browse the repository at this point in the history
  • Loading branch information
raczu authored Jun 23, 2024
1 parent 656a913 commit 40dd22b
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Client/reasn-client/apps/web/middleware.ts
Original file line number Diff line number Diff line change
@@ -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/(.*)",
],
};

0 comments on commit 40dd22b

Please sign in to comment.