49 lines
1.7 KiB
TypeScript
49 lines
1.7 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 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'映射到正确的物理路径
|