project_account.js 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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. return result;
  988. }
  989. async getSubProjectAccountListWithPermission(subProject, filter) {
  990. const filterInfo = [{ filter: { spid: subProject.id }, tableName: 'spp' }];
  991. if (filter) filterInfo.push({ filter, tableName: 'pa' });
  992. const filterSql = this._getFilterSql(filterInfo);
  993. const limit = this.ctx.pageSize ? this.ctx.pageSize : this.app.config.pageSize;
  994. const offset = limit * (this.ctx.page - 1);
  995. const sql = `SELECT pa.*, spp.id AS permission_id,
  996. 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
  997. 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 ?, ?';
  998. const result = await this.db.query(sql, [offset, limit]);
  999. return result;
  1000. }
  1001. }
  1002. return ProjectAccount;
  1003. };