Files
soroushasadi/middleware.ts
T
soroush.asadi add78d8460
ci / build (push) Failing after 23s
deploy / deploy (push) Failing after 10m12s
first commit
2026-05-31 12:47:02 +03:30

40 lines
1.2 KiB
TypeScript

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { SESSION_COOKIE, verifySession } from '@/lib/auth/session';
/**
* Gate everything under /admin and /api/admin behind the session cookie.
* The login page and login endpoint stay public so a fresh visitor can sign in.
*/
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const isLoginPage = pathname === '/admin/login';
const isLoginApi = pathname === '/api/admin/login';
const token = req.cookies.get(SESSION_COOKIE)?.value;
const authed = await verifySession(token);
// Public auth endpoints.
if (isLoginApi) return NextResponse.next();
if (isLoginPage) {
return authed
? NextResponse.redirect(new URL('/admin', req.url))
: NextResponse.next();
}
if (!authed) {
if (pathname.startsWith('/api/admin')) {
return NextResponse.json({ error: 'unauthorized' }, { status: 401 });
}
const url = new URL('/admin/login', req.url);
if (pathname !== '/admin') url.searchParams.set('from', pathname);
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ['/admin/:path*', '/api/admin/:path*'],
};