feat: implement simple cookie-based authentication middleware
This commit is contained in:
28
middleware.ts
Normal file
28
middleware.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
// middleware.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
import { COOKIE_NAME, COOKIE_MAX_AGE } from './lib/constants';
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
|
||||
// 登录页面不需要认证
|
||||
if (pathname === '/login') {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
// 检查是否有认证 cookie
|
||||
const authCookie = request.cookies.get(COOKIE_NAME);
|
||||
|
||||
if (!authCookie || authCookie.value !== 'ok') {
|
||||
// 未认证,重定向到登录页
|
||||
const loginUrl = new URL('/login', request.url);
|
||||
return NextResponse.redirect(loginUrl);
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
|
||||
};
|
||||
Reference in New Issue
Block a user