data-permission.integration.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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().optional(),
  49. updatedBy: z.number().optional()
  50. });
  51. const listTestSchema = z.object({
  52. id: z.number(),
  53. name: z.string(),
  54. userId: z.number(),
  55. createdBy: z.number().optional(),
  56. updatedBy: z.number().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. beforeEach(async () => {
  67. // 获取数据源
  68. const dataSource = await IntegrationTestDatabase.getDataSource();
  69. // 创建测试用户1
  70. const userRepository = dataSource.getRepository(TestUser);
  71. testUser1 = userRepository.create({
  72. username: `test_user_1_${Date.now()}`,
  73. password: 'test_password',
  74. nickname: '测试用户1',
  75. registrationSource: 'web'
  76. });
  77. await userRepository.save(testUser1);
  78. // 创建测试用户2
  79. testUser2 = userRepository.create({
  80. username: `test_user_2_${Date.now()}`,
  81. password: 'test_password',
  82. nickname: '测试用户2',
  83. registrationSource: 'web'
  84. });
  85. await userRepository.save(testUser2);
  86. // 生成测试用户的token
  87. testToken1 = JWTUtil.generateToken({
  88. id: testUser1.id,
  89. username: testUser1.username,
  90. roles: [{name:'user'}]
  91. });
  92. testToken2 = JWTUtil.generateToken({
  93. id: testUser2.id,
  94. username: testUser2.username,
  95. roles: [{name:'user'}]
  96. });
  97. // 创建测试路由 - 启用数据权限控制
  98. const testRoutes = createCrudRoutes({
  99. entity: TestEntity,
  100. createSchema: createTestSchema,
  101. updateSchema: updateTestSchema,
  102. getSchema: getTestSchema,
  103. listSchema: listTestSchema,
  104. dataPermission: {
  105. enabled: true,
  106. userIdField: 'userId'
  107. }
  108. });
  109. client = testClient(testRoutes);
  110. });
  111. describe('GET / - 列表查询权限过滤', () => {
  112. it('应该只返回当前用户的数据', async () => {
  113. // 创建测试数据
  114. const dataSource = await IntegrationTestDatabase.getDataSource();
  115. const testRepository = dataSource.getRepository(TestEntity);
  116. // 为用户1创建数据
  117. const user1Data1 = testRepository.create({
  118. name: '用户1的数据1',
  119. userId: testUser1.id
  120. });
  121. await testRepository.save(user1Data1);
  122. const user1Data2 = testRepository.create({
  123. name: '用户1的数据2',
  124. userId: testUser1.id
  125. });
  126. await testRepository.save(user1Data2);
  127. // 为用户2创建数据
  128. const user2Data = testRepository.create({
  129. name: '用户2的数据',
  130. userId: testUser2.id
  131. });
  132. await testRepository.save(user2Data);
  133. // 用户1查询列表
  134. const response = await client.index.$get({
  135. query: {}
  136. }, {
  137. headers: {
  138. 'Authorization': `Bearer ${testToken1}`
  139. }
  140. });
  141. console.debug('列表查询响应状态:', response.status);
  142. expect(response.status).toBe(200);
  143. if (response.status === 200) {
  144. const data = await response.json();
  145. expect(data).toHaveProperty('data');
  146. expect(Array.isArray(data.data)).toBe(true);
  147. expect(data.data).toHaveLength(2); // 应该只返回用户1的2条数据
  148. // 验证所有返回的数据都属于用户1
  149. data.data.forEach((item: any) => {
  150. expect(item.userId).toBe(testUser1.id);
  151. });
  152. }
  153. });
  154. it('应该拒绝未认证用户的访问', async () => {
  155. const response = await client.index.$get({
  156. query: {}
  157. });
  158. expect(response.status).toBe(401);
  159. });
  160. });
  161. describe('POST / - 创建操作权限验证', () => {
  162. it('应该成功创建属于当前用户的数据', async () => {
  163. const createData = {
  164. name: '测试创建数据',
  165. userId: testUser1.id // 用户ID与当前用户匹配
  166. };
  167. const response = await client.index.$post({
  168. json: createData
  169. }, {
  170. headers: {
  171. 'Authorization': `Bearer ${testToken1}`
  172. }
  173. });
  174. console.debug('创建数据响应状态:', response.status);
  175. expect(response.status).toBe(201);
  176. if (response.status === 201) {
  177. const data = await response.json();
  178. expect(data).toHaveProperty('id');
  179. expect(data.name).toBe(createData.name);
  180. expect(data.userId).toBe(testUser1.id);
  181. }
  182. });
  183. it('应该拒绝创建不属于当前用户的数据', async () => {
  184. const createData = {
  185. name: '测试创建数据',
  186. userId: testUser2.id // 用户ID与当前用户不匹配
  187. };
  188. const response = await client.index.$post({
  189. json: createData
  190. }, {
  191. headers: {
  192. 'Authorization': `Bearer ${testToken1}`
  193. }
  194. });
  195. console.debug('创建无权数据响应状态:', response.status);
  196. expect(response.status).toBe(500); // 权限验证失败会抛出错误
  197. if (response.status === 500) {
  198. const data = await response.json();
  199. expect(data.message).toContain('无权');
  200. }
  201. });
  202. });
  203. describe('GET /:id - 获取详情权限验证', () => {
  204. it('应该成功获取属于当前用户的数据详情', async () => {
  205. // 先创建测试数据
  206. const dataSource = await IntegrationTestDatabase.getDataSource();
  207. const testRepository = dataSource.getRepository(TestEntity);
  208. const testData = testRepository.create({
  209. name: '测试数据详情',
  210. userId: testUser1.id
  211. });
  212. await testRepository.save(testData);
  213. const response = await client[':id'].$get({
  214. param: { id: testData.id }
  215. }, {
  216. headers: {
  217. 'Authorization': `Bearer ${testToken1}`
  218. }
  219. });
  220. console.debug('获取详情响应状态:', response.status);
  221. expect(response.status).toBe(200);
  222. if (response.status === 200) {
  223. const data = await response.json();
  224. expect(data.id).toBe(testData.id);
  225. expect(data.name).toBe(testData.name);
  226. expect(data.userId).toBe(testUser1.id);
  227. }
  228. });
  229. it('应该拒绝获取不属于当前用户的数据详情', async () => {
  230. // 先创建属于用户2的数据
  231. const dataSource = await IntegrationTestDatabase.getDataSource();
  232. const testRepository = dataSource.getRepository(TestEntity);
  233. const testData = testRepository.create({
  234. name: '用户2的数据',
  235. userId: testUser2.id
  236. });
  237. await testRepository.save(testData);
  238. // 用户1尝试获取用户2的数据
  239. const response = await client[':id'].$get({
  240. param: { id: testData.id }
  241. }, {
  242. headers: {
  243. 'Authorization': `Bearer ${testToken1}`
  244. }
  245. });
  246. console.debug('获取无权详情响应状态:', response.status);
  247. expect(response.status).toBe(404); // 权限验证失败返回404
  248. });
  249. it('应该处理不存在的资源', async () => {
  250. const response = await client[':id'].$get({
  251. param: { id: 999999 }
  252. }, {
  253. headers: {
  254. 'Authorization': `Bearer ${testToken1}`
  255. }
  256. });
  257. expect(response.status).toBe(404);
  258. });
  259. });
  260. describe('PUT /:id - 更新操作权限验证', () => {
  261. it('应该成功更新属于当前用户的数据', async () => {
  262. // 先创建测试数据
  263. const dataSource = await IntegrationTestDatabase.getDataSource();
  264. const testRepository = dataSource.getRepository(TestEntity);
  265. const testData = testRepository.create({
  266. name: '原始数据',
  267. userId: testUser1.id
  268. });
  269. await testRepository.save(testData);
  270. const updateData = {
  271. name: '更新后的数据'
  272. };
  273. const response = await client[':id'].$put({
  274. param: { id: testData.id },
  275. json: updateData
  276. }, {
  277. headers: {
  278. 'Authorization': `Bearer ${testToken1}`
  279. }
  280. });
  281. console.debug('更新数据响应状态:', response.status);
  282. expect(response.status).toBe(200);
  283. if (response.status === 200) {
  284. const data = await response.json();
  285. expect(data.name).toBe(updateData.name);
  286. expect(data.userId).toBe(testUser1.id);
  287. }
  288. });
  289. it('应该拒绝更新不属于当前用户的数据', async () => {
  290. // 先创建属于用户2的数据
  291. const dataSource = await IntegrationTestDatabase.getDataSource();
  292. const testRepository = dataSource.getRepository(TestEntity);
  293. const testData = testRepository.create({
  294. name: '用户2的数据',
  295. userId: testUser2.id
  296. });
  297. await testRepository.save(testData);
  298. const updateData = {
  299. name: '尝试更新的数据'
  300. };
  301. // 用户1尝试更新用户2的数据
  302. const response = await client[':id'].$put({
  303. param: { id: testData.id },
  304. json: updateData
  305. }, {
  306. headers: {
  307. 'Authorization': `Bearer ${testToken1}`
  308. }
  309. });
  310. console.debug('更新无权数据响应状态:', response.status);
  311. expect(response.status).toBe(500); // 权限验证失败会抛出错误
  312. if (response.status === 500) {
  313. const data = await response.json();
  314. expect(data.message).toContain('无权');
  315. }
  316. });
  317. });
  318. describe('DELETE /:id - 删除操作权限验证', () => {
  319. it('应该成功删除属于当前用户的数据', async () => {
  320. // 先创建测试数据
  321. const dataSource = await IntegrationTestDatabase.getDataSource();
  322. const testRepository = dataSource.getRepository(TestEntity);
  323. const testData = testRepository.create({
  324. name: '待删除数据',
  325. userId: testUser1.id
  326. });
  327. await testRepository.save(testData);
  328. const response = await client[':id'].$delete({
  329. param: { id: testData.id }
  330. }, {
  331. headers: {
  332. 'Authorization': `Bearer ${testToken1}`
  333. }
  334. });
  335. console.debug('删除数据响应状态:', response.status);
  336. expect(response.status).toBe(204);
  337. // 验证数据确实被删除
  338. const deletedData = await testRepository.findOne({
  339. where: { id: testData.id }
  340. });
  341. expect(deletedData).toBeNull();
  342. });
  343. it('应该拒绝删除不属于当前用户的数据', async () => {
  344. // 先创建属于用户2的数据
  345. const dataSource = await IntegrationTestDatabase.getDataSource();
  346. const testRepository = dataSource.getRepository(TestEntity);
  347. const testData = testRepository.create({
  348. name: '用户2的数据',
  349. userId: testUser2.id
  350. });
  351. await testRepository.save(testData);
  352. // 用户1尝试删除用户2的数据
  353. const response = await client[':id'].$delete({
  354. param: { id: testData.id }
  355. }, {
  356. headers: {
  357. 'Authorization': `Bearer ${testToken1}`
  358. }
  359. });
  360. console.debug('删除无权数据响应状态:', response.status);
  361. expect(response.status).toBe(500); // 权限验证失败会抛出错误
  362. if (response.status === 500) {
  363. const data = await response.json();
  364. expect(data.message).toContain('无权');
  365. }
  366. // 验证数据没有被删除
  367. const existingData = await testRepository.findOne({
  368. where: { id: testData.id }
  369. });
  370. expect(existingData).not.toBeNull();
  371. });
  372. });
  373. describe('禁用数据权限控制的情况', () => {
  374. it('当数据权限控制禁用时应该允许跨用户访问', async () => {
  375. // 创建禁用数据权限控制的路由
  376. const noPermissionRoutes = createCrudRoutes({
  377. entity: TestEntity,
  378. createSchema: createTestSchema,
  379. updateSchema: updateTestSchema,
  380. getSchema: getTestSchema,
  381. listSchema: listTestSchema,
  382. dataPermission: {
  383. enabled: false, // 禁用权限控制
  384. userIdField: 'userId'
  385. }
  386. });
  387. const noPermissionClient = testClient(noPermissionRoutes);
  388. // 创建属于用户2的数据
  389. const dataSource = await IntegrationTestDatabase.getDataSource();
  390. const testRepository = dataSource.getRepository(TestEntity);
  391. const testData = testRepository.create({
  392. name: '用户2的数据',
  393. userId: testUser2.id
  394. });
  395. await testRepository.save(testData);
  396. // 用户1应该能够访问用户2的数据(权限控制已禁用)
  397. const response = await noPermissionClient[':id'].$get({
  398. param: { id: testData.id }
  399. }, {
  400. headers: {
  401. 'Authorization': `Bearer ${testToken1}`
  402. }
  403. });
  404. console.debug('禁用权限控制时的响应状态:', response.status);
  405. expect(response.status).toBe(200);
  406. if (response.status === 200) {
  407. const data = await response.json();
  408. expect(data.id).toBe(testData.id);
  409. expect(data.userId).toBe(testUser2.id);
  410. }
  411. });
  412. });
  413. });