-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[RSN-74] - Add middleware for handling protected routes (#68)
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/(.*)", | ||
], | ||
}; |