49 lines
1.6 KiB
TypeScript
49 lines
1.6 KiB
TypeScript
|
|
import { NextResponse } from 'next/server';
|
|||
|
|
import type { NextRequest } from 'next/server';
|
|||
|
|
import { getToken } from 'next-auth/jwt';
|
|||
|
|
|
|||
|
|
// 更直接的中间件实现
|
|||
|
|
export async function middleware(request: NextRequest) {
|
|||
|
|
const { pathname } = request.nextUrl;
|
|||
|
|
|
|||
|
|
// 定义需要检查登录状态的页面
|
|||
|
|
const isRootPage = pathname === '/';
|
|||
|
|
const isLoginPage = pathname === '/login';
|
|||
|
|
const isRegisterPage = pathname === '/register';
|
|||
|
|
|
|||
|
|
// 只对这三个页面进行检查
|
|||
|
|
const shouldCheckAuth = isRootPage || isLoginPage || isRegisterPage;
|
|||
|
|
|
|||
|
|
if (!shouldCheckAuth) {
|
|||
|
|
return NextResponse.next();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
// 使用cookie存储的next-auth会话信息来检查登录状态
|
|||
|
|
// 从请求头中提取cookie信息
|
|||
|
|
const authCookie = request.cookies.get('next-auth.session-token') ||
|
|||
|
|
request.cookies.get('__Secure-next-auth.session-token');
|
|||
|
|
|
|||
|
|
// 如果存在auth cookie,认为用户已登录,重定向到用户主页
|
|||
|
|
if (authCookie) {
|
|||
|
|
const url = request.nextUrl.clone();
|
|||
|
|
url.pathname = '/user-home';
|
|||
|
|
return NextResponse.redirect(url);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 不存在auth cookie,允许访问原页面
|
|||
|
|
return NextResponse.next();
|
|||
|
|
} catch (error) {
|
|||
|
|
console.error('登录状态检查错误:', error);
|
|||
|
|
// 发生错误时,为了安全起见,默认允许访问原页面
|
|||
|
|
return NextResponse.next();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 配置中间件适用的路径
|
|||
|
|
export const config = {
|
|||
|
|
// 直接匹配三个目标页面
|
|||
|
|
matcher: ['/', '/login', '/register'],
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
// 重要提示:对于(auth)路由组中的页面,Next.js路由系统会自动将'/login'和'/register'映射到正确的物理路径
|