data-permission.integration.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import { IntegrationTestDatabase, setupIntegrationDatabaseHooksWithEntities } from '@d8d/shared-test-util';
  4. import { JWTUtil } from '@d8d/shared-utils';
  5. import { z } from '@hono/zod-openapi';
  6. import { createCrudRoutes } from '../../src/routes/generic-crud.routes';
  7. import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
  8. // 测试用户实体
  9. @Entity()
  10. class TestUser {
  11. @PrimaryGeneratedColumn()
  12. id!: number;
  13. @Column('varchar')
  14. username!: string;
  15. @Column('varchar')
  16. password!: string;
  17. @Column('varchar')
  18. nickname!: string;
  19. @Column('varchar')
  20. registrationSource!: string;
  21. }
  22. // 测试实体类
  23. @Entity()
  24. class TestEntity {
  25. @PrimaryGeneratedColumn()
  26. id!: number;
  27. @Column('varchar')
  28. name!: string;
  29. @Column('int')
  30. userId!: number;
  31. @Column('int', { nullable: true })
  32. createdBy?: number;
  33. @Column('int', { nullable: true })
  34. updatedBy?: number;
  35. }
  36. // 定义测试实体的Schema
  37. const createTestSchema = z.object({
  38. name: z.string().min(1, '名称不能为空'),
  39. userId: z.number().optional()
  40. });
  41. const updateTestSchema = z.object({
  42. name: z.string().min(1, '名称不能为空').optional()
  43. });
  44. const getTestSchema = z.object({
  45. id: z.number(),
  46. name: z.string(),
  47. userId: z.number(),
  48. createdBy: z.number().nullable().optional(),
  49. updatedBy: z.number().nullable().optional()
  50. });
  51. const listTestSchema = z.object({
  52. id: z.number(),
  53. name: z.string(),
  54. userId: z.number(),
  55. createdBy: z.number().nullable().optional(),
  56. updatedBy: z.number().nullable().optional()
  57. });
  58. // 设置集成测试钩子
  59. setupIntegrationDatabaseHooksWithEntities([TestUser, TestEntity])
  60. describe('共享CRUD数据权限控制集成测试', () => {
  61. let client: any;
  62. let testToken1: string;
  63. let testToken2: string;
  64. let testUser1: TestUser;
  65. let testUser2: TestUser;
  66. let mockAuthMiddleware: any;
  67. beforeEach(async () => {
  68. // 获取数据源
  69. const dataSource = await IntegrationTestDatabase.getDataSource();
  70. // 创建测试用户1
  71. const userRepository = dataSource.getRepository(TestUser);
  72. testUser1 = userRepository.create({
  73. username: `test_user_1_${Date.now()}`,
  74. password: 'test_password',
  75. nickname: '测试用户1',
  76. registrationSource: 'web'
  77. });
  78. await userRepository.save(testUser1);
  79. // 创建测试用户2
  80. testUser2 = userRepository.create({
  81. username: `test_user_2_${Date.now()}`,
  82. password: 'test_password',
  83. nickname: '测试用户2',
  84. registrationSource: 'web'
  85. });
  86. await userRepository.save(testUser2);
  87. // 生成测试用户的token
  88. testToken1 = JWTUtil.generateToken({
  89. id: testUser1.id,
  90. username: testUser1.username,
  91. roles: [{name:'user'}]
  92. });
  93. testToken2 = JWTUtil.generateToken({
  94. id: testUser2.id,
  95. username: testUser2.username,
  96. roles: [{name:'user'}]
  97. });
  98. // 创建模拟认证中间件
  99. const mockAuthMiddleware = async (c: any, next: any) => {
  100. const authHeader = c.req.header('Authorization');
  101. if (authHeader && authHeader.startsWith('Bearer ')) {
  102. const token = authHeader.substring(7);
  103. try {
  104. // 简单模拟用户解析
  105. if (token === testToken1) {
  106. c.set('user', { id: testUser1.id, username: testUser1.username });
  107. } else if (token === testToken2) {
  108. c.set('user', { id: testUser2.id, username: testUser2.username });
  109. }
  110. } catch (error) {
  111. // token解析失败
  112. }
  113. }
  114. await next();
  115. };
  116. // 创建测试路由 - 启用数据权限控制
  117. const testRoutes = createCrudRoutes({
  118. entity: TestEntity,
  119. createSchema: createTestSchema,
  120. updateSchema: updateTestSchema,
  121. getSchema: getTestSchema,
  122. listSchema: listTestSchema,
  123. middleware: [mockAuthMiddleware],
  124. dataPermission: {
  125. enabled: true,
  126. userIdField: 'userId'
  127. }
  128. });
  129. client = testClient(testRoutes);
  130. });
  131. describe('GET / - 列表查询权限过滤', () => {
  132. it('应该只返回当前用户的数据', async () => {
  133. // 创建测试数据
  134. const dataSource = await IntegrationTestDatabase.getDataSource();
  135. const testRepository = dataSource.getRepository(TestEntity);
  136. // 为用户1创建数据
  137. const user1Data1 = testRepository.create({
  138. name: '用户1的数据1',
  139. userId: testUser1.id
  140. });
  141. await testRepository.save(user1Data1);
  142. const user1Data2 = testRepository.create({
  143. name: '用户1的数据2',
  144. userId: testUser1.id
  145. });
  146. await testRepository.save(user1Data2);
  147. // 为用户2创建数据
  148. const user2Data = testRepository.create({
  149. name: '用户2的数据',
  150. userId: testUser2.id
  151. });
  152. await testRepository.save(user2Data);
  153. // 用户1查询列表
  154. const response = await client.index.$get({
  155. query: {
  156. page: 1,
  157. pageSize: 10
  158. }
  159. }, {
  160. headers: {
  161. 'Authorization': `Bearer ${testToken1}`
  162. }
  163. });
  164. console.debug('列表查询响应状态:', response.status);
  165. if (response.status !== 200) {
  166. const errorData = await response.json();
  167. console.debug('列表查询错误信息:', errorData);
  168. }
  169. expect(response.status).toBe(200);
  170. if (response.status === 200) {
  171. const data = await response.json();
  172. expect(data).toHaveProperty('data');
  173. expect(Array.isArray(data.data)).toBe(true);
  174. expect(data.data).toHaveLength(2); // 应该只返回用户1的2条数据
  175. // 验证所有返回的数据都属于用户1
  176. data.data.forEach((item: any) => {
  177. expect(item.userId).toBe(testUser1.id);
  178. });
  179. }
  180. });
  181. it('应该拒绝未认证用户的访问', async () => {
  182. const response = await client.index.$get({
  183. query: {
  184. page: 1,
  185. pageSize: 10
  186. }
  187. });
  188. expect(response.status).toBe(401);
  189. });
  190. });
  191. describe('POST / - 创建操作权限验证', () => {
  192. it('应该成功创建属于当前用户的数据', async () => {
  193. const createData = {
  194. name: '测试创建数据',
  195. userId: testUser1.id // 用户ID与当前用户匹配
  196. };
  197. const response = await client.index.$post({
  198. json: createData
  199. }, {
  200. headers: {
  201. 'Authorization': `Bearer ${testToken1}`
  202. }
  203. });
  204. console.debug('创建数据响应状态:', response.status);
  205. expect(response.status).toBe(201);
  206. if (response.status === 201) {
  207. const data = await response.json();
  208. expect(data).toHaveProperty('id');
  209. expect(data.name).toBe(createData.name);
  210. expect(data.userId).toBe(testUser1.id);
  211. }
  212. });
  213. it('应该拒绝创建不属于当前用户的数据', async () => {
  214. const createData = {
  215. name: '测试创建数据',
  216. userId: testUser2.id // 用户ID与当前用户不匹配
  217. };
  218. const response = await client.index.$post({
  219. json: createData
  220. }, {
  221. headers: {
  222. 'Authorization': `Bearer ${testToken1}`
  223. }
  224. });
  225. console.debug('创建无权数据响应状态:', response.status);
  226. expect(response.status).toBe(500); // 权限验证失败会抛出错误
  227. if (response.status === 500) {
  228. const data = await response.json();
  229. expect(data.message).toContain('无权');
  230. }
  231. });
  232. });
  233. describe('GET /:id - 获取详情权限验证', () => {
  234. it('应该成功获取属于当前用户的数据详情', async () => {
  235. // 先创建测试数据
  236. const dataSource = await IntegrationTestDatabase.getDataSource();
  237. const testRepository = dataSource.getRepository(TestEntity);
  238. const testData = testRepository.create({
  239. name: '测试数据详情',
  240. userId: testUser1.id
  241. });
  242. await testRepository.save(testData);
  243. const response = await client[':id'].$get({
  244. param: { id: testData.id }
  245. }, {
  246. headers: {
  247. 'Authorization': `Bearer ${testToken1}`
  248. }
  249. });
  250. console.debug('获取详情响应状态:', response.status);
  251. expect(response.status).toBe(200);
  252. if (response.status === 200) {
  253. const data = await response.json();
  254. expect(data.id).toBe(testData.id);
  255. expect(data.name).toBe(testData.name);
  256. expect(data.userId).toBe(testUser1.id);
  257. }
  258. });
  259. it('应该拒绝获取不属于当前用户的数据详情', async () => {
  260. // 先创建属于用户2的数据
  261. const dataSource = await IntegrationTestDatabase.getDataSource();
  262. const testRepository = dataSource.getRepository(TestEntity);
  263. const testData = testRepository.create({
  264. name: '用户2的数据',
  265. userId: testUser2.id
  266. });
  267. await testRepository.save(testData);
  268. // 用户1尝试获取用户2的数据
  269. const response = await client[':id'].$get({
  270. param: { id: testData.id }
  271. }, {
  272. headers: {
  273. 'Authorization': `Bearer ${testToken1}`
  274. }
  275. });
  276. console.debug('获取无权详情响应状态:', response.status);
  277. expect(response.status).toBe(404); // 权限验证失败返回404
  278. });
  279. it('应该处理不存在的资源', async () => {
  280. const response = await client[':id'].$get({
  281. param: { id: 999999 }
  282. }, {
  283. headers: {
  284. 'Authorization': `Bearer ${testToken1}`
  285. }
  286. });
  287. expect(response.status).toBe(404);
  288. });
  289. });
  290. describe('PUT /:id - 更新操作权限验证', () => {
  291. it('应该成功更新属于当前用户的数据', async () => {
  292. // 先创建测试数据
  293. const dataSource = await IntegrationTestDatabase.getDataSource();
  294. const testRepository = dataSource.getRepository(TestEntity);
  295. const testData = testRepository.create({
  296. name: '原始数据',
  297. userId: testUser1.id
  298. });
  299. await testRepository.save(testData);
  300. const updateData = {
  301. name: '更新后的数据'
  302. };
  303. const response = await client[':id'].$put({
  304. param: { id: testData.id },
  305. json: updateData
  306. }, {
  307. headers: {
  308. 'Authorization': `Bearer ${testToken1}`
  309. }
  310. });
  311. console.debug('更新数据响应状态:', response.status);
  312. expect(response.status).toBe(200);
  313. if (response.status === 200) {
  314. const data = await response.json();
  315. expect(data.name).toBe(updateData.name);
  316. expect(data.userId).toBe(testUser1.id);
  317. }
  318. });
  319. it('应该拒绝更新不属于当前用户的数据', async () => {
  320. // 先创建属于用户2的数据
  321. const dataSource = await IntegrationTestDatabase.getDataSource();
  322. const testRepository = dataSource.getRepository(TestEntity);
  323. const testData = testRepository.create({
  324. name: '用户2的数据',
  325. userId: testUser2.id
  326. });
  327. await testRepository.save(testData);
  328. const updateData = {
  329. name: '尝试更新的数据'
  330. };
  331. // 用户1尝试更新用户2的数据
  332. const response = await client[':id'].$put({
  333. param: { id: testData.id },
  334. json: updateData
  335. }, {
  336. headers: {
  337. 'Authorization': `Bearer ${testToken1}`
  338. }
  339. });
  340. console.debug('更新无权数据响应状态:', response.status);
  341. expect(response.status).toBe(500); // 权限验证失败会抛出错误
  342. if (response.status === 500) {
  343. const data = await response.json();
  344. expect(data.message).toContain('无权');
  345. }
  346. });
  347. });
  348. describe('DELETE /:id - 删除操作权限验证', () => {
  349. it('应该成功删除属于当前用户的数据', async () => {
  350. // 先创建测试数据
  351. const dataSource = await IntegrationTestDatabase.getDataSource();
  352. const testRepository = dataSource.getRepository(TestEntity);
  353. const testData = testRepository.create({
  354. name: '待删除数据',
  355. userId: testUser1.id
  356. });
  357. await testRepository.save(testData);
  358. const response = await client[':id'].$delete({
  359. param: { id: testData.id }
  360. }, {
  361. headers: {
  362. 'Authorization': `Bearer ${testToken1}`
  363. }
  364. });
  365. console.debug('删除数据响应状态:', response.status);
  366. expect(response.status).toBe(204);
  367. // 验证数据确实被删除
  368. const deletedData = await testRepository.findOne({
  369. where: { id: testData.id }
  370. });
  371. expect(deletedData).toBeNull();
  372. });
  373. it('应该拒绝删除不属于当前用户的数据', async () => {
  374. // 先创建属于用户2的数据
  375. const dataSource = await IntegrationTestDatabase.getDataSource();
  376. const testRepository = dataSource.getRepository(TestEntity);
  377. const testData = testRepository.create({
  378. name: '用户2的数据',
  379. userId: testUser2.id
  380. });
  381. await testRepository.save(testData);
  382. // 用户1尝试删除用户2的数据
  383. const response = await client[':id'].$delete({
  384. param: { id: testData.id }
  385. }, {
  386. headers: {
  387. 'Authorization': `Bearer ${testToken1}`
  388. }
  389. });
  390. console.debug('删除无权数据响应状态:', response.status);
  391. expect(response.status).toBe(500); // 权限验证失败会抛出错误
  392. if (response.status === 500) {
  393. const data = await response.json();
  394. expect(data.message).toContain('无权');
  395. }
  396. // 验证数据没有被删除
  397. const existingData = await testRepository.findOne({
  398. where: { id: testData.id }
  399. });
  400. expect(existingData).not.toBeNull();
  401. });
  402. });
  403. describe('禁用数据权限控制的情况', () => {
  404. it('当数据权限控制禁用时应该允许跨用户访问', async () => {
  405. // 创建禁用数据权限控制的路由
  406. const noPermissionRoutes = createCrudRoutes({
  407. entity: TestEntity,
  408. createSchema: createTestSchema,
  409. updateSchema: updateTestSchema,
  410. getSchema: getTestSchema,
  411. listSchema: listTestSchema,
  412. middleware: [mockAuthMiddleware],
  413. dataPermission: {
  414. enabled: false, // 禁用权限控制
  415. userIdField: 'userId'
  416. }
  417. });
  418. const noPermissionClient = testClient(noPermissionRoutes);
  419. // 创建属于用户2的数据
  420. const dataSource = await IntegrationTestDatabase.getDataSource();
  421. const testRepository = dataSource.getRepository(TestEntity);
  422. const testData = testRepository.create({
  423. name: '用户2的数据',
  424. userId: testUser2.id
  425. });
  426. await testRepository.save(testData);
  427. // 用户1应该能够访问用户2的数据(权限控制已禁用)
  428. const response = await noPermissionClient[':id'].$get({
  429. param: { id: testData.id }
  430. }, {
  431. headers: {
  432. 'Authorization': `Bearer ${testToken1}`
  433. }
  434. });
  435. console.debug('禁用权限控制时的响应状态:', response.status);
  436. expect(response.status).toBe(200);
  437. if (response.status === 200) {
  438. const data = await response.json();
  439. expect(data.id).toBe(testData.id);
  440. expect(data.userId).toBe(testUser2.id);
  441. }
  442. });
  443. });
  444. });