59 lines
1.9 KiB
TypeScript
59 lines
1.9 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { getSessionCookieName, verifySessionToken } from "@/lib/auth";
|
|
|
|
function normalizeHost(host: string) {
|
|
return host.split(":")[0].toLowerCase();
|
|
}
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
const pathname = request.nextUrl.pathname;
|
|
const search = request.nextUrl.search;
|
|
const host = normalizeHost(request.headers.get("host") || "");
|
|
const crmHost = (process.env.CRM_HOST || "crm.workparking.ru").toLowerCase();
|
|
|
|
const isCrmHost = host === crmHost;
|
|
const isAdminPath = pathname.startsWith("/admin");
|
|
const isLoginPage = pathname === "/admin/login";
|
|
|
|
const token = request.cookies.get(getSessionCookieName())?.value;
|
|
const isAuthed = await verifySessionToken(token);
|
|
|
|
// Если открыли crm.workparking.ru/ — сразу ведём в CRM
|
|
if (isCrmHost && pathname === "/") {
|
|
const url = request.nextUrl.clone();
|
|
url.pathname = isAuthed ? "/admin/leads" : "/admin/login";
|
|
url.search = "";
|
|
return NextResponse.redirect(url);
|
|
}
|
|
|
|
// Если admin открыли не на CRM-домене — уводим на CRM без порта
|
|
if (isAdminPath && !isCrmHost) {
|
|
const url = request.nextUrl.clone();
|
|
url.protocol = "https";
|
|
url.hostname = crmHost;
|
|
url.port = "";
|
|
return NextResponse.redirect(url);
|
|
}
|
|
|
|
if (isAdminPath) {
|
|
if (!isAuthed && !isLoginPage) {
|
|
const loginUrl = request.nextUrl.clone();
|
|
loginUrl.pathname = "/admin/login";
|
|
loginUrl.search = `?next=${encodeURIComponent(`${pathname}${search}`)}`;
|
|
return NextResponse.redirect(loginUrl);
|
|
}
|
|
|
|
if (isAuthed && isLoginPage) {
|
|
const url = request.nextUrl.clone();
|
|
url.pathname = "/admin/leads";
|
|
url.search = "";
|
|
return NextResponse.redirect(url);
|
|
}
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ["/", "/admin/:path*"],
|
|
}; |