data-permission.integration.test.ts 14 KB

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