62 lines
2.2 KiB
TypeScript
62 lines
2.2 KiB
TypeScript
import { ICustomerJwtPayload, IUserJwtPayload } from "@Front/Services/JwtService/JwtService";
|
|
import jwt_decode from "jwt-decode";
|
|
import { NextResponse } from "next/server";
|
|
import type { NextRequest } from "next/server";
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
const cookieStaging = request.cookies.get("protect_staging");
|
|
if (!cookieStaging) return NextResponse.redirect(new URL("/protect", request.url));
|
|
|
|
// Get the JWT from the cookies
|
|
const cookies = request.cookies.get("leCoffreAccessToken");
|
|
if (!cookies) return NextResponse.redirect(new URL("/login", request.url));
|
|
|
|
// Decode it
|
|
const userDecodedToken = jwt_decode(cookies.value) as IUserJwtPayload;
|
|
const customerDecodedToken = jwt_decode(cookies.value) as ICustomerJwtPayload;
|
|
|
|
// If no JWT provided, redirect to login page
|
|
if (!userDecodedToken && !customerDecodedToken) return NextResponse.redirect(new URL("/login", request.url));
|
|
|
|
// If JWT expired, redirect to login page
|
|
const token = userDecodedToken ?? customerDecodedToken;
|
|
const now = Math.floor(Date.now() / 1000);
|
|
if (token.exp < now) {
|
|
return NextResponse.redirect(new URL("/login", request.url));
|
|
}
|
|
|
|
const requestUrlPath = request.nextUrl.pathname;
|
|
if (
|
|
requestUrlPath.startsWith("/collaborators") ||
|
|
requestUrlPath.startsWith("/deed-types") ||
|
|
requestUrlPath.startsWith("/customer") ||
|
|
requestUrlPath.startsWith("/offices") ||
|
|
requestUrlPath.startsWith("/roles") ||
|
|
requestUrlPath.startsWith("/users")
|
|
) {
|
|
if (userDecodedToken.role !== "admin" && userDecodedToken.role !== "super-admin")
|
|
return NextResponse.redirect(new URL("/404", request.url));
|
|
}
|
|
if ((requestUrlPath.startsWith("/my-account") || requestUrlPath.startsWith("/document-types")) && !userDecodedToken)
|
|
return NextResponse.redirect(new URL("/404", request.url));
|
|
if (requestUrlPath.startsWith("/client-dashboard") && !customerDecodedToken) return NextResponse.redirect(new URL("/404", request.url));
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: [
|
|
"/client-dashboard/:path*",
|
|
"/collaborators/:path*",
|
|
"/customer/:path*",
|
|
"/document-types/:path*",
|
|
"/deed-types/:path*",
|
|
"/folders/:path*",
|
|
"/my-account/:path*",
|
|
"/offices/:path*",
|
|
"/roles/:path*",
|
|
"/users/:path*",
|
|
"/",
|
|
],
|
|
};
|