Files
frontend/middleware.ts
Mikuisnotavailable 957e7d9a15 我忘了改啥了
2025-10-26 00:19:23 +08:00

49 lines
1.7 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 shouldCheckAuth = isRootPage || isLoginPage;
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'],
};
// 重要提示:对于(auth)路由组中的页面Next.js路由系统会自动将'/login'和'/register'映射到正确的物理路径