FPSMS-frontend
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

44 行
1.4 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. if (!Boolean(token)) {
  11. return Boolean(token)
  12. }
  13. // example
  14. // const abilities = token!.abilities as string[]
  15. // if (req.nextUrl.pathname.endsWith('/user') && 'abilities dont hv view/maintain user') {
  16. // return false
  17. // }
  18. return true
  19. }
  20. }
  21. });
  22. export default async function middleware(
  23. req: NextRequestWithAuth,
  24. event: NextFetchEvent,
  25. ) {
  26. const langPref = req.nextUrl.searchParams.get(LANG_QUERY_PARAM);
  27. if (langPref) {
  28. // Redirect to same url without the lang query param + set cookies
  29. const newUrl = new URL(req.nextUrl);
  30. newUrl.searchParams.delete(LANG_QUERY_PARAM);
  31. const response = NextResponse.redirect(newUrl);
  32. response.cookies.set("i18next", langPref);
  33. return response;
  34. }
  35. // Matcher for using the auth middleware
  36. return PRIVATE_ROUTES.some((route) => req.nextUrl.pathname.startsWith(route))
  37. ? await authMiddleware(req, event) // Let auth middleware handle response
  38. : NextResponse.next(); // Return normal response
  39. }