lecoffre-front/src/middleware.ts
2023-12-11 17:09:44 +01:00

45 lines
1.5 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) {
// 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 callback page to refresh tokens
const now = Math.floor(Date.now() / 1000);
if (userDecodedToken.userId && userDecodedToken.exp < now) {
return NextResponse.redirect(new URL("/authorized-client", request.url));
}
if (customerDecodedToken.customerId && customerDecodedToken.exp < now) {
return NextResponse.redirect(new URL("/id360/customer-callback", 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*",
"/",
],
};