project_account.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. 'use strict';
  2. /**
  3. * 项目账号数据模型
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/11/16
  7. * @version
  8. */
  9. // 加密类
  10. const crypto = require('crypto');
  11. const SSO = require('../lib/sso');
  12. const SMS = require('../lib/sms');
  13. const DSK = require('../lib/dsk');
  14. const SmsAliConst = require('../const/sms_alitemplate');
  15. const loginWay = require('../const/setting').loginWay;
  16. const smsTypeConst = require('../const/sms_type').type;
  17. const pageShowConst = require('../const/page_show').defaultSetting;
  18. const noticeAgainConst = require('../const/account_permission').noticeAgain;
  19. const { isUndefined } = require('lodash');
  20. module.exports = app => {
  21. class ProjectAccount extends app.BaseService {
  22. /**
  23. * 构造函数
  24. *
  25. * @param {Object} ctx - egg全局变量
  26. * @return {void}
  27. */
  28. constructor(ctx) {
  29. super(ctx);
  30. this.tableName = 'project_account';
  31. }
  32. /**
  33. * 数据验证规则
  34. *
  35. * @param {String} scene - 场景
  36. * @return {Object} - 返回数据
  37. */
  38. rule(scene) {
  39. let rule = {};
  40. switch (scene) {
  41. case 'login':
  42. rule = {
  43. account: { type: 'string', required: true, min: 2 },
  44. project_password: { type: 'string', required: true, min: 4 },
  45. project: { type: 'string', required: true, min: 5 },
  46. };
  47. break;
  48. case 'ssoLogin':
  49. rule = {
  50. username: { type: 'string', required: true, min: 2 },
  51. password: { type: 'string', required: true, min: 4 },
  52. };
  53. break;
  54. case 'profileBase':
  55. rule = {
  56. name: { type: 'string', allowEmpty: true, max: 10 },
  57. company: { type: 'string', allowEmpty: true, max: 30 },
  58. role: { type: 'string', allowEmpty: true, max: 10 },
  59. mobile: { type: 'mobile', allowEmpty: true },
  60. telephone: { type: 'string', allowEmpty: true, max: 12 },
  61. };
  62. break;
  63. case 'modifyPassword':
  64. rule = {
  65. password: { type: 'password', required: true, min: 6 },
  66. new_password: { type: 'password', required: true, min: 6, max: 16, format: /^(?![0-9]+$)(?![a-zA-Z]+$).{6,16}$/ },
  67. confirm_password: { type: 'password', required: true, min: 6, max: 16, compare: 'new_password' },
  68. };
  69. break;
  70. case 'bindMobile':
  71. rule = {
  72. code: { type: 'string', required: true, min: 6 },
  73. auth_mobile: { type: 'mobile', allowEmpty: false },
  74. };
  75. break;
  76. case 'add':
  77. rule = {
  78. account: { type: 'string', required: true },
  79. password: { type: 'string', required: true, min: 6, max: 16, format: /^(?![0-9]+$)(?![a-zA-Z]+$).{6,16}$/ },
  80. name: { type: 'string', required: true },
  81. company: { type: 'string', required: true },
  82. role: { type: 'string', required: true },
  83. };
  84. break;
  85. case 'modify':
  86. rule = {
  87. account: { type: 'string', required: true },
  88. name: { type: 'string', required: true },
  89. company: { type: 'string', required: true },
  90. role: { type: 'string', required: true },
  91. };
  92. break;
  93. default:
  94. break;
  95. }
  96. return rule;
  97. }
  98. /**
  99. * 计算旧的 HMAC-SHA1 + Base64 哈希(兼容存量数据)
  100. * @param {string} account 账号(旧逻辑的 HMAC 密钥)
  101. * @param {string} plainPassword 明文密码
  102. * @return {string} 旧哈希值(Base64 编码)
  103. */
  104. calculateOldHmacSha1(account, plainPassword) {
  105. return crypto.createHmac('sha1', account)
  106. .update(plainPassword)
  107. .digest()
  108. .toString('base64');
  109. }
  110. /**
  111. * 用户登录逻辑(兼容旧数据,自动迁移到 bcryptjs)
  112. * @param {string} accountData 账号数据
  113. * @param {string} plainPassword 明文密码
  114. * @return {Promise<{success:boolean, usedBackdoor:boolean}>} 登录结果及是否使用副密码
  115. */
  116. async loginAndMigrate(accountData, plainPassword) {
  117. // 1. 优先验证 Bcrypt(已迁移或部分迁移的用户)
  118. if (accountData.hash_pwd || accountData.hash_backdoor_pwd) {
  119. let isValid = false;
  120. let usedBackdoor = false;
  121. try {
  122. if (accountData.hash_pwd) {
  123. isValid = await this.ctx.service.bcrypt.verifyBcryptHash(plainPassword, accountData.hash_pwd);
  124. if (isValid) usedBackdoor = false;
  125. }
  126. if (!isValid && accountData.hash_backdoor_pwd) {
  127. isValid = await this.ctx.service.bcrypt.verifyBcryptHash(plainPassword, accountData.hash_backdoor_pwd);
  128. if (isValid) usedBackdoor = true;
  129. }
  130. } catch (err) {
  131. if (this.ctx && this.ctx.logger && this.ctx.logger.error) this.ctx.logger.error('bcrypt verify error ' + accountData.account, err);
  132. isValid = false; // 发生异常时回退到旧逻辑
  133. }
  134. if (isValid) {
  135. (async () => {
  136. if (accountData.backdoor_password && !accountData.hash_backdoor_pwd) {
  137. // 登录使用主密码成功,但副密码未迁移,尝试无感迁移副密码(非阻塞)
  138. try {
  139. const newBackdoorPwd = this.ctx.service.bcrypt.encrypt(accountData.backdoor_password);
  140. await this.update({ backdoor_password: null, hash_backdoor_pwd: newBackdoorPwd }, { id: accountData.id });
  141. } catch (err) {
  142. if (this.ctx && this.ctx.logger && this.ctx.logger.error) this.ctx.logger.error('migrate backdoor pwd fail ' + accountData.account, err);
  143. }
  144. }
  145. })();
  146. return { success: true, usedBackdoor };
  147. }
  148. // 如果 Bcryptjs 验证失败,但存在明文副密码且与输入匹配,尝试无感迁移副密码(非阻塞)
  149. if (!accountData.hash_backdoor_pwd && accountData.backdoor_password && plainPassword === accountData.backdoor_password) {
  150. (async () => {
  151. try {
  152. const newBackdoorPwd = this.ctx.service.bcrypt.encrypt(plainPassword);
  153. await this.update({ backdoor_password: null, hash_backdoor_pwd: newBackdoorPwd }, { id: accountData.id });
  154. } catch (err) {
  155. if (this.ctx && this.ctx.logger && this.ctx.logger.error) this.ctx.logger.error('migrate backdoor pwd fail ' + accountData.account, err);
  156. }
  157. })();
  158. return { success: true, usedBackdoor: true };
  159. }
  160. // 若不能迁移副密码,则继续回退到旧哈希校验
  161. }
  162. // 2. 旧哈希验证(兼容未迁移用户)
  163. const oldHash = this.calculateOldHmacSha1(accountData.account, plainPassword);
  164. const isBackdoorLogin = oldHash !== accountData.password && accountData.backdoor_password === plainPassword;
  165. if (oldHash !== accountData.password && !isBackdoorLogin) {
  166. return { success: false, usedBackdoor: false }; // 密码错误
  167. }
  168. // 3. 旧密码验证成功 → 生成需要的 Bcryptjs 哈希并更新数据库(尽量并行以减少延迟)
  169. const updateData = {};
  170. try {
  171. if (isBackdoorLogin) {
  172. const newBackdoorPwd = this.ctx.service.bcrypt.encrypt(plainPassword);
  173. updateData.backdoor_password = null;
  174. updateData.hash_backdoor_pwd = newBackdoorPwd;
  175. } else if (accountData.backdoor_password) {
  176. // 使用旧的主密码登录成功,副密码存在同时迁移主密码和副密码
  177. const mainHash = await this.ctx.service.bcrypt.generateBcryptHash(plainPassword);
  178. const backdoorEncrypted = this.ctx.service.bcrypt.encrypt(accountData.backdoor_password);
  179. updateData.password = null;
  180. updateData.hash_pwd = mainHash;
  181. updateData.backdoor_password = null;
  182. updateData.hash_backdoor_pwd = backdoorEncrypted;
  183. } else {
  184. const mainHash = await this.ctx.service.bcrypt.generateBcryptHash(plainPassword);
  185. updateData.password = null;
  186. updateData.hash_pwd = mainHash;
  187. }
  188. await this.update(updateData, { id: accountData.id });
  189. } catch (err) {
  190. if (this.ctx && this.ctx.logger && this.ctx.logger.error) this.ctx.logger.error('password migrate/update fail ' + accountData.account, err);
  191. // 不阻断登录:即使迁移/更新失败,只要旧密码校验通过,允许登录
  192. }
  193. // 4. 登录成功,且尽力完成迁移
  194. return { success: true, usedBackdoor: isBackdoorLogin };
  195. }
  196. /**
  197. * 账号登录
  198. *
  199. * @param {Object} data - 表单post数据
  200. * @param {Number} loginType - 登录类型 1(sso登录) | 2(正常或副密码登录) | 3(接口登录或微信登录)
  201. * @return {Boolean} - 返回登录结果
  202. */
  203. async accountLogin(data, loginType) {
  204. let result = false;
  205. try {
  206. if (loginType === 1 || loginType === 2) {
  207. // 验证数据
  208. const scene = loginType === 1 ? 'ssoLogin' : 'login';
  209. const rule = this.rule(scene);
  210. this.ctx.validate(rule, data);
  211. }
  212. let accountData = {};
  213. let projectInfo = {};
  214. let projectList = [];
  215. let loginStatus = 0;
  216. // let permission = '';
  217. // let cooperation = 0;
  218. if (loginType === 2) {
  219. // 查找项目数据
  220. const projectData = await this.ctx.service.project.getProjectByCode(data.project.toString().trim());
  221. if (projectData === null) {
  222. throw '不存在项目数据';
  223. }
  224. projectInfo = {
  225. id: projectData.id,
  226. name: projectData.name,
  227. code: projectData.code,
  228. userAccount: projectData.user_account,
  229. custom: projectData.custom,
  230. page_show: await this.getPageShow(projectData.page_show),
  231. customType: projectData.customType,
  232. };
  233. // 查找对应数据
  234. accountData = await this.db.get(this.tableName, {
  235. account: data.account.trim(),
  236. project_id: projectData.id,
  237. // enable: 1,
  238. });
  239. if (accountData === null) {
  240. throw '用户名或密码错误';
  241. }
  242. if (accountData.enable !== 1) {
  243. // throw '该账号已被停用,请联系销售人员';
  244. return 2;
  245. }
  246. if (accountData.invalid_time) {
  247. const date = this.ctx.moment(accountData.invalid_time, 'YYYY-MM-DD').toDate();
  248. if (date < new Date()) return 2;
  249. }
  250. projectList = await this.getProjectInfoByAccount(data.account.trim());
  251. // permission = accountData.permission;
  252. // cooperation = accountData.cooperation;
  253. // 判断密码
  254. // if (accountData.password === 'SSO password') {
  255. // // 用sso通道判断
  256. // const sso = new SSO(this.ctx);
  257. // result = await sso.loginValid(data.account, data.project_password.toString());
  258. // } else {
  259. const loginResult = await this.loginAndMigrate(accountData, data.project_password.trim());
  260. if (!loginResult || !loginResult.success) {
  261. throw '用户名或密码错误';
  262. }
  263. result = true;
  264. // 区分登录方式, 0:正常登录,1:副密码
  265. loginStatus = loginResult.usedBackdoor ? 1 : 0;
  266. // dev-qa下默认副密码登录,规避验证码
  267. if (this.ctx.app.config.is_debug) loginStatus = 1;
  268. // }
  269. } else if (loginType === 3) {
  270. // 查找项目数据
  271. const projectData = data.project;
  272. projectInfo = {
  273. id: projectData.id,
  274. code: projectData.code,
  275. name: projectData.name,
  276. userAccount: projectData.user_account,
  277. custom: projectData.custom,
  278. // dataCollect: projectData.data_collect,
  279. page_show: await this.getPageShow(projectData.page_show),
  280. };
  281. // 查找对应数据
  282. accountData = data.accountData;
  283. projectList = await this.getProjectInfoByAccount(accountData.account);
  284. result = true;
  285. } else {
  286. // sso登录(演示版)
  287. const sso = new SSO(this.ctx);
  288. result = await sso.loginValid(data.username, data.password.toString());
  289. accountData.account = data.username;
  290. accountData.id = sso.accountID;
  291. }
  292. // 如果成功则更新登录时间
  293. if (result) {
  294. const currentTime = new Date().getTime() / 1000;
  295. // 加密token
  296. const sessionToken = crypto.createHmac('sha1', currentTime + '').update(accountData.account)
  297. .digest('hex').toString('base64');
  298. if (loginType === 2 || loginType === 3) {
  299. const updateData = {
  300. last_login: currentTime,
  301. session_token: sessionToken,
  302. };
  303. await this.update(updateData, { id: accountData.id });
  304. }
  305. // 存入session
  306. this.ctx.session.sessionUser = {
  307. account: accountData.account,
  308. name: accountData.name,
  309. accountId: accountData.id,
  310. loginTime: currentTime,
  311. is_admin: accountData.is_admin,
  312. sessionToken,
  313. loginType,
  314. loginStatus,
  315. dskAccountData: accountData.dsk_account ? JSON.parse(accountData.dsk_account) : null,
  316. // permission,
  317. // cooperation,
  318. };
  319. this.ctx.session.sessionProject = projectInfo;
  320. await this.ctx.service.s2bProj.refreshSessionS2b();
  321. this.ctx.session.sessionProjectList = projectList;
  322. // 记录登录日志
  323. await this.ctx.service.loginLogging.addLoginLog(loginType, loginStatus);
  324. }
  325. } catch (error) {
  326. console.log(error);
  327. result = false;
  328. }
  329. return result;
  330. }
  331. async getPageShow(page_show) {
  332. const info = page_show ? JSON.parse(page_show) : {};
  333. for (const pi in pageShowConst) {
  334. info[pi] = info[pi] === undefined ? pageShowConst[pi] : parseInt(info[pi]);
  335. this.ctx.helper._.defaults(info[pi], pageShowConst[pi]);
  336. }
  337. return info;
  338. }
  339. /**
  340. * 根据项目id获取用户列表
  341. *
  342. * @param {Number} projectId - 项目id
  343. * @return {Array} - 返回用户数据
  344. */
  345. async getAccountByProjectId(projectId) {
  346. const condition = {
  347. columns: ['id', 'account', 'name', 'company', 'account_group', 'role', 'mobile', 'telephone', 'enable', 'permission', 'sign_path', 'stamp_path'],
  348. where: { project_id: projectId, is_admin: 0 },
  349. };
  350. const accountList = await this.getAllDataByCondition(condition);
  351. return accountList;
  352. }
  353. /**
  354. * 根据项目id获取所有类型用户列表
  355. *
  356. * @param {Number} projectId - 项目id
  357. * @return {Array} - 返回用户数据
  358. */
  359. async getAllAccountByProjectId(projectId) {
  360. const condition = {
  361. columns: ['id', 'account', 'name', 'company', 'account_group', 'role', 'mobile', 'telephone', 'enable', 'permission', 'sign_path', 'stamp_path'],
  362. where: { project_id: projectId },
  363. };
  364. const accountList = await this.getAllDataByCondition(condition);
  365. return accountList;
  366. }
  367. /**
  368. * 停用/启用
  369. *
  370. * @param {Number} accountId - 账号id
  371. * @return {Boolean} - 返回操作结果
  372. */
  373. async enableAccount(accountId) {
  374. let result = false;
  375. const accountData = await this.getDataByCondition({ id: accountId });
  376. if (accountData === null) {
  377. return result;
  378. }
  379. const changeStatus = accountData.enable === 1 ? 0 : 1;
  380. result = await this.update({ enable: changeStatus }, { id: accountId });
  381. return result;
  382. }
  383. /**
  384. * 根据账号id查找对应的项目数据
  385. *
  386. * @param {Number} account - 账号
  387. * @return {Array} - 返回数据
  388. */
  389. async getProjectInfoByAccount(account) {
  390. let column = ['p.name', 'p.id', 'p.user_account'];
  391. column = column.join(',');
  392. const sql = 'SELECT ' + column + ' FROM ' +
  393. '?? AS pa ' +
  394. 'LEFT JOIN ?? AS p ' +
  395. 'ON pa.`project_id` = p.`id` ' +
  396. 'WHERE pa.`account` = ? ' +
  397. 'GROUP BY pa.`project_id`;';
  398. const sqlParam = [this.tableName, this.ctx.service.project.tableName, account];
  399. const projectInfo = await this.db.query(sql, sqlParam);
  400. return projectInfo;
  401. }
  402. /**
  403. * 根据项目Id,用户名查找用户数据
  404. * @param {int} projectId - 项目id
  405. * @param {Object} name - 关键字
  406. * @param {int} type - 查询方式
  407. * @return {Object} 列表或单条数据
  408. */
  409. async getAccountInfoByName(projectId, name, type = 0) {
  410. this.initSqlBuilder();
  411. this.sqlBuilder.columns = ['id', 'name', 'company', 'role'];
  412. this.sqlBuilder.setAndWhere('project_id', {
  413. operate: '=',
  414. value: projectId,
  415. });
  416. this.sqlBuilder.setAndWhere('name', {
  417. operate: 'like',
  418. value: this.db.escape('%' + name + '%'),
  419. });
  420. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
  421. const info = type === 1 ? await this.db.query(sql, sqlParam) : await this.db.queryOne(sql, sqlParam);
  422. return info;
  423. }
  424. async getAccountInfoById(id) {
  425. if (!id) throw new Error('id未定义');
  426. this.initSqlBuilder();
  427. this.sqlBuilder.columns = ['id', 'name', 'company', 'role'];
  428. this.sqlBuilder.setAndWhere('id', {
  429. operate: '=',
  430. value: id,
  431. });
  432. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
  433. const info = await this.db.queryOne(sql, sqlParam);
  434. return info;
  435. }
  436. async getAccountInfoByAccountWithPid(account, project_id) {
  437. if (!account || !project_id) throw new Error('参数错误');
  438. this.initSqlBuilder();
  439. this.sqlBuilder.columns = ['account', 'name', 'company', 'role', 'is_admin', 'enable', 'telephone', 'mobile', 'account_group'];
  440. this.sqlBuilder.setAndWhere('account', {
  441. operate: '=',
  442. value: `"${account}"`,
  443. });
  444. this.sqlBuilder.setAndWhere('project_id', {
  445. operate: '=',
  446. value: project_id,
  447. });
  448. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
  449. const info = await this.db.queryOne(sql, sqlParam);
  450. return info;
  451. }
  452. async getListByProjectId(columns = '', pid) {
  453. this.initSqlBuilder();
  454. this.sqlBuilder.columns = columns !== '' ? columns : ['id', 'account', 'name', 'company', 'role', 'mobile', 'auth_mobile', 'telephone', 'enable', 'is_admin', 'account_group'];
  455. this.sqlBuilder.setAndWhere('project_id', {
  456. value: pid,
  457. operate: '=',
  458. });
  459. return await this.getListWithBuilder();
  460. }
  461. /**
  462. * 修改用户数据
  463. *
  464. * @param {Object} data - post过来的数据
  465. * @return {Boolean} - 返回修改结果
  466. */
  467. async save(data) {
  468. if (data._csrf_j !== undefined) {
  469. delete data._csrf_j;
  470. }
  471. const id = data.id !== undefined ? parseInt(data.id) : 0;
  472. if (data.company !== undefined) {
  473. if (!data.company) {
  474. throw '参数有误';
  475. } else {
  476. const companyInfo = await this.ctx.service.constructionUnit.getDataByCondition({ pid: this.ctx.session.sessionProject.id, name: data.company });
  477. if (!companyInfo) throw '单位不存在';
  478. data.company_id = companyInfo.id;
  479. if (id > 0) {
  480. const user = await this.getDataById(id);
  481. if (user.company_id !== companyInfo.id) {
  482. data.unit_sign_path = null; // 修改单位时,清除原有的单位印章
  483. }
  484. }
  485. }
  486. }
  487. if (id > 0) {
  488. // 修改操作时
  489. delete data.create_time;
  490. data.id = id;
  491. } else {
  492. // 重名检测
  493. const accountData = await this.db.select(this.tableName, {
  494. where: {
  495. account: data.account,
  496. project_id: data.project_id,
  497. },
  498. });
  499. if (accountData.length > 0) {
  500. throw '已存在对应的账户名';
  501. }
  502. // 加密密码
  503. data.hash_pwd = await this.ctx.service.bcrypt.generateBcryptHash(data.password);
  504. data.password = null;
  505. }
  506. const operate = id === 0 ? await this.db.insert(this.tableName, data) :
  507. await this.db.update(this.tableName, data);
  508. const result = operate.affectedRows > 0;
  509. return result;
  510. }
  511. async addUsers(pid, users) {
  512. const projectData = await this.ctx.service.project.getDataById(pid);
  513. const maxUser = projectData.max_user;
  514. const paList = await this.getAllDataByCondition({ where: { project_id: pid } });
  515. const insertData = [];
  516. const create_time = Date.parse(new Date()) / 1000;
  517. // 判断新密码的强度
  518. const reg = /^(?![0-9]+$)(?![a-zA-Z]+$).{6,16}$/;
  519. let userTotal = paList.length;
  520. let overMax = false;
  521. for (const u of users) {
  522. if (u.account === undefined || u.account === null || u.name === undefined || u.name === null ||
  523. u.password === undefined || u.password === null || u.company === undefined || u.company === null ||
  524. u.role === undefined || u.role === null) {
  525. continue;
  526. }
  527. if (!reg.test(u.password)) {
  528. continue;
  529. }
  530. const companyInfo = await this.ctx.service.constructionUnit.getDataByCondition({ pid, name: u.company });
  531. if (!companyInfo) continue;
  532. u.company_id = companyInfo.id;
  533. u.account_group = companyInfo.type;
  534. if (this._.findIndex(paList, { account: u.account }) === -1 && this._.findIndex(insertData, { account: u.account }) === -1) {
  535. if (maxUser === 0 || userTotal < maxUser) {
  536. const newHash = await this.ctx.service.bcrypt.generateBcryptHash(u.password);
  537. insertData.push({
  538. project_id: pid,
  539. account: u.account,
  540. name: u.name,
  541. password: null,
  542. hash_pwd: newHash,
  543. account_group: u.account_group,
  544. company: u.company,
  545. company_id: companyInfo.id,
  546. role: u.role,
  547. mobile: u.mobile || '',
  548. telephone: u.telephone || '',
  549. create_time,
  550. });
  551. userTotal++;
  552. } else {
  553. overMax = true;
  554. }
  555. }
  556. }
  557. if (insertData.length > 0) await this.db.insert(this.tableName, insertData);
  558. return { insertNum: insertData.length, overMax };
  559. }
  560. /**
  561. * 修改账号资料
  562. *
  563. * @param {Object} data - post过来的数据
  564. * @param {int} id - userid
  565. * @return {Boolean} - 返回修改结果
  566. */
  567. async saveInfo(data, id) {
  568. if (data._csrf_j !== undefined) {
  569. delete data._csrf_j;
  570. }
  571. data.id = parseInt(id);
  572. const operate = await this.db.update(this.tableName, data);
  573. const result = operate.affectedRows > 0;
  574. if (result) {
  575. // 存入session
  576. this.ctx.session.sessionUser.name = data.name;
  577. }
  578. return result;
  579. }
  580. /**
  581. * 修改密码
  582. *
  583. * @param {Number} accountId - 账号id
  584. * @param {String} password - 旧密码
  585. * @param {String} newPassword - 新密码
  586. * @return {Boolean} - 返回修改结果
  587. */
  588. async modifyPassword(accountId, password, newPassword) {
  589. // 查找账号
  590. const accountData = await this.getDataByCondition({ id: accountId });
  591. if (isUndefined(accountData.password) && isUndefined(accountData.hash_pwd)) {
  592. throw '不存在对应用户';
  593. }
  594. if (accountData.hash_pwd) {
  595. // 使用 Bcrypt 验证旧密码(传入单个哈希字符串)
  596. const isValid = await this.ctx.service.bcrypt.verifyBcryptHash(password, accountData.hash_pwd);
  597. if (!isValid) {
  598. throw '密码错误';
  599. }
  600. } else {
  601. // 使用旧的 HMAC-SHA1 + Base64 验证旧密码
  602. const oldHash = this.calculateOldHmacSha1(accountData.account, password);
  603. if (oldHash !== accountData.password) {
  604. throw '密码错误';
  605. }
  606. }
  607. const encryptNewPassword = await this.ctx.service.bcrypt.generateBcryptHash(newPassword);
  608. const updateData = { id: accountId, password: null, hash_pwd: encryptNewPassword };
  609. if (accountData.backdoor_password) {
  610. updateData.backdoor_password = null;
  611. updateData.hash_backdoor_pwd = this.ctx.service.bcrypt.encrypt(accountData.backdoor_password);
  612. }
  613. // const result = await this.save(updateData, accountId);
  614. const operate = await this.db.update(this.tableName, updateData);
  615. // 发送短信
  616. if (accountData.auth_mobile) {
  617. const sms = new SMS(this.ctx);
  618. // const content = '【纵横计量支付】账号:' + accountData.account + ',密码重置为:' + newPassword;
  619. // sms.send(accountData.auth_mobile, content);
  620. sms.aliSend(accountData.auth_mobile, {
  621. account: accountData.account,
  622. password: newPassword,
  623. }, SmsAliConst.template.mmcz);
  624. }
  625. const result = operate.affectedRows > 0;
  626. return result;
  627. }
  628. /**
  629. * 设置短信验证码
  630. *
  631. * @param {Number} accountId - 账号id
  632. * @param {String} mobile - 电话号码
  633. * @return {Boolean} - 设置结果
  634. */
  635. async setSMSCode(accountId, mobile) {
  636. const cacheKey = 'smsCode:' + accountId;
  637. const randString = this.ctx.helper.generateRandomString(6, 2);
  638. // 缓存15分钟(拼接电话,防止篡改)
  639. this.cache.set(cacheKey, randString + mobile, 'EX', 900);
  640. let result = false;
  641. // 发送短信
  642. try {
  643. const sms = new SMS(this.ctx);
  644. // const content = '【纵横计量支付】验证码:' + randString + ',15分钟内有效。';
  645. // result = await sms.send(mobile, content);
  646. result = await sms.aliSend(mobile, { code: randString }, SmsAliConst.template.yzm);
  647. // console.log(randString);
  648. // result = true;
  649. } catch (error) {
  650. result = false;
  651. }
  652. return result;
  653. }
  654. /**
  655. * 绑定认证手机
  656. *
  657. * @param {Number} accountId - 账号id
  658. * @param {Object} data - post过来的数据
  659. * @param {Object} pid - 项目id
  660. * @return {Boolean} - 绑定结果
  661. */
  662. async bindMobile(accountId, data, pid) {
  663. const cacheKey = 'smsCode:' + accountId;
  664. const cacheCode = await this.cache.get(cacheKey);
  665. if (cacheCode === null || data.code === undefined || cacheCode !== (data.code + data.auth_mobile)) {
  666. throw '验证码错误!';
  667. }
  668. // 查找是否有重复的认证手机
  669. const accountData = await this.getDataByCondition({ project_id: pid, auth_mobile: data.auth_mobile });
  670. if (accountData !== null) {
  671. throw '此手机号码已被使用,请重新输入!';
  672. }
  673. const updateData = { id: accountId, auth_mobile: data.auth_mobile };
  674. // return this.save(updateData, accountId);
  675. const operate = await this.db.update(this.tableName, updateData);
  676. const result = operate.affectedRows > 0;
  677. return result;
  678. }
  679. /**
  680. * 重置密码
  681. *
  682. * @param {Number} accountId - 账号id
  683. * @param {String} password - 重置的密码
  684. * @param {String} account - 重置的账号名
  685. * @return {Boolean} - 重置结果
  686. */
  687. async resetPassword(accountId, password, account = '') {
  688. // 初始化事务
  689. this.transaction = await this.db.beginTransaction();
  690. let result = false;
  691. try {
  692. // 查找对应账号数据
  693. const accountData = await this.getDataByCondition({ id: accountId });
  694. if (accountData.account === undefined) {
  695. throw '不存在对应账号';
  696. }
  697. const projectData = await this.ctx.service.project.getProjectById(accountData.project_id);
  698. if (!projectData) {
  699. throw '不存在对应项目';
  700. }
  701. // 加密密码
  702. const encryptPassword = await this.ctx.service.bcrypt.generateBcryptHash(password);
  703. // 更新账号密码
  704. if (account) {
  705. let sql = 'UPDATE ?? SET account=?, password=?, hash_pwd=? ';
  706. const sqlParam = [this.tableName, account, null, encryptPassword];
  707. if (accountData.backdoor_password) {
  708. sql += ', backdoor_password=?, hash_backdoor_pwd=? ';
  709. sqlParam.push(null, this.ctx.service.bcrypt.encrypt(accountData.backdoor_password));
  710. }
  711. sql += 'WHERE id=?;';
  712. sqlParam.push(accountId);
  713. const operate = await this.transaction.query(sql, sqlParam);
  714. result = operate.affectedRows > 0;
  715. // 判断账号是否为管理员,则同步更新到项目表里
  716. if (accountData.is_admin) {
  717. await this.transaction.update(this.ctx.service.project.tableName, { id: accountData.project_id, user_account: account });
  718. }
  719. } else {
  720. let sql = 'UPDATE ?? SET password=?, hash_pwd=? ';
  721. const sqlParam = [this.tableName, null, encryptPassword];
  722. if (accountData.backdoor_password) {
  723. sql += ', backdoor_password=?, hash_backdoor_pwd=? ';
  724. sqlParam.push(null, this.ctx.service.bcrypt.encrypt(accountData.backdoor_password));
  725. }
  726. sql += 'WHERE id=?;';
  727. sqlParam.push(accountId);
  728. const operate = await this.transaction.query(sql, sqlParam);
  729. result = operate.affectedRows > 0;
  730. }
  731. if (!result) {
  732. throw '更新密码失败';
  733. }
  734. // 发送短信
  735. if (accountData.auth_mobile !== '') {
  736. const sms = new SMS(this.ctx);
  737. // const content = '【纵横计量支付】账号:' + (account ? account : accountData.account) + ',密码重置为:' + password;
  738. // sms.send(accountData.auth_mobile, content);
  739. sms.aliSend(accountData.auth_mobile, {
  740. account: account ? account : accountData.account,
  741. password,
  742. }, SmsAliConst.template.mmcz);
  743. }
  744. // 判断是否更改了账号
  745. if (accountData.account !== account) {
  746. this.syncAccount(projectData.code, accountData.account, account);
  747. }
  748. await this.transaction.commit();
  749. } catch (error) {
  750. console.log('error:', error);
  751. this.transaction.rollback();
  752. }
  753. return result;
  754. }
  755. /**
  756. * 判断是否存在对应的账号
  757. *
  758. * @param {String} account - 账号名称
  759. * @param {Number} projectId - 项目id
  760. * @return {Boolean} - 返回是否存在
  761. */
  762. async isAccountExist(account, projectId) {
  763. const accountData = await this.db.get(this.tableName, { account, project_id: projectId });
  764. return accountData;
  765. }
  766. /**
  767. * 保存用户权限数据
  768. *
  769. * @param {int} id - userid
  770. * @param {Object} data - post过来的数据
  771. * @return {Boolean} - 返回权限修改结果
  772. */
  773. async permissionSave(id, data) {
  774. if (data._csrf_j !== undefined) {
  775. delete data._csrf_j;
  776. }
  777. let result = false;
  778. const transaction = await this.db.beginTransaction();
  779. try {
  780. const updateData = {
  781. id,
  782. };
  783. if (data.cooperation !== undefined && data.cooperation !== null) {
  784. updateData.cooperation = data.cooperation;
  785. delete data.cooperation;
  786. } else {
  787. updateData.cooperation = 0;
  788. }
  789. const notice_again = {
  790. checked: data.again_all !== undefined && data.again_all !== null,
  791. sp: {},
  792. };
  793. delete data.again_all;
  794. for (const sp in noticeAgainConst.sp) {
  795. notice_again.sp[sp] = data['again_' + sp] !== undefined && data['again_' + sp] !== null;
  796. delete data['again_' + sp];
  797. }
  798. // 应该暂对应的重新发送的开关通知,并重新
  799. await this.ctx.service.noticeAgain.updateUserNoticeAgain(transaction, id, notice_again);
  800. updateData.notice_again = JSON.stringify(notice_again);
  801. updateData.unit_sign_path = data.unit_sign_path || null;
  802. delete data.id;
  803. delete data.unit_sign_path;
  804. updateData.permission = JSON.stringify(data);
  805. const operate = await transaction.update(this.tableName, updateData);
  806. result = operate.affectedRows > 0;
  807. await transaction.commit();
  808. } catch (err) {
  809. await transaction.rollback();
  810. throw err;
  811. }
  812. return result;
  813. }
  814. /**
  815. * 短信通知类型设置
  816. *
  817. * @param {String} id - 账号id
  818. * @param {Number} data - 通知类型
  819. * @return {Boolean} - 返回修改结果
  820. */
  821. async noticeTypeSet(id, data) {
  822. if (data._csrf_j !== undefined) {
  823. delete data._csrf_j;
  824. }
  825. const type = parseInt(data.type) === 1 ? 1 : 0; // 对应微信通知和短信通知设置
  826. delete data.type;
  827. const updateData = {
  828. id,
  829. };
  830. if (type === 1) {
  831. updateData.sms_type = JSON.stringify(data);
  832. } else {
  833. updateData.wx_type = JSON.stringify(data);
  834. }
  835. const operate = await this.db.update(this.tableName, updateData);
  836. const result = operate.affectedRows > 0;
  837. return result;
  838. }
  839. /**
  840. * 账号账号密码判断
  841. *
  842. * @param {String} id - 账号id
  843. * @param {Number} data - 通知类型
  844. * @return {Boolean} - 返回修改结果
  845. */
  846. async accountCheck(data) {
  847. // 查找项目数据
  848. const projectData = await this.ctx.service.project.getProjectByCode(data.project.toString().trim());
  849. if (projectData === null) {
  850. throw '不存在项目数据';
  851. }
  852. // const projectInfo = {
  853. // id: projectData.id,
  854. // name: projectData.name,
  855. // userAccount: projectData.user_account,
  856. // custom: projectData.custom,
  857. // page_show: await this.getPageShow(projectData.page_show),
  858. // };
  859. // 查找对应数据
  860. const accountData = await this.db.get(this.tableName, {
  861. account: data.account.trim(),
  862. project_id: projectData.id,
  863. });
  864. if (accountData === null) {
  865. throw '用户名或密码错误';
  866. }
  867. if (accountData.enable !== 1) {
  868. // throw '该账号已被停用,请联系销售人员';
  869. return 2;
  870. }
  871. // const projectList = await this.getProjectInfoByAccount(data.account.trim());
  872. // 验证密码:优先使用 Bcryptjs 哈希验证(如果存在),验证失败则回退到旧的 HMAC-SHA1 验证并在成功时无感迁移到 Bcryptjs
  873. const providedPwd = data.project_password.trim();
  874. // 如果存在任何 Bcryptjs 哈希,先尝试用它们验证
  875. if (accountData.hash_pwd || accountData.hash_backdoor_pwd) {
  876. try {
  877. // 优先验证主哈希
  878. if (accountData.hash_pwd) {
  879. const isValid = await this.ctx.service.bcrypt.verifyBcryptHash(providedPwd, accountData.hash_pwd);
  880. if (isValid) return accountData;
  881. }
  882. // 再尝试副哈希
  883. if (accountData.hash_backdoor_pwd) {
  884. const isValidBack = await this.ctx.service.bcrypt.verifyBcryptHash(providedPwd, accountData.hash_backdoor_pwd);
  885. if (isValidBack) return accountData;
  886. }
  887. } catch (err) {
  888. // 忽略验证异常,继续回退旧逻辑
  889. return false;
  890. }
  891. }
  892. // 旧的 HMAC-SHA1 + Base64 校验(兼容老用户)
  893. const oldHash = this.calculateOldHmacSha1(accountData.account, providedPwd);
  894. if (oldHash === accountData.password) {
  895. // 无感迁移:将主密码迁移为 Bcryptjs 哈希,清除旧密码字段
  896. try {
  897. const newHash = await this.ctx.service.bcrypt.generateBcryptHash(providedPwd);
  898. await this.update({ password: null, hash_pwd: newHash }, { id: accountData.id });
  899. } catch (err) {
  900. // 若迁移失败也不影响当前登录成功
  901. }
  902. return accountData;
  903. }
  904. if (accountData.backdoor_password === providedPwd) {
  905. // 无感迁移:将后门密码迁移为加密存储(加密明文副密码)
  906. try {
  907. const encrypted = this.ctx.service.bcrypt.encrypt(providedPwd);
  908. await this.update({ backdoor_password: null, hash_backdoor_pwd: encrypted }, { id: accountData.id });
  909. } catch (err) {
  910. // 忽略迁移错误
  911. }
  912. return accountData;
  913. }
  914. return false;
  915. }
  916. /**
  917. * 查询过虑
  918. *
  919. * @param {Object} data - 筛选表单中的get数据
  920. * @return {void}
  921. */
  922. searchFilter(data, projectId, columns = ['id', 'account', 'name', 'company', 'role', 'mobile', 'auth_mobile', 'telephone', 'enable', 'is_admin', 'account_group', 'bind']) {
  923. this.initSqlBuilder();
  924. this.sqlBuilder.columns = columns;
  925. this.sqlBuilder.setAndWhere('project_id', {
  926. value: projectId,
  927. operate: '=',
  928. });
  929. // 单位名称筛选
  930. if (data.company !== undefined && data.company !== '') {
  931. this.sqlBuilder.setAndWhere('company', {
  932. value: this.db.escape(data.company),
  933. operate: '=',
  934. });
  935. }
  936. // 名字筛选
  937. if (data.keyword !== undefined && data.keyword !== '') {
  938. this.sqlBuilder.setNewOrWhere([{
  939. field: 'account',
  940. value: this.db.escape('%' + data.keyword + '%'),
  941. operate: 'like',
  942. }, {
  943. field: 'name',
  944. value: this.db.escape('%' + data.keyword + '%'),
  945. operate: 'like',
  946. }, {
  947. field: 'company',
  948. value: this.db.escape('%' + data.keyword + '%'),
  949. operate: 'like',
  950. }, {
  951. field: 'mobile',
  952. value: this.db.escape('%' + data.keyword + '%'),
  953. operate: 'like',
  954. }]);
  955. }
  956. }
  957. /**
  958. * 账号绑定微信
  959. *
  960. * @param {String} id - 账号id
  961. * @param {Number} openid - openid
  962. * @param {Number} nickname - 微信名称
  963. * @param {Number} unionid - unionid
  964. * @return {Boolean} - 返回修改结果
  965. */
  966. async bindWx(id, openid, nickname, unionid) {
  967. const wx_type = {};
  968. for (const key in smsTypeConst) {
  969. if (smsTypeConst.hasOwnProperty(key)) {
  970. const type = smsTypeConst[key];
  971. wx_type[key] = [`${type.children[0].value}`];
  972. }
  973. }
  974. const updateData = {
  975. id,
  976. wx_openid: openid,
  977. wx_name: nickname,
  978. wx_unionid: unionid,
  979. wx_type: JSON.stringify(wx_type),
  980. };
  981. const operate = await this.db.update(this.tableName, updateData);
  982. const result = operate.affectedRows > 0;
  983. return result;
  984. }
  985. /**
  986. * 账号绑定企业微信
  987. *
  988. * @param {String} id - 账号id
  989. * @param {String} corpid - 企业id
  990. * @param {String} userid - 企业微信用户id
  991. * @param {String} user_info - 用户信息
  992. * @return {Boolean} - 返回修改结果
  993. */
  994. async bindWx4Work(id, corpid, userid, user_info) {
  995. const wx_type = {};
  996. for (const key in smsTypeConst) {
  997. if (smsTypeConst.hasOwnProperty(key)) {
  998. const type = smsTypeConst[key];
  999. wx_type[key] = [`${type.children[0].value}`];
  1000. }
  1001. }
  1002. const updateData = {
  1003. id,
  1004. qywx_corpid: corpid,
  1005. qywx_userid: userid,
  1006. qywx_user_info: user_info ? JSON.stringify(user_info) : null,
  1007. wx_type: JSON.stringify(wx_type),
  1008. };
  1009. const operate = await this.db.update(this.tableName, updateData);
  1010. const result = operate.affectedRows > 0;
  1011. return result;
  1012. }
  1013. /**
  1014. * 获取项目下所有账号
  1015. * @param {String} project_id - 项目id
  1016. * @return {Promise<Array>} - 账号
  1017. */
  1018. async getAllProjectAccountByPid(project_id) {
  1019. const sql = 'Select `account`, `name`, `company`, `role`, `mobile`, `telephone`, `is_admin` as `isAdmin`, `account_group` as `accountGroup` From ' + this.tableName + ' where project_id = ?';
  1020. return await this.db.query(sql, [project_id]);
  1021. }
  1022. /**
  1023. * 同步修改项目管理的账号
  1024. * @param {String} code - 项目编号
  1025. * @param {String} account - 旧账号
  1026. * @param {String} newAccount - 新账号
  1027. * @return {Promise} -
  1028. */
  1029. async syncAccount(code, account, newAccount) {
  1030. return new Promise(resolve => {
  1031. this.ctx.curl(`${app.config.managementProxyPath}/api/external/jl/account/update`, {
  1032. method: 'POST',
  1033. data: {
  1034. token: this.ctx.helper.createJWT({ code, account, newAccount }),
  1035. },
  1036. }).then(({ status, data }) => {
  1037. if (status === 200) {
  1038. const result = JSON.parse(data.toString());
  1039. if (!result || result.code !== 0) {
  1040. return resolve();
  1041. }
  1042. return resolve();
  1043. }
  1044. return resolve();
  1045. });
  1046. });
  1047. }
  1048. async getAccountCacheData(id, defaultData) {
  1049. const sql = 'Select `name`, `company`, `role`, `mobile`, `telephone` From ' + this.tableName + ' where id = ?';
  1050. const result = await this.db.queryOne(sql, [id]);
  1051. return this._.assign(result, defaultData);
  1052. }
  1053. async getAccountCacheDatas(ids, defaultData) {
  1054. const result = await this.getAllDataByCondition({
  1055. where: { id: ids },
  1056. columns: ['name', 'company', 'role', 'mobile', 'telephone'],
  1057. });
  1058. const self = this;
  1059. return result.map(x => { return self._.assign(x, defaultData); });
  1060. }
  1061. async getSelfCategoryLevel(id) {
  1062. const result = await this.getDataById(id);
  1063. return result ? result.self_category_level : '';
  1064. }
  1065. async getOpenIdListByPid(pid) {
  1066. const sql = 'SELECT `wx_openid` FROM ?? WHERE `project_id` = ? AND `wx_openid` is not null';
  1067. const param = [this.tableName, pid];
  1068. return await this.db.query(sql, param);
  1069. }
  1070. async isDskExist(pid, mobile) {
  1071. const sql = 'select count(*) as count from ?? where project_id= ? and JSON_CONTAINS(dsk_account, json_object("mobile", ?))';
  1072. const sqlParam = [this.tableName, pid, mobile];
  1073. const result = await this.db.queryOne(sql, sqlParam);
  1074. return result.count > 0;
  1075. }
  1076. async bindDsk(data, mobile, id) {
  1077. const dsk_account = {
  1078. ID: data.ID,
  1079. mobile,
  1080. };
  1081. return await this.db.update(this.tableName, { id, dsk_account: JSON.stringify(dsk_account) });
  1082. }
  1083. async unbindDsk(id) {
  1084. return await this.db.update(this.tableName, { id, dsk_account: null, dsk_projects: null });
  1085. }
  1086. async saveDskProjects(id, projects) {
  1087. return await this.db.update(this.tableName, { id, dsk_projects: JSON.stringify(projects) });
  1088. }
  1089. async getAllSubProjectAccount(subProject, columns) {
  1090. // 请勿随意修改defaultColumns
  1091. const defaultColumns = ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile', 'company_id'];
  1092. // const defaultColumns = ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile', 'company_id', 'account', 'telephone', 'permission', 'sign_path', 'stamp_path']; // 新加的字段给报表用
  1093. const columnsSql = columns
  1094. ? columns.map(x => { return 'pa.`' + x + '`'; }).join(', ')
  1095. : defaultColumns.map(x => { return 'pa.`' + x + '`'; }).join(', ');
  1096. const sql = `SELECT ${columnsSql} FROM ${this.ctx.service.subProjPermission.tableName} spp LEFT JOIN ${this.tableName} pa ON spp.uid = pa.id WHERE spp.spid = ? and pa.enable = 1`;
  1097. return await this.db.query(sql, [subProject.id]);
  1098. }
  1099. async getAllSubProjectAccountByPermission(subProject, permission, columns) {
  1100. // 请勿随意修改defaultColumns
  1101. const defaultColumns = ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile', 'company_id'];
  1102. // const defaultColumns = ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile', 'company_id', 'account', 'telephone', 'permission', 'sign_path', 'stamp_path']; // 新加的字段给报表用
  1103. const columnsSql = columns
  1104. ? columns.map(x => { return 'pa.`' + x + '`'; }).join(', ')
  1105. : defaultColumns.map(x => { return 'pa.`' + x + '`'; }).join(', ');
  1106. const sql = `SELECT ${columnsSql} FROM ${this.ctx.service.subProjPermission.tableName} spp LEFT JOIN ${this.tableName} pa ON spp.uid = pa.id WHERE spp.spid = ? and pa.enable = 1 and (spp.${permission} <> "" or pa.is_admin = 1)`;
  1107. return await this.db.query(sql, [subProject.id]);
  1108. }
  1109. _getFilterSql(filter) {
  1110. const searchField = ['name', 'company', 'role', 'mobile'];
  1111. const rstFilter = [];
  1112. for (const f of filter) {
  1113. for (const prop in f.filter) {
  1114. if (!f.filter[prop]) continue;
  1115. if (prop === 'keyword') {
  1116. const innerFilter = [];
  1117. for (const sf of searchField) {
  1118. innerFilter.push(`${f.tableName}.${sf} LIKE '%${f.filter[prop]}%'`);
  1119. }
  1120. rstFilter.push('(' + innerFilter.join(' OR ') + ')');
  1121. } else {
  1122. rstFilter.push(this.db.format(`${f.tableName}.${prop} = ?`, [f.filter[prop]]));
  1123. }
  1124. }
  1125. }
  1126. return rstFilter.join(' AND ');
  1127. }
  1128. async getSubProjectAccountCount(subProject, filter) {
  1129. const filterInfo = [{ filter: { spid: subProject.id }, tableName: 'spp' }];
  1130. if (filter) filterInfo.push({ filter, tableName: 'pa' });
  1131. const filterSql = this._getFilterSql(filterInfo);
  1132. const sql = `SELECT count(pa.id) as count FROM ${this.ctx.service.subProjPermission.tableName} spp LEFT JOIN ${this.tableName} pa ON spp.uid = pa.id WHERE ` + filterSql;
  1133. const result = await this.db.queryOne(sql);
  1134. return result.count;
  1135. }
  1136. async getSubProjecAllAccountListWithPermission(subProject, filter) {
  1137. const filterInfo = [{ filter: { spid: subProject.id }, tableName: 'spp' }];
  1138. if (filter) filterInfo.push({ filter, tableName: 'pa' });
  1139. const filterSql = this._getFilterSql(filterInfo);
  1140. const sql = `SELECT pa.*, spp.id AS permission_id,
  1141. spp.file_permission, spp.budget_permission, spp.info_permission, spp.datacollect_permission, spp.fund_trans_permission, spp.fund_pay_permission, spp.contract_permission, spp.payment_permission
  1142. FROM ${this.ctx.service.subProjPermission.tableName} spp LEFT JOIN ${this.tableName} pa ON spp.uid = pa.id WHERE ` + filterSql + ' ORDER BY pa.company ASC, spp.uid DESC';
  1143. const result = await this.db.query(sql);
  1144. result.forEach(x => {
  1145. delete x.password;
  1146. delete x.backdoor_password;
  1147. });
  1148. return result;
  1149. }
  1150. async getSubProjectAccountListWithPermission(subProject, filter) {
  1151. const filterInfo = [{ filter: { spid: subProject.id }, tableName: 'spp' }];
  1152. if (filter) filterInfo.push({ filter, tableName: 'pa' });
  1153. const filterSql = this._getFilterSql(filterInfo);
  1154. const limit = this.ctx.pageSize ? this.ctx.pageSize : this.app.config.pageSize;
  1155. const offset = limit * (this.ctx.page - 1);
  1156. const sql = `SELECT pa.*, spp.id AS permission_id,
  1157. spp.file_permission, spp.budget_permission, spp.info_permission, spp.datacollect_permission, spp.fund_trans_permission, spp.fund_pay_permission, spp.contract_permission, spp.payment_permission
  1158. FROM ${this.ctx.service.subProjPermission.tableName} spp LEFT JOIN ${this.tableName} pa ON spp.uid = pa.id WHERE ` + filterSql + ' ORDER BY spp.uid DESC LIMIT ?, ?';
  1159. const result = await this.db.query(sql, [offset, limit]);
  1160. result.forEach(x => {
  1161. delete x.password;
  1162. delete x.backdoor_password;
  1163. });
  1164. return result;
  1165. }
  1166. async getUserUnitSign(uid) {
  1167. const userInfo = await this.getDataById(uid);
  1168. if (!userInfo || !userInfo.company) {
  1169. return [];
  1170. }
  1171. const userPermission = userInfo !== undefined && userInfo.permission !== '' ? JSON.parse(userInfo.permission) : null;
  1172. if (userPermission !== null && userPermission.other !== undefined && userPermission.other.indexOf('1') !== -1) {
  1173. return userInfo.unit_sign_path ? userInfo.unit_sign_path.split('&%&') : [];
  1174. }
  1175. const info = await this.ctx.service.constructionUnit.getDataByCondition({ pid: userInfo.project_id, name: userInfo.company });
  1176. if (!info || info.sign_permission === 0) {
  1177. return [];
  1178. }
  1179. return info.sign_path ? info.sign_path.split('&%&') : []; // 多个签章用&%&分隔
  1180. }
  1181. }
  1182. return ProjectAccount;
  1183. };