FPSMS-frontend
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 

54 строки
1.8 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. // Handle language parameters
  26. const langPref = req.nextUrl.searchParams.get(LANG_QUERY_PARAM);
  27. if (langPref) {
  28. const newUrl = new URL(req.nextUrl);
  29. newUrl.searchParams.delete(LANG_QUERY_PARAM);
  30. const response = NextResponse.redirect(newUrl);
  31. response.cookies.set("i18next", langPref);
  32. return response;
  33. }
  34. // Check if the current URL starts with any string in PRIVATE_ROUTES
  35. const isPrivateRoute = PRIVATE_ROUTES.some((route) =>
  36. req.nextUrl.pathname.startsWith(route)
  37. );
  38. // Debugging: View terminal logs to see if the path is being caught
  39. if (req.nextUrl.pathname.startsWith("/ps") || req.nextUrl.pathname.startsWith("/testing")) {
  40. console.log("--- Middleware Check ---");
  41. console.log("Path:", req.nextUrl.pathname);
  42. console.log("Is Private Match:", isPrivateRoute);
  43. }
  44. return isPrivateRoute
  45. ? await authMiddleware(req, event) // Run authentication check
  46. : NextResponse.next(); // Allow public access
  47. }