repair-order-data-permission-test.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. const axios = require('axios');
  2. const colors = require('colors');
  3. // 配置信息
  4. const CONFIG = {
  5. baseURL: 'http://localhost/dev-api',
  6. timeout: 10000,
  7. };
  8. // 测试用户配置
  9. const TEST_USERS = {
  10. // 超级管理员
  11. superAdmin: {
  12. username: 'admin',
  13. password: 'admin123',
  14. description: '超级管理员',
  15. expectedRole: 'superadmin',
  16. },
  17. // 物业维修管理员
  18. propertyAdmin: {
  19. username: 'zwc003', // 总务处科长舒刚
  20. password: 'admin123',
  21. description: '物业维修管理员',
  22. expectedRole: 'property_maintenance_admin',
  23. },
  24. // 维修人员
  25. maintenanceWorker: {
  26. username: 'zwc005', // 总务处干事陆雄
  27. password: 'admin123',
  28. description: '维修人员',
  29. expectedRole: 'maintenance_worker',
  30. },
  31. // 普通用户
  32. normalUser: {
  33. username: 'zkxy001', // 智控学院张三
  34. password: 'admin123',
  35. description: '普通用户(报修人)',
  36. expectedRole: 'none',
  37. },
  38. };
  39. /**
  40. * 登录获取Token
  41. */
  42. async function login(username, password) {
  43. const CryptoJS = require('crypto-js');
  44. const NodeRSA = require('node-rsa');
  45. // 生成32位随机AES密钥
  46. function generateAESKey() {
  47. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  48. let result = '';
  49. for (let i = 0; i < 32; i++) {
  50. result += chars.charAt(Math.floor(Math.random() * chars.length));
  51. }
  52. return result;
  53. }
  54. // AES加密
  55. function aesEncrypt(data, key) {
  56. const keyUtf8 = CryptoJS.enc.Utf8.parse(key);
  57. return CryptoJS.AES.encrypt(data, keyUtf8, {
  58. mode: CryptoJS.mode.ECB,
  59. padding: CryptoJS.pad.Pkcs7,
  60. }).toString();
  61. }
  62. // RSA加密AES密钥
  63. function rsaEncrypt(aesKey) {
  64. const rsaKeyStr =
  65. 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdHnzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ==';
  66. const pemKey = `-----BEGIN PUBLIC KEY-----\n${rsaKeyStr}\n-----END PUBLIC KEY-----`;
  67. const rsaKey = new NodeRSA(pemKey);
  68. rsaKey.setOptions({ encryptionScheme: 'pkcs1' });
  69. const aesKeyBase64 = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(aesKey));
  70. return rsaKey.encrypt(aesKeyBase64, 'base64');
  71. }
  72. const aesKey = generateAESKey();
  73. const loginData = {
  74. tenantId: '000000',
  75. username: username,
  76. password: password,
  77. clientId: 'e5cd7e4891bf95d1d19206ce24a7b32e',
  78. grantType: 'password',
  79. };
  80. const encryptedData = aesEncrypt(JSON.stringify(loginData), aesKey);
  81. const encryptedKey = rsaEncrypt(aesKey);
  82. const headers = {
  83. 'Content-Type': 'application/json;charset=utf-8',
  84. clientid: 'e5cd7e4891bf95d1d19206ce24a7b32e',
  85. 'encrypt-key': encryptedKey,
  86. referer: 'http://localhost/login?redirect=%252Findex',
  87. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  88. isToken: 'false',
  89. isEncrypt: 'true',
  90. };
  91. try {
  92. const response = await axios.post(`${CONFIG.baseURL}/auth/login`, encryptedData, {
  93. headers: headers,
  94. timeout: CONFIG.timeout,
  95. });
  96. if (response.data.code === 200 && response.data.data?.access_token) {
  97. return response.data.data.access_token;
  98. } else {
  99. throw new Error(response.data.msg || 'Login failed');
  100. }
  101. } catch (error) {
  102. console.error(`登录失败 [${username}]:`, error.message);
  103. throw error;
  104. }
  105. }
  106. /**
  107. * 调用API接口
  108. */
  109. async function callAPI(token, endpoint, method = 'GET', data = null) {
  110. try {
  111. const config = {
  112. method: method.toLowerCase(),
  113. url: `${CONFIG.baseURL}${endpoint}`,
  114. headers: {
  115. 'Content-Type': 'application/json;charset=utf-8',
  116. Authorization: `Bearer ${token}`,
  117. clientid: 'e5cd7e4891bf95d1d19206ce24a7b32e',
  118. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  119. referer: 'http://localhost/login?redirect=%252Findex',
  120. },
  121. timeout: CONFIG.timeout,
  122. };
  123. if (data && method.toUpperCase() !== 'GET') {
  124. config.data = data;
  125. } else if (data && method.toUpperCase() === 'GET') {
  126. config.params = data;
  127. }
  128. const response = await axios(config);
  129. return {
  130. success: true,
  131. data: response.data,
  132. status: response.status,
  133. };
  134. } catch (error) {
  135. return {
  136. success: false,
  137. error: error.response?.data || error.message,
  138. status: error.response?.status || 0,
  139. };
  140. }
  141. }
  142. /**
  143. * 获取用户信息
  144. */
  145. async function getUserInfo(token) {
  146. return await callAPI(token, '/system/user/getInfo');
  147. }
  148. /**
  149. * 获取报修工单列表
  150. */
  151. async function getRepairOrders(token, params = {}) {
  152. return await callAPI(token, '/pm/repairOrder/list', 'GET', params);
  153. }
  154. /**
  155. * 获取指定工单详情
  156. */
  157. async function getRepairOrderDetail(token, orderId) {
  158. return await callAPI(token, `/pm/repairOrder/${orderId}`);
  159. }
  160. /**
  161. * 测试数据权限
  162. */
  163. async function testDataPermissions() {
  164. console.log('🔐 报修工单数据权限测试'.yellow.bold);
  165. console.log('='.repeat(80).gray);
  166. const results = {};
  167. for (const [userType, userConfig] of Object.entries(TEST_USERS)) {
  168. console.log(`\n📋 测试用户:${userConfig.description} (${userConfig.username})`.cyan.bold);
  169. console.log('-'.repeat(60).gray);
  170. try {
  171. // 1. 登录获取Token
  172. console.log('🔑 正在登录...'.yellow);
  173. const token = await login(userConfig.username, userConfig.password);
  174. console.log('✅ 登录成功'.green);
  175. // 2. 获取用户信息
  176. console.log('👤 获取用户信息...'.yellow);
  177. const userInfoResult = await getUserInfo(token);
  178. if (userInfoResult.success) {
  179. const userInfo = userInfoResult.data.data;
  180. console.log(
  181. `✅ 用户信息:${userInfo.user.nickName} | 角色:${userInfo.roles.join(', ')}`,
  182. );
  183. results[userType] = {
  184. userConfig,
  185. userInfo: userInfo,
  186. token,
  187. tests: {},
  188. };
  189. } else {
  190. console.log('❌ 获取用户信息失败'.red);
  191. continue;
  192. }
  193. // 3. 测试工单列表权限
  194. console.log('📝 测试工单列表权限...'.yellow);
  195. const listResult = await getRepairOrders(token);
  196. if (listResult.success) {
  197. const totalOrders = listResult.data.total || 0;
  198. const orders = listResult.data.rows || [];
  199. console.log(`✅ 可查看工单数量:${totalOrders} 个`);
  200. results[userType].tests.listAccess = {
  201. success: true,
  202. totalOrders,
  203. orders: orders.slice(0, 3), // 只保存前3个用于显示
  204. };
  205. // 显示可查看的工单概况
  206. if (orders.length > 0) {
  207. console.log(' 可查看的工单:');
  208. orders.slice(0, 3).forEach((order) => {
  209. console.log(
  210. ` - ${order.orderNo}: ${order.title} (报修人:${
  211. order.reporterName
  212. }, 维修员:${order.assigneeName || '未分派'})`,
  213. );
  214. });
  215. if (orders.length > 3) {
  216. console.log(` - 还有 ${orders.length - 3} 个工单...`);
  217. }
  218. }
  219. } else {
  220. console.log(`❌ 工单列表查询失败:${listResult.error.msg || listResult.error}`);
  221. results[userType].tests.listAccess = {
  222. success: false,
  223. error: listResult.error,
  224. };
  225. }
  226. // 4. 测试具体工单详情权限(测试工单ID: 1001, 1002, 1003)
  227. console.log('🔍 测试工单详情权限...'.yellow);
  228. const testOrderIds = [1001, 1002, 1003];
  229. const detailResults = [];
  230. for (const orderId of testOrderIds) {
  231. const detailResult = await getRepairOrderDetail(token, orderId);
  232. if (detailResult.success) {
  233. const order = detailResult.data.data;
  234. console.log(` ✅ 工单 ${orderId}: ${order.title} (有权限查看)`);
  235. detailResults.push({
  236. orderId,
  237. success: true,
  238. order: {
  239. orderNo: order.orderNo,
  240. title: order.title,
  241. reporterName: order.reporterName,
  242. assigneeName: order.assigneeName,
  243. },
  244. });
  245. } else {
  246. console.log(
  247. ` ❌ 工单 ${orderId}: 无权限查看 (${
  248. detailResult.error.msg || detailResult.error
  249. })`,
  250. );
  251. detailResults.push({
  252. orderId,
  253. success: false,
  254. error: detailResult.error.msg || detailResult.error,
  255. });
  256. }
  257. }
  258. results[userType].tests.detailAccess = detailResults;
  259. } catch (error) {
  260. console.log(`❌ 测试失败:${error.message}`.red);
  261. results[userType] = {
  262. userConfig,
  263. error: error.message,
  264. };
  265. }
  266. }
  267. // 输出测试总结
  268. console.log('\n📊 数据权限测试总结'.cyan.bold);
  269. console.log('='.repeat(80).gray);
  270. for (const [userType, result] of Object.entries(results)) {
  271. if (result.error) {
  272. console.log(`❌ ${result.userConfig.description}: 测试失败 - ${result.error}`.red);
  273. continue;
  274. }
  275. const listAccess = result.tests.listAccess;
  276. const detailAccess = result.tests.detailAccess;
  277. console.log(`\n👤 ${result.userConfig.description} (${result.userConfig.username}):`.cyan);
  278. console.log(` 角色权限:${result.userInfo.roles.join(', ')}`);
  279. console.log(
  280. ` 可查看工单:${listAccess.success ? listAccess.totalOrders + ' 个' : '查询失败'}`,
  281. );
  282. if (detailAccess) {
  283. const accessibleDetails = detailAccess.filter((d) => d.success).length;
  284. console.log(
  285. ` 详情权限:${accessibleDetails}/${detailAccess.length} 个工单可查看详情`,
  286. );
  287. }
  288. }
  289. // 权限验证结果
  290. console.log('\n🎯 权限验证结果'.green.bold);
  291. console.log('-'.repeat(60).gray);
  292. // 验证超级管理员权限
  293. const superAdminResult = results.superAdmin;
  294. if (superAdminResult && !superAdminResult.error) {
  295. const canViewAll = superAdminResult.tests.listAccess.totalOrders >= 12; // 应该能看到所有工单
  296. console.log(
  297. `✅ 超级管理员权限:${canViewAll ? '✅ 正确' : '❌ 异常'} (可查看 ${
  298. superAdminResult.tests.listAccess.totalOrders
  299. } 个工单)`,
  300. );
  301. }
  302. // 验证物业维修管理员权限
  303. const propertyAdminResult = results.propertyAdmin;
  304. if (propertyAdminResult && !propertyAdminResult.error) {
  305. const canViewAll = propertyAdminResult.tests.listAccess.totalOrders >= 12; // 应该能看到所有工单
  306. console.log(
  307. `✅ 物业维修管理员权限:${canViewAll ? '✅ 正确' : '❌ 异常'} (可查看 ${
  308. propertyAdminResult.tests.listAccess.totalOrders
  309. } 个工单)`,
  310. );
  311. }
  312. // 验证维修人员权限
  313. const workerResult = results.maintenanceWorker;
  314. if (workerResult && !workerResult.error) {
  315. const limitedAccess = workerResult.tests.listAccess.totalOrders < 12; // 应该只能看到部分工单
  316. console.log(
  317. `✅ 维修人员权限:${limitedAccess ? '✅ 正确' : '❌ 异常'} (可查看 ${
  318. workerResult.tests.listAccess.totalOrders
  319. } 个工单)`,
  320. );
  321. }
  322. // 验证普通用户权限
  323. const normalUserResult = results.normalUser;
  324. if (normalUserResult && !normalUserResult.error) {
  325. const limitedAccess = normalUserResult.tests.listAccess.totalOrders <= 2; // 应该只能看到自己的工单
  326. console.log(
  327. `✅ 普通用户权限:${limitedAccess ? '✅ 正确' : '❌ 异常'} (可查看 ${
  328. normalUserResult.tests.listAccess.totalOrders
  329. } 个工单)`,
  330. );
  331. }
  332. return results;
  333. }
  334. /**
  335. * 主函数
  336. */
  337. async function main() {
  338. try {
  339. console.log('🚀 开始数据权限测试...'.green.bold);
  340. const results = await testDataPermissions();
  341. console.log('\n✅ 数据权限测试完成!'.green.bold);
  342. // 保存测试结果到文件(可选)
  343. const fs = require('fs');
  344. const reportPath = `data-permission-test-result-${
  345. new Date().toISOString().split('T')[0]
  346. }.json`;
  347. fs.writeFileSync(reportPath, JSON.stringify(results, null, 2));
  348. console.log(`📋 测试结果已保存到:${reportPath}`.gray);
  349. } catch (error) {
  350. console.error('❌ 测试执行失败:', error.message.red);
  351. process.exit(1);
  352. }
  353. }
  354. // 运行测试
  355. if (require.main === module) {
  356. main();
  357. }
  358. module.exports = {
  359. testDataPermissions,
  360. login,
  361. callAPI,
  362. TEST_USERS,
  363. };