first commit
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
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*'],
|
||||
};
|
||||
Reference in New Issue
Block a user