mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-06 23:07:21 +08:00
fix: 校验会话对应账号当前状态
This commit is contained in:
@@ -62,8 +62,13 @@ describe('/api/user', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// withUser 包装器通过 prisma 查询用户,设置默认返回值
|
||||
mocks.mockPrismaUser.findUnique.mockResolvedValue(defaultDbUser);
|
||||
// withUser 按 session 中的不可变 ID(旧测试 session 没有 ID 时按邮箱)读取当前账号。
|
||||
mocks.mockPrismaUser.findUnique.mockImplementation(async (args: { where?: { email?: string } }) => {
|
||||
const email = args.where?.email;
|
||||
if (email === 'admin@localhost') return { ...defaultDbUser, email, role: 'admin' };
|
||||
if (email && email !== defaultDbUser.email) return { ...defaultDbUser, email };
|
||||
return defaultDbUser;
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/user', () => {
|
||||
|
||||
@@ -71,6 +71,7 @@ const existingUser = {
|
||||
email: 'user@example.com',
|
||||
name: 'Test User',
|
||||
role: 'user',
|
||||
isActive: true,
|
||||
};
|
||||
|
||||
const adminUser = {
|
||||
@@ -78,6 +79,7 @@ const adminUser = {
|
||||
email: 'admin@localhost',
|
||||
name: 'Admin',
|
||||
role: 'admin',
|
||||
isActive: true,
|
||||
};
|
||||
|
||||
describe('withUser', () => {
|
||||
@@ -110,6 +112,17 @@ describe('withUser', () => {
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('数据库中已停用的账号不能继续使用已有会话', async () => {
|
||||
mocks.getServerSession.mockResolvedValue(loggedInSession);
|
||||
mocks.userFindUnique.mockResolvedValue({ ...existingUser, isActive: false });
|
||||
const handler = vi.fn();
|
||||
|
||||
const response = await withUser(handler)(new Request('http://localhost/api/test'));
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('已登录用户正常执行 handler 并传入 user 与 session', async () => {
|
||||
mocks.getServerSession.mockResolvedValue(loggedInSession);
|
||||
mocks.userFindUnique.mockResolvedValue(existingUser);
|
||||
@@ -200,9 +213,7 @@ describe('withAdmin', () => {
|
||||
expect(ctx.session).toEqual(adminSession);
|
||||
});
|
||||
|
||||
it('管理员判定与 isAdmin 一致:session.user.role === admin', async () => {
|
||||
// session 中 role 为 admin,但数据库中 role 为 user(数据不一致的边缘场景)
|
||||
// 按 session 判定(与现有 requireAdmin 一致)
|
||||
it('数据库已降权时,旧的管理员 session 不能继续访问管理接口', async () => {
|
||||
mocks.getServerSession.mockResolvedValue(adminSession);
|
||||
mocks.userFindUnique.mockResolvedValue({ ...adminUser, role: 'user' });
|
||||
const handler = vi.fn().mockResolvedValue(new Response('ok', { status: 200 }));
|
||||
@@ -210,8 +221,19 @@ describe('withAdmin', () => {
|
||||
|
||||
const response = await wrapped(new Request('http://localhost/api/admin/test'));
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(handler).toHaveBeenCalledTimes(1);
|
||||
expect(response.status).toBe(403);
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('数据库中已停用的管理员不能继续访问管理接口', async () => {
|
||||
mocks.getServerSession.mockResolvedValue(adminSession);
|
||||
mocks.userFindUnique.mockResolvedValue({ ...adminUser, isActive: false });
|
||||
const handler = vi.fn();
|
||||
|
||||
const response = await withAdmin(handler)(new Request('http://localhost/api/admin/test'));
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -15,6 +15,11 @@ vi.mock('@/lib/logger', () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
const { userFindUnique } = vi.hoisted(() => ({ userFindUnique: vi.fn() }));
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
prisma: { user: { findUnique: userFindUnique } },
|
||||
}));
|
||||
|
||||
import { proxy } from '@/proxy';
|
||||
import { getToken } from 'next-auth/jwt';
|
||||
import type { JWT } from 'next-auth/jwt';
|
||||
@@ -22,6 +27,11 @@ import type { JWT } from 'next-auth/jwt';
|
||||
describe('proxy', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
userFindUnique.mockImplementation(({ where }: { where: { id?: string } }) => Promise.resolve(
|
||||
where.id === 'admin-1'
|
||||
? { isActive: true, role: 'admin' }
|
||||
: { isActive: true, role: 'user' },
|
||||
));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -85,7 +95,7 @@ describe('proxy', () => {
|
||||
|
||||
describe('已认证用户', () => {
|
||||
const mockToken = {
|
||||
sub: 'user-123',
|
||||
id: 'user-123',
|
||||
email: 'test@example.com',
|
||||
name: 'Test User',
|
||||
};
|
||||
@@ -162,6 +172,28 @@ describe('proxy', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('数据库账号状态', () => {
|
||||
it('数据库停用账号时,即使 token 仍存在也跳转登录页', async () => {
|
||||
vi.mocked(getToken).mockResolvedValue({ id: 'user-123', role: 'user' } as unknown as JWT);
|
||||
userFindUnique.mockResolvedValue({ isActive: false, role: 'user' });
|
||||
|
||||
const response = await proxy(new NextRequest('http://localhost:3000/notebooks'));
|
||||
|
||||
expect(response?.status).toBe(307);
|
||||
expect(response?.headers.get('location')).toContain('/login');
|
||||
});
|
||||
|
||||
it('数据库已降权时,旧管理员 token 不能访问管理页', async () => {
|
||||
vi.mocked(getToken).mockResolvedValue({ id: 'admin-1', role: 'admin' } as unknown as JWT);
|
||||
userFindUnique.mockResolvedValue({ isActive: true, role: 'user' });
|
||||
|
||||
const response = await proxy(new NextRequest('http://localhost:3000/admin'));
|
||||
|
||||
expect(response?.status).toBe(307);
|
||||
expect(response?.headers.get('location')).toContain('/login?callbackUrl=%2Fadmin');
|
||||
});
|
||||
});
|
||||
|
||||
describe('错误处理', () => {
|
||||
it('Token 验证失败时按未登录处理,跳到登录页而不是放行', async () => {
|
||||
vi.mocked(getToken).mockRejectedValue(new Error('Token validation failed'));
|
||||
|
||||
@@ -62,25 +62,44 @@ async function resolveUser(): Promise<{ user: User; session: Session } | { error
|
||||
if (!session?.user?.email) {
|
||||
return { error: unauthorized("Authentication required") };
|
||||
}
|
||||
const adminUser = await prisma.user.findUnique({ where: { email: session.user.email } });
|
||||
if (!adminUser) {
|
||||
// JWT 会话可能在账号被停用或降权后仍然存在一段时间,不能只相信 token 中的邮箱和角色。
|
||||
// 新会话优先按不可变的用户 ID 查找;旧会话没有 ID 时再回退到邮箱。
|
||||
const principal = session.user.id
|
||||
? await prisma.user.findUnique({ where: { id: session.user.id } })
|
||||
: await prisma.user.findUnique({ where: { email: session.user.email } });
|
||||
if (!principal || principal.isActive === false) {
|
||||
return { error: unauthorized("Authentication required") };
|
||||
}
|
||||
|
||||
// 管理员角色以数据库当前值为准,避免旧 JWT 在降权后继续获得管理员权限。
|
||||
const principalSession = principal.id === session.user.id
|
||||
&& principal.email === session.user.email
|
||||
&& principal.role === session.user.role
|
||||
? session
|
||||
: {
|
||||
...session,
|
||||
user: {
|
||||
...session.user,
|
||||
id: principal.id,
|
||||
email: principal.email,
|
||||
role: principal.role,
|
||||
},
|
||||
};
|
||||
|
||||
// 管理员「以某用户身份查看」:普通接口按目标用户执行,鉴权仍以管理员会话为准
|
||||
if (session.user.role === "admin") {
|
||||
if (principal.role === "admin") {
|
||||
try {
|
||||
const targetId = (await cookies()).get(ADMIN_VIEW_AS_COOKIE)?.value;
|
||||
if (targetId && targetId !== adminUser.id) {
|
||||
if (targetId && targetId !== principal.id) {
|
||||
const target = await prisma.user.findUnique({ where: { id: targetId } });
|
||||
if (target) return { user: target, session };
|
||||
if (target) return { user: target, session: principalSession };
|
||||
}
|
||||
} catch {
|
||||
// 非请求上下文(如直接调用路由的测试)没有 cookie 存储,按管理员本人处理
|
||||
}
|
||||
}
|
||||
|
||||
return { user: adminUser, session };
|
||||
return { user: principal, session: principalSession };
|
||||
}
|
||||
|
||||
export interface AdminRouteOptions {
|
||||
|
||||
11
src/proxy.ts
11
src/proxy.ts
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
|
||||
import { getToken } from "next-auth/jwt";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const logger = createLogger('proxy');
|
||||
|
||||
@@ -24,7 +25,13 @@ export async function proxy(req: NextRequest) {
|
||||
cookieName: "next-auth.session-token", // Explicitly look for the standardized cookie
|
||||
});
|
||||
|
||||
const isAuth = !!token;
|
||||
// 页面代理不能只相信 JWT:管理员停用账号后,旧 token 仍可能存在。
|
||||
// API 层也会再次校验,这里提前阻止旧会话继续访问受保护页面。
|
||||
const currentUser = token?.id
|
||||
? await prisma.user.findUnique({ where: { id: token.id }, select: { isActive: true, role: true } })
|
||||
: null;
|
||||
const isAuth = !!token?.id && currentUser?.isActive !== false && currentUser !== null;
|
||||
const currentRole = currentUser?.role;
|
||||
// /initialize:全新安装时用一次性初始化链接创建管理员,未登录也要能打开
|
||||
const isAuthPage = ["/login", "/register", "/initialize"].some((prefix) => req.nextUrl.pathname.startsWith(prefix));
|
||||
const isAdminPage = req.nextUrl.pathname.startsWith("/admin");
|
||||
@@ -65,7 +72,7 @@ export async function proxy(req: NextRequest) {
|
||||
}
|
||||
|
||||
// Admin route protection: only allow users with admin role
|
||||
if (isAdminPage && token?.role !== "admin") {
|
||||
if (isAdminPage && currentRole !== "admin") {
|
||||
logger.warn({ userId: token?.id, path: req.nextUrl.pathname }, 'Non-admin user attempting to access admin area');
|
||||
return NextResponse.redirect(new URL("/", req.url));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user