import { NextResponse } from 'next/server'; import { withAuth, NextRequestWithAuth } from "next-auth/middleware"; const rewriteURL = (request: NextRequestWithAuth, originBaseURL: string, destinationBaseURL: string, headers: any = {}) => { const destinationURL = request.url.replace(originBaseURL, destinationBaseURL); console.log(`Rewriting ${request.url} to ${destinationURL}`); const requestHeaders = new Headers(request.headers); for (const [key, value] of Object.entries(headers)) { requestHeaders.set(key, value as string); } requestHeaders.delete('connection'); return NextResponse.rewrite(new URL(destinationURL), { request: { headers: requestHeaders } }); }; const checkRewrites = async (request: NextRequestWithAuth) => { const linkBaseURL = process.env.LINK_URL ?? "http://localhost:3000"; const zammadURL = process.env.ZAMMAD_URL ?? "http://zammad-nginx:8080"; const metamigoURL = process.env.METAMIGO_URL ?? "http://metamigo-api:3000"; const labelStudioURL = process.env.LABEL_STUDIO_URL ?? "http://label-studio:8080"; const { token } = request.nextauth; if (request.nextUrl.pathname.startsWith('/metamigo')) { return rewriteURL(request, `${linkBaseURL}/metamigo`, metamigoURL); } else if (request.nextUrl.pathname.startsWith('/label-studio')) { return rewriteURL(request, `${linkBaseURL}/label-studio`, labelStudioURL); } else if (request.nextUrl.pathname.startsWith('/zammad')) { return rewriteURL(request, `${linkBaseURL}/zammad`, zammadURL); } else if (request.nextUrl.pathname.startsWith('/auth/sso') || request.nextUrl.pathname.startsWith('/assets')) { const headers = { 'X-Forwarded-User': token.email.toLowerCase() }; return rewriteURL(request, linkBaseURL, zammadURL, headers); } else if (request.nextUrl.pathname.startsWith('/proxy/api') || request.nextUrl.pathname.startsWith('/proxy/assets')) { return rewriteURL(request, `${linkBaseURL}/proxy`, zammadURL); } else if (request.nextUrl.pathname.startsWith('/api/v1') || request.nextUrl.pathname.startsWith('/auth/sso')) { return rewriteURL(request, linkBaseURL, zammadURL); } return NextResponse.next(); }; export default withAuth( checkRewrites, { pages: { signIn: `/login`, }, callbacks: { authorized: ({ token, req }) => { const { url, } = req; const noAuthPaths = ["/login", "/zammad/api/v1"]; const parsedURL = new URL(url); const path = parsedURL.pathname; console.log({ p: parsedURL.pathname }); if (noAuthPaths.some((p: string) => path.startsWith(p))) { console.log({ a: "no auth" }); return true; } const roles: any = token?.roles ?? []; if (roles.includes("admin") || roles.includes("agent")) { return true; } return false; }, } } ); export const config = { matcher: [ '/((?!ws|_next/static|_next/image|favicon.ico).*)', ], };