next-windfonts/middleware.ts
bo.yu 8c2b422a37 feat(auth): 实现基于 NextAuth.js 的管理员认证系统
添加 NextAuth.js 依赖并配置认证模块
创建登录页面和管理后台会话保护中间件
更新 README 文档说明管理员认证功能
2025-09-08 16:45:57 +08:00

47 lines
1.4 KiB
TypeScript

/*
* Copyright (C) 2024 WindFonts Project
*
* This file is part of WindFonts.
*
* WindFonts is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WindFonts is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with WindFonts. If not, see <https://www.gnu.org/licenses/>.
*/
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
export default auth((req: NextRequest & { auth: any }) => {
const { pathname } = req.nextUrl;
// 保护 /admin 路由
if (pathname.startsWith('/admin')) {
if (!req.auth) {
// 未登录,重定向到登录页面
const loginUrl = new URL('/login', req.url);
loginUrl.searchParams.set('callbackUrl', pathname);
return NextResponse.redirect(loginUrl);
}
// 检查用户角色
if (req.auth.user?.role !== 'admin') {
// 非管理员,重定向到首页
return NextResponse.redirect(new URL('/', req.url));
}
}
return NextResponse.next();
});
export const config = {
matcher: ['/admin/:path*'],
};