67 lines
1.9 KiB
TypeScript
67 lines
1.9 KiB
TypeScript
import { NextResponse, type NextRequest } from 'next/server';
|
|
import createIntlMiddleware from 'next-intl/middleware';
|
|
import { routing } from '@/i18n/routing';
|
|
|
|
const intlMiddleware = createIntlMiddleware(routing);
|
|
|
|
// Anonymous users may visit these paths without being redirected to /login.
|
|
// Use prefixes — every nested route under each entry is also public.
|
|
const publicPaths = [
|
|
'/login',
|
|
'/register',
|
|
'/auth/callback',
|
|
'/forgot-password',
|
|
'/reset-password',
|
|
'/search',
|
|
'/listings',
|
|
'/khu-cong-nghiep', // industrial parks catalog + detail
|
|
'/du-an', // projects (real estate developments)
|
|
'/chuyen-nhuong', // property transfers
|
|
'/bang-gia', // pricing
|
|
'/pricing',
|
|
'/about',
|
|
'/contact',
|
|
'/privacy',
|
|
'/terms',
|
|
];
|
|
const publicExactPaths = ['/'];
|
|
const authOnlyPaths = ['/login', '/register'];
|
|
|
|
function isPublicPath(pathname: string): boolean {
|
|
return (
|
|
publicExactPaths.includes(pathname) ||
|
|
publicPaths.some((path) => pathname.startsWith(path))
|
|
);
|
|
}
|
|
|
|
function stripLocale(pathname: string): string {
|
|
const localePattern = /^\/(vi|en)(\/|$)/;
|
|
return pathname.replace(localePattern, '/') || '/';
|
|
}
|
|
|
|
export function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl;
|
|
const strippedPath = stripLocale(pathname);
|
|
|
|
const hasAuthCookie = request.cookies.has('goodgo_authenticated');
|
|
|
|
if (!isPublicPath(strippedPath) && !hasAuthCookie) {
|
|
const loginUrl = new URL('/login', request.url);
|
|
loginUrl.searchParams.set('redirect', strippedPath);
|
|
return NextResponse.redirect(loginUrl);
|
|
}
|
|
|
|
const isAuthOnly = authOnlyPaths.some((path) =>
|
|
strippedPath.startsWith(path),
|
|
);
|
|
if (isAuthOnly && hasAuthCookie) {
|
|
return NextResponse.redirect(new URL('/dashboard', request.url));
|
|
}
|
|
|
|
return intlMiddleware(request);
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ['/((?!api|_next/static|_next/image|favicon.ico|public).*)'],
|
|
};
|