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.
 
 
 

46 lines
1.4 KiB

  1. import { NextRequestWithAuth, withAuth } from "next-auth/middleware";
  2. // import { authOptions } from "@/config/authConfig";
  3. import { authOptions } from "./config/authConfig";
  4. import { NextFetchEvent, NextResponse } from "next/server";
  5. import { PRIVATE_ROUTES } from "./routes";
  6. const LANG_QUERY_PARAM = "lang";
  7. const authMiddleware = withAuth({
  8. pages: authOptions.pages,
  9. callbacks: {
  10. authorized: ({ req, token }) => {
  11. if (!Boolean(token)) {
  12. return Boolean(token);
  13. }
  14. // example
  15. // const abilities = token!.abilities as string[]
  16. // if (req.nextUrl.pathname.endsWith('/user') && 'abilities dont hv view/maintain user') {
  17. // return false
  18. // }
  19. return true;
  20. },
  21. },
  22. });
  23. export default async function middleware(
  24. req: NextRequestWithAuth,
  25. event: NextFetchEvent,
  26. ) {
  27. const langPref = req.nextUrl.searchParams.get(LANG_QUERY_PARAM);
  28. if (langPref) {
  29. // Redirect to same url without the lang query param + set cookies
  30. const newUrl = new URL(req.nextUrl);
  31. newUrl.searchParams.delete(LANG_QUERY_PARAM);
  32. const response = NextResponse.redirect(newUrl);
  33. response.cookies.set("i18next", langPref);
  34. return response;
  35. }
  36. // Matcher for using the auth middleware
  37. return PRIVATE_ROUTES.some((route) => req.nextUrl.pathname.startsWith(route))
  38. ? await authMiddleware(req, event) // Let auth middleware handle response
  39. : NextResponse.next(); // Return normal response
  40. }