FPSMS-frontend
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

59 lines
2.0 KiB

  1. import { NextRequestWithAuth, withAuth } from "next-auth/middleware";
  2. import { authOptions } from "./config/authConfig";
  3. import { NextFetchEvent, NextResponse } from "next/server";
  4. import { PRIVATE_ROUTES } from "./routes";
  5. const LANG_QUERY_PARAM = "lang";
  6. const authMiddleware = withAuth({
  7. pages: authOptions.pages,
  8. callbacks: {
  9. authorized: ({ req, token }) => {
  10. const currentTime = Math.floor(Date.now() / 1000);
  11. // Redirect to login if:
  12. // 1. No token exists
  13. // 2. Token has an expiry field (exp) and current time has passed it
  14. if (!token || (token.exp && currentTime > (token.exp as number))) {
  15. return false;
  16. }
  17. return true;
  18. },
  19. },
  20. });
  21. export default async function middleware(
  22. req: NextRequestWithAuth,
  23. event: NextFetchEvent,
  24. ) {
  25. const blockedDemoPaths = ["/m18Syn", "/settings/m18ImportTesting", "/testing", "/jo/testing"];
  26. if (blockedDemoPaths.some((path) => req.nextUrl.pathname === path || req.nextUrl.pathname.startsWith(`${path}/`))) {
  27. return NextResponse.redirect(new URL("/dashboard", req.url));
  28. }
  29. // Handle language parameters
  30. const langPref = req.nextUrl.searchParams.get(LANG_QUERY_PARAM);
  31. if (langPref) {
  32. const newUrl = new URL(req.nextUrl);
  33. newUrl.searchParams.delete(LANG_QUERY_PARAM);
  34. const response = NextResponse.redirect(newUrl);
  35. response.cookies.set("i18next", langPref);
  36. return response;
  37. }
  38. // Check if the current URL starts with any string in PRIVATE_ROUTES
  39. const isPrivateRoute = PRIVATE_ROUTES.some((route) =>
  40. req.nextUrl.pathname.startsWith(route)
  41. );
  42. // Debugging: View terminal logs to see if the path is being caught
  43. if (req.nextUrl.pathname.startsWith("/ps") || req.nextUrl.pathname.startsWith("/testing")) {
  44. console.log("--- Middleware Check ---");
  45. console.log("Path:", req.nextUrl.pathname);
  46. console.log("Is Private Match:", isPrivateRoute);
  47. }
  48. return isPrivateRoute
  49. ? await authMiddleware(req, event) // Run authentication check
  50. : NextResponse.next(); // Allow public access
  51. }