project_account.js 40 KB

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