50 lines
1.6 KiB
TypeScript
50 lines
1.6 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import type { NextRequest } from 'next/server';
|
|
|
|
export function middleware(request: NextRequest) {
|
|
const hostname = request.headers.get('host') || '';
|
|
const url = request.nextUrl;
|
|
|
|
// Extrair subdomínio
|
|
const subdomain = hostname.split('.')[0];
|
|
|
|
// Se for dash.localhost - rotas administrativas (SUPERADMIN)
|
|
if (subdomain === 'dash') {
|
|
// Permitir acesso a /superadmin, /cadastro, /login
|
|
return NextResponse.next();
|
|
}
|
|
|
|
// Se for agência ({subdomain}.localhost) - validar se existe
|
|
if (hostname.includes('.')) {
|
|
try {
|
|
const res = await fetch(`http://backend:8080/api/tenant/check?subdomain=${subdomain}`);
|
|
if (res.status === 404) {
|
|
// Redireciona para o host base (sem subdomínio)
|
|
const baseHost = hostname.split('.').slice(1).join('.') || hostname;
|
|
const redirectUrl = new URL(url.toString());
|
|
redirectUrl.hostname = baseHost;
|
|
redirectUrl.pathname = '/';
|
|
return NextResponse.redirect(redirectUrl);
|
|
}
|
|
} catch (err) {
|
|
// Em caso de erro de rede, não bloquear
|
|
}
|
|
}
|
|
|
|
// Permitir /dashboard, /login, /clientes, etc.
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: [
|
|
/*
|
|
* Match all request paths except for the ones starting with:
|
|
* - api (API routes)
|
|
* - _next/static (static files)
|
|
* - _next/image (image optimization files)
|
|
* - favicon.ico (favicon file)
|
|
*/
|
|
'/((?!api|_next/static|_next/image|favicon.ico).*)',
|
|
],
|
|
};
|