project_account.js 47 KB

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