36 lines
1.0 KiB
TypeScript
36 lines
1.0 KiB
TypeScript
|
|
import { NextResponse, type NextRequest } from 'next/server';
|
|||
|
|
|
|||
|
|
const TOKEN_COOKIE = process.env.NEXT_PUBLIC_TOKEN_KEY ?? 'admin_token';
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 后台路由鉴权中间件(Edge 运行时)
|
|||
|
|
* - /admin/login 放行
|
|||
|
|
* - 其他 /admin 路径无 token cookie → 跳登录
|
|||
|
|
*
|
|||
|
|
* 说明:token 真值由前端 adminStore 同步写入 cookie,
|
|||
|
|
* 这里仅做"是否已登录"的初步判断,最终有效性由后端 JWT 校验。
|
|||
|
|
*/
|
|||
|
|
export function middleware(req: NextRequest): NextResponse {
|
|||
|
|
const { pathname, search } = req.nextUrl;
|
|||
|
|
|
|||
|
|
if (!pathname.startsWith('/admin')) {
|
|||
|
|
return NextResponse.next();
|
|||
|
|
}
|
|||
|
|
if (pathname === '/admin/login') {
|
|||
|
|
return NextResponse.next();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const token = req.cookies.get(TOKEN_COOKIE)?.value;
|
|||
|
|
if (!token) {
|
|||
|
|
const url = req.nextUrl.clone();
|
|||
|
|
url.pathname = '/admin/login';
|
|||
|
|
url.searchParams.set('redirect', encodeURIComponent(pathname + search));
|
|||
|
|
return NextResponse.redirect(url);
|
|||
|
|
}
|
|||
|
|
return NextResponse.next();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export const config = {
|
|||
|
|
matcher: ['/admin/:path*'],
|
|||
|
|
};
|