import { NextResponse } from 'next/server'; import { withAuth, NextRequestWithAuth } from "next-auth/middleware"; const rewriteURL = (request: NextRequestWithAuth, originBaseURL: string, destinationBaseURL: string, headers: any = {}) => { if (request.nextUrl.protocol.startsWith('ws')) { return NextResponse.next(); } if (request.nextUrl.pathname.includes('/_next/static/development/')) { return NextResponse.next(); } 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)) { // @ts-ignore requestHeaders.set(key, value); } 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 leafcutterURL = process.env.LEAFCUTTER_URL ?? "https://lc.digiresilience.org"; const metamigoURL = process.env.METAMIGO_URL ?? "http://metamigo-frontend:3000"; const labelStudioURL = process.env.LABEL_STUDIO_URL ?? "http://label-studio:8080"; if (request.nextUrl.pathname.startsWith('/proxy/leafcutter')) { const headers = { 'X-Leafcutter-Embedded': "true" }; return rewriteURL(request, `${linkBaseURL}/proxy/leafcutter`, leafcutterURL, headers); } else if (request.nextUrl.pathname.startsWith('/proxy/metamigo')) { return rewriteURL(request, `${linkBaseURL}/proxy/metamigo`, metamigoURL); } else if (request.nextUrl.pathname.startsWith('/proxy/label-studio')) { return rewriteURL(request, `${linkBaseURL}/proxy/label-studio`, labelStudioURL); } else if (request.nextUrl.pathname.startsWith('/proxy/zammad')) { const { token } = request.nextauth; const headers = { 'X-Forwarded-User': token.email.toLowerCase() }; return rewriteURL(request, `${linkBaseURL}/proxy/zammad`, zammadURL, headers); } else if (request.nextUrl.pathname.startsWith('/proxy/api')) { return rewriteURL(request, `${linkBaseURL}/proxy`, zammadURL); } else if (request.nextUrl.pathname.startsWith('/api/v1')) { return rewriteURL(request, linkBaseURL, zammadURL); } }; export default withAuth( checkRewrites, { pages: { signIn: `/login`, }, callbacks: { authorized: ({ token, req }) => { const { url, } = req; // check login page const parsedURL = new URL(url); if (parsedURL.pathname.startsWith('/login')) { return true; } // check session auth const authorizedDomains = ["redaranj.com", "digiresilience.org", "sr2.uk"]; const userDomain = token?.email?.toLowerCase().split("@").pop() ?? "unauthorized.net"; if (authorizedDomains.includes(userDomain)) { return true; } return false; }, } } );