63 lines
1.8 KiB
TypeScript
63 lines
1.8 KiB
TypeScript
import { NextResponse, NextRequest } from 'next/server';
|
|
import { cookies } from 'next/headers'
|
|
import { decrypt } from '@/app/actions/session';
|
|
import createIntlMiddleware from 'next-intl/middleware'
|
|
import { routing } from '@/i18n/routing'
|
|
|
|
const protectedRoutes = ['/pages'];
|
|
const publicRoutes = ['/login', '/register', '/'];
|
|
const intlMiddleware = createIntlMiddleware(routing);
|
|
|
|
export default async function proxy(request: NextRequest) {
|
|
const path = request.nextUrl.pathname;
|
|
|
|
if (
|
|
path.startsWith('/_next') ||
|
|
path.includes('/api/') ||
|
|
path.includes('.')
|
|
) {
|
|
return NextResponse.next()
|
|
}
|
|
|
|
const intlResponse = intlMiddleware(request);
|
|
|
|
if (intlResponse) {
|
|
const localizedPath = intlResponse.headers.get('x-middleware-request') ||
|
|
intlResponse.headers.get('x-middleware-next') ||
|
|
path
|
|
|
|
const isProtectedRoute = protectedRoutes.some(route =>
|
|
localizedPath.includes(route) ||
|
|
path.includes(route)
|
|
)
|
|
|
|
const isPublicRoute = publicRoutes.some(route =>
|
|
localizedPath === `/${request.nextUrl.locale}${route}` ||
|
|
localizedPath === route
|
|
)
|
|
|
|
|
|
const cookie = (await cookies()).get('session')?.value;
|
|
const session = await decrypt(cookie);
|
|
|
|
if (isProtectedRoute && !session?.token) {
|
|
const loginUrl = new URL('/login', request.nextUrl)
|
|
loginUrl.searchParams.set('locale', request.nextUrl.locale || 'ru')
|
|
return NextResponse.redirect(loginUrl)
|
|
}
|
|
|
|
if (path === '/en' || path === '/ru' || localizedPath === `/${request.nextUrl.locale}`) {
|
|
const dashboardUrl = new URL('/pages/dashboard', request.nextUrl)
|
|
dashboardUrl.searchParams.set('locale', request.nextUrl.locale || 'ru')
|
|
return NextResponse.redirect(dashboardUrl)
|
|
}
|
|
|
|
return intlResponse
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)']
|
|
}; |