Skip to content

Commit

Permalink
🔄 Update middleware.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
ad956 committed Jul 15, 2024
1 parent 3b42094 commit f09bb41
Showing 1 changed file with 5 additions and 46 deletions.
51 changes: 5 additions & 46 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import { NextRequest, NextResponse } from "next/server";
import { decrypt, updateSession } from "@sessions/sessionUtils";

const PublicRoutes = ["/", "/login", "/signup"];
const PrivateRoutes = [
"/patient",
"/receptionist",
"/doctor",
"/hospital",
// "/admin",
];
import {
PublicRoutes,
redirectMiddleware,
updateSessionMiddleware,
} from "@middlewares/index";

export async function middleware(request: NextRequest) {
if (!PublicRoutes.includes(request.nextUrl.pathname)) {
Expand All @@ -25,42 +20,6 @@ export async function middleware(request: NextRequest) {
return redirectMiddleware(request);
}

export async function updateSessionMiddleware(request: NextRequest) {
try {
await updateSession(request);
return true;
} catch (error) {
console.error("Error updating session:", error);
return false;
}
}

export async function redirectMiddleware(request: NextRequest) {
const path = request.nextUrl.pathname;
const token = request.cookies.get("session")?.value;

const isPublicRoute = PublicRoutes.includes(path);
const isPrivateRoute = PrivateRoutes.includes(`/${path.split("/")[1]}`); // extracts the user path from url

if (token) {
const decryptedToken = await decrypt(token);
const userRole = decryptedToken.user.role;

if (isPublicRoute && token) {
return NextResponse.redirect(new URL(`/${userRole}`, request.url));
}

if (isPrivateRoute && path.split("/")[1] !== userRole) {
return NextResponse.redirect(new URL(`/${userRole}`, request.url));
}
}
if (isPrivateRoute && !token) {
return NextResponse.redirect(new URL(`/login`, request.url));
}

return NextResponse.next();
}

// Optionally, don't invoke Middleware on some paths
export const config = {
matcher: [
Expand Down

0 comments on commit f09bb41

Please sign in to comment.