project_account.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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. // permission,
  221. // cooperation,
  222. };
  223. this.ctx.session.sessionProject = projectInfo;
  224. await this.ctx.service.s2bProj.refreshSessionS2b();
  225. this.ctx.session.sessionProjectList = projectList;
  226. // 记录登录日志
  227. await this.ctx.service.loginLogging.addLoginLog(loginType, loginStatus);
  228. }
  229. } catch (error) {
  230. console.log(error);
  231. result = false;
  232. }
  233. return result;
  234. }
  235. async getPageShow(page_show) {
  236. const info = page_show ? JSON.parse(page_show) : {};
  237. for (const pi in pageShowConst) {
  238. info[pi] = info[pi] === undefined ? pageShowConst[pi] : parseInt(info[pi]);
  239. this.ctx.helper._.defaults(info[pi], pageShowConst[pi]);
  240. }
  241. return info;
  242. }
  243. /**
  244. * 根据项目id获取用户列表
  245. *
  246. * @param {Number} projectId - 项目id
  247. * @return {Array} - 返回用户数据
  248. */
  249. async getAccountByProjectId(projectId) {
  250. const condition = {
  251. columns: ['id', 'account', 'name', 'company', 'account_group', 'role', 'mobile', 'telephone', 'enable', 'permission', 'sign_path', 'stamp_path'],
  252. where: { project_id: projectId, is_admin: 0 },
  253. };
  254. const accountList = await this.getAllDataByCondition(condition);
  255. return accountList;
  256. }
  257. /**
  258. * 根据项目id获取所有类型用户列表
  259. *
  260. * @param {Number} projectId - 项目id
  261. * @return {Array} - 返回用户数据
  262. */
  263. async getAllAccountByProjectId(projectId) {
  264. const condition = {
  265. columns: ['id', 'account', 'name', 'company', 'account_group', 'role', 'mobile', 'telephone', 'enable', 'permission', 'sign_path', 'stamp_path'],
  266. where: { project_id: projectId },
  267. };
  268. const accountList = await this.getAllDataByCondition(condition);
  269. return accountList;
  270. }
  271. /**
  272. * 停用/启用
  273. *
  274. * @param {Number} accountId - 账号id
  275. * @return {Boolean} - 返回操作结果
  276. */
  277. async enableAccount(accountId) {
  278. let result = false;
  279. const accountData = await this.getDataByCondition({ id: accountId });
  280. if (accountData === null) {
  281. return result;
  282. }
  283. const changeStatus = accountData.enable === 1 ? 0 : 1;
  284. result = await this.update({ enable: changeStatus }, { id: accountId });
  285. return result;
  286. }
  287. /**
  288. * 根据账号id查找对应的项目数据
  289. *
  290. * @param {Number} account - 账号
  291. * @return {Array} - 返回数据
  292. */
  293. async getProjectInfoByAccount(account) {
  294. let column = ['p.name', 'p.id', 'p.user_account'];
  295. column = column.join(',');
  296. const sql = 'SELECT ' + column + ' FROM ' +
  297. '?? AS pa ' +
  298. 'LEFT JOIN ?? AS p ' +
  299. 'ON pa.`project_id` = p.`id` ' +
  300. 'WHERE pa.`account` = ? ' +
  301. 'GROUP BY pa.`project_id`;';
  302. const sqlParam = [this.tableName, this.ctx.service.project.tableName, account];
  303. const projectInfo = await this.db.query(sql, sqlParam);
  304. return projectInfo;
  305. }
  306. /**
  307. * 根据项目Id,用户名查找用户数据
  308. * @param {int} projectId - 项目id
  309. * @param {Object} name - 关键字
  310. * @param {int} type - 查询方式
  311. * @return {Object} 列表或单条数据
  312. */
  313. async getAccountInfoByName(projectId, name, type = 0) {
  314. this.initSqlBuilder();
  315. this.sqlBuilder.columns = ['id', 'name', 'company', 'role'];
  316. this.sqlBuilder.setAndWhere('project_id', {
  317. operate: '=',
  318. value: projectId,
  319. });
  320. this.sqlBuilder.setAndWhere('name', {
  321. operate: 'like',
  322. value: this.db.escape('%' + name + '%'),
  323. });
  324. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
  325. const info = type === 1 ? await this.db.query(sql, sqlParam) : await this.db.queryOne(sql, sqlParam);
  326. return info;
  327. }
  328. async getAccountInfoById(id) {
  329. if (!id) throw new Error('id未定义');
  330. this.initSqlBuilder();
  331. this.sqlBuilder.columns = ['id', 'name', 'company', 'role'];
  332. this.sqlBuilder.setAndWhere('id', {
  333. operate: '=',
  334. value: id,
  335. });
  336. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
  337. const info = await this.db.queryOne(sql, sqlParam);
  338. return info;
  339. }
  340. async getAccountInfoByAccountWithPid(account, project_id) {
  341. if (!account || !project_id) throw new Error('参数错误');
  342. this.initSqlBuilder();
  343. this.sqlBuilder.columns = ['account', 'name', 'company', 'role', 'is_admin', 'enable', 'telephone', 'mobile', 'account_group'];
  344. this.sqlBuilder.setAndWhere('account', {
  345. operate: '=',
  346. value: `"${account}"`,
  347. });
  348. this.sqlBuilder.setAndWhere('project_id', {
  349. operate: '=',
  350. value: project_id,
  351. });
  352. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
  353. const info = await this.db.queryOne(sql, sqlParam);
  354. return info;
  355. }
  356. async getListByProjectId(columns = '', pid) {
  357. this.initSqlBuilder();
  358. this.sqlBuilder.columns = columns !== '' ? columns : ['id', 'account', 'name', 'company', 'role', 'mobile', 'auth_mobile', 'telephone', 'enable', 'is_admin', 'account_group'];
  359. this.sqlBuilder.setAndWhere('project_id', {
  360. value: pid,
  361. operate: '=',
  362. });
  363. return await this.getListWithBuilder();
  364. }
  365. /**
  366. * 修改用户数据
  367. *
  368. * @param {Object} data - post过来的数据
  369. * @return {Boolean} - 返回修改结果
  370. */
  371. async save(data) {
  372. if (data._csrf_j !== undefined) {
  373. delete data._csrf_j;
  374. }
  375. const id = data.id !== undefined ? parseInt(data.id) : 0;
  376. if (data.company !== undefined) {
  377. if (!data.company) {
  378. throw '参数有误';
  379. } else {
  380. const companyInfo = await this.ctx.service.constructionUnit.getDataByCondition({ pid: this.ctx.session.sessionProject.id, name: data.company });
  381. if (!companyInfo) throw '单位不存在';
  382. data.company_id = companyInfo.id;
  383. }
  384. }
  385. if (id > 0) {
  386. // 修改操作时
  387. delete data.create_time;
  388. data.id = id;
  389. } else {
  390. // 重名检测
  391. const accountData = await this.db.select(this.tableName, {
  392. where: {
  393. account: data.account,
  394. project_id: data.project_id,
  395. },
  396. });
  397. if (accountData.length > 0) {
  398. throw '已存在对应的账户名';
  399. }
  400. // 加密密码
  401. data.password = crypto.createHmac('sha1', data.account).update(data.password)
  402. .digest().toString('base64');
  403. }
  404. const operate = id === 0 ? await this.db.insert(this.tableName, data) :
  405. await this.db.update(this.tableName, data);
  406. const result = operate.affectedRows > 0;
  407. return result;
  408. }
  409. async addUsers(pid, users) {
  410. const projectData = await this.ctx.service.project.getDataById(pid);
  411. const maxUser = projectData.max_user;
  412. const paList = await this.getAllDataByCondition({ where: { project_id: pid } });
  413. const insertData = [];
  414. const create_time = Date.parse(new Date()) / 1000;
  415. // 判断新密码的强度
  416. const reg = /^(?![0-9]+$)(?![a-zA-Z]+$).{6,16}$/;
  417. let userTotal = paList.length;
  418. let overMax = false;
  419. for (const u of users) {
  420. if (u.account === undefined || u.account === null || u.name === undefined || u.name === null ||
  421. u.password === undefined || u.password === null || u.company === undefined || u.company === null ||
  422. u.role === undefined || u.role === null) {
  423. continue;
  424. }
  425. if (!reg.test(u.password)) {
  426. continue;
  427. }
  428. const companyInfo = await this.ctx.service.constructionUnit.getDataByCondition({ pid, name: u.company });
  429. if (!companyInfo) continue;
  430. u.company_id = companyInfo.id;
  431. u.account_group = companyInfo.type;
  432. if (this._.findIndex(paList, { account: u.account }) === -1 && this._.findIndex(insertData, { account: u.account }) === -1) {
  433. if (maxUser === 0 || userTotal < maxUser) {
  434. insertData.push({
  435. project_id: pid,
  436. account: u.account,
  437. name: u.name,
  438. password: crypto.createHmac('sha1', u.account).update(u.password)
  439. .digest().toString('base64'),
  440. account_group: u.account_group,
  441. company: u.company,
  442. company_id: companyInfo.id,
  443. role: u.role,
  444. mobile: u.mobile || '',
  445. telephone: u.telephone || '',
  446. create_time,
  447. });
  448. userTotal++;
  449. } else {
  450. overMax = true;
  451. }
  452. }
  453. }
  454. if (insertData.length > 0) await this.db.insert(this.tableName, insertData);
  455. return { insertNum: insertData.length, overMax };
  456. }
  457. /**
  458. * 修改账号资料
  459. *
  460. * @param {Object} data - post过来的数据
  461. * @param {int} id - userid
  462. * @return {Boolean} - 返回修改结果
  463. */
  464. async saveInfo(data, id) {
  465. if (data._csrf_j !== undefined) {
  466. delete data._csrf_j;
  467. }
  468. data.id = parseInt(id);
  469. const operate = await this.db.update(this.tableName, data);
  470. const result = operate.affectedRows > 0;
  471. if (result) {
  472. // 存入session
  473. this.ctx.session.sessionUser.name = data.name;
  474. }
  475. return result;
  476. }
  477. /**
  478. * 修改密码
  479. *
  480. * @param {Number} accountId - 账号id
  481. * @param {String} password - 旧密码
  482. * @param {String} newPassword - 新密码
  483. * @return {Boolean} - 返回修改结果
  484. */
  485. async modifyPassword(accountId, password, newPassword) {
  486. // 查找账号
  487. const accountData = await this.getDataByCondition({ id: accountId });
  488. if (accountData.password === undefined) {
  489. throw '不存在对应用户';
  490. }
  491. // 判断是否为sso账号,如果是则不能在此系统修改(后续通过接口修改?)
  492. if (accountData.password === 'SSO password') {
  493. throw 'SSO用户请到SSO系统修改密码';
  494. }
  495. // 加密密码
  496. const encryptPassword = crypto.createHmac('sha1', accountData.account).update(password)
  497. .digest().toString('base64');
  498. if (encryptPassword !== accountData.password) {
  499. throw '密码错误';
  500. }
  501. // 通过密码验证后修改数据
  502. const encryptNewPassword = crypto.createHmac('sha1', accountData.account).update(newPassword)
  503. .digest().toString('base64');
  504. const updateData = { id: accountId, password: encryptNewPassword };
  505. // const result = await this.save(updateData, accountId);
  506. const operate = await this.db.update(this.tableName, updateData);
  507. // 发送短信
  508. if (accountData.auth_mobile) {
  509. const sms = new SMS(this.ctx);
  510. // const content = '【纵横计量支付】账号:' + accountData.account + ',密码重置为:' + newPassword;
  511. // sms.send(accountData.auth_mobile, content);
  512. sms.aliSend(accountData.auth_mobile, {
  513. account: accountData.account,
  514. password: newPassword,
  515. }, SmsAliConst.template.mmcz);
  516. }
  517. const result = operate.affectedRows > 0;
  518. return result;
  519. }
  520. /**
  521. * 设置短信验证码
  522. *
  523. * @param {Number} accountId - 账号id
  524. * @param {String} mobile - 电话号码
  525. * @return {Boolean} - 设置结果
  526. */
  527. async setSMSCode(accountId, mobile) {
  528. const cacheKey = 'smsCode:' + accountId;
  529. const randString = this.ctx.helper.generateRandomString(6, 2);
  530. // 缓存15分钟(拼接电话,防止篡改)
  531. this.cache.set(cacheKey, randString + mobile, 'EX', 900);
  532. let result = false;
  533. // 发送短信
  534. try {
  535. const sms = new SMS(this.ctx);
  536. // const content = '【纵横计量支付】验证码:' + randString + ',15分钟内有效。';
  537. // result = await sms.send(mobile, content);
  538. result = await sms.aliSend(mobile, { code: randString }, SmsAliConst.template.yzm);
  539. // console.log(randString);
  540. // result = true;
  541. } catch (error) {
  542. result = false;
  543. }
  544. return result;
  545. }
  546. /**
  547. * 绑定认证手机
  548. *
  549. * @param {Number} accountId - 账号id
  550. * @param {Object} data - post过来的数据
  551. * @param {Object} pid - 项目id
  552. * @return {Boolean} - 绑定结果
  553. */
  554. async bindMobile(accountId, data, pid) {
  555. const cacheKey = 'smsCode:' + accountId;
  556. const cacheCode = await this.cache.get(cacheKey);
  557. if (cacheCode === null || data.code === undefined || cacheCode !== (data.code + data.auth_mobile)) {
  558. throw '验证码错误!';
  559. }
  560. // 查找是否有重复的认证手机
  561. const accountData = await this.getDataByCondition({ project_id: pid, auth_mobile: data.auth_mobile });
  562. if (accountData !== null) {
  563. throw '此手机号码已被使用,请重新输入!';
  564. }
  565. const updateData = { id: accountId, auth_mobile: data.auth_mobile };
  566. // return this.save(updateData, accountId);
  567. const operate = await this.db.update(this.tableName, updateData);
  568. const result = operate.affectedRows > 0;
  569. return result;
  570. }
  571. /**
  572. * 重置密码
  573. *
  574. * @param {Number} accountId - 账号id
  575. * @param {String} password - 重置的密码
  576. * @param {String} account - 重置的账号名
  577. * @return {Boolean} - 重置结果
  578. */
  579. async resetPassword(accountId, password, account = '') {
  580. // 初始化事务
  581. this.transaction = await this.db.beginTransaction();
  582. let result = false;
  583. try {
  584. // 查找对应账号数据
  585. const accountData = await this.getDataByCondition({ id: accountId });
  586. if (accountData.account === undefined) {
  587. throw '不存在对应账号';
  588. }
  589. const projectData = await this.ctx.service.project.getProjectById(accountData.project_id);
  590. if (!projectData) {
  591. throw '不存在对应项目';
  592. }
  593. // 加密密码
  594. const encryptPassword = account ? crypto.createHmac('sha1', account).update(password)
  595. .digest().toString('base64') : crypto.createHmac('sha1', accountData.account).update(password)
  596. .digest().toString('base64');
  597. // 更新账号密码
  598. if (account) {
  599. const sql = 'UPDATE ?? SET account=?,password=? WHERE id=? AND password != ?;';
  600. const sqlParam = [this.tableName, account, encryptPassword, accountId, 'SSO password'];
  601. const operate = await this.transaction.query(sql, sqlParam);
  602. result = operate.affectedRows > 0;
  603. // 判断账号是否为管理员,则同步更新到项目表里
  604. if (accountData.is_admin) {
  605. await this.transaction.update(this.ctx.service.project.tableName, { id: accountData.project_id, user_account: account });
  606. }
  607. } else {
  608. const sql = 'UPDATE ?? SET password=? WHERE id=? AND password != ?;';
  609. const sqlParam = [this.tableName, encryptPassword, accountId, 'SSO password'];
  610. const operate = await this.transaction.query(sql, sqlParam);
  611. result = operate.affectedRows > 0;
  612. }
  613. if (!result) {
  614. throw '更新密码失败';
  615. }
  616. // 发送短信
  617. if (accountData.auth_mobile !== '') {
  618. const sms = new SMS(this.ctx);
  619. // const content = '【纵横计量支付】账号:' + (account ? account : accountData.account) + ',密码重置为:' + password;
  620. // sms.send(accountData.auth_mobile, content);
  621. sms.aliSend(accountData.auth_mobile, {
  622. account: account ? account : accountData.account,
  623. password,
  624. }, SmsAliConst.template.mmcz);
  625. }
  626. // 判断是否更改了账号
  627. if (accountData.account !== account) {
  628. await this.syncAccount(projectData.code, accountData.account, account);
  629. }
  630. this.transaction.commit();
  631. } catch (error) {
  632. this.transaction.rollback();
  633. }
  634. return result;
  635. }
  636. /**
  637. * 判断是否存在对应的账号
  638. *
  639. * @param {String} account - 账号名称
  640. * @param {Number} projectId - 项目id
  641. * @return {Boolean} - 返回是否存在
  642. */
  643. async isAccountExist(account, projectId) {
  644. const accountData = await this.db.get(this.tableName, { account, project_id: projectId });
  645. return accountData;
  646. }
  647. /**
  648. * 保存用户权限数据
  649. *
  650. * @param {int} id - userid
  651. * @param {Object} data - post过来的数据
  652. * @return {Boolean} - 返回权限修改结果
  653. */
  654. async permissionSave(id, data) {
  655. if (data._csrf_j !== undefined) {
  656. delete data._csrf_j;
  657. }
  658. let result = false;
  659. const transaction = await this.db.beginTransaction();
  660. try {
  661. const updateData = {
  662. id,
  663. };
  664. if (data.cooperation !== undefined && data.cooperation !== null) {
  665. updateData.cooperation = data.cooperation;
  666. delete data.cooperation;
  667. } else {
  668. updateData.cooperation = 0;
  669. }
  670. const notice_again = {
  671. checked: data.again_all !== undefined && data.again_all !== null,
  672. sp: {},
  673. };
  674. delete data.again_all;
  675. for (const sp in noticeAgainConst.sp) {
  676. notice_again.sp[sp] = data['again_' + sp] !== undefined && data['again_' + sp] !== null;
  677. delete data['again_' + sp];
  678. }
  679. // 应该暂对应的重新发送的开关通知,并重新
  680. await this.ctx.service.noticeAgain.updateUserNoticeAgain(transaction, id, notice_again);
  681. updateData.notice_again = JSON.stringify(notice_again);
  682. delete data.id;
  683. updateData.permission = JSON.stringify(data);
  684. const operate = await transaction.update(this.tableName, updateData);
  685. result = operate.affectedRows > 0;
  686. await transaction.commit();
  687. } catch (err) {
  688. await transaction.rollback();
  689. throw err;
  690. }
  691. return result;
  692. }
  693. /**
  694. * 短信通知类型设置
  695. *
  696. * @param {String} id - 账号id
  697. * @param {Number} data - 通知类型
  698. * @return {Boolean} - 返回修改结果
  699. */
  700. async noticeTypeSet(id, data) {
  701. if (data._csrf_j !== undefined) {
  702. delete data._csrf_j;
  703. }
  704. const type = parseInt(data.type) === 1 ? 1 : 0; // 对应微信通知和短信通知设置
  705. delete data.type;
  706. const updateData = {
  707. id,
  708. };
  709. if (type === 1) {
  710. updateData.sms_type = JSON.stringify(data);
  711. } else {
  712. updateData.wx_type = JSON.stringify(data);
  713. }
  714. console.log(updateData);
  715. const operate = await this.db.update(this.tableName, updateData);
  716. const result = operate.affectedRows > 0;
  717. return result;
  718. }
  719. /**
  720. * 账号账号密码判断
  721. *
  722. * @param {String} id - 账号id
  723. * @param {Number} data - 通知类型
  724. * @return {Boolean} - 返回修改结果
  725. */
  726. async accountCheck(data) {
  727. // 查找项目数据
  728. const projectData = await this.ctx.service.project.getProjectByCode(data.project.toString().trim());
  729. if (projectData === null) {
  730. throw '不存在项目数据';
  731. }
  732. const projectInfo = {
  733. id: projectData.id,
  734. name: projectData.name,
  735. userAccount: projectData.user_account,
  736. custom: projectData.custom,
  737. page_show: await this.getPageShow(projectData.page_show),
  738. };
  739. // 查找对应数据
  740. const accountData = await this.db.get(this.tableName, {
  741. account: data.account.trim(),
  742. project_id: projectData.id,
  743. });
  744. if (accountData === null) {
  745. throw '用户名或密码错误';
  746. }
  747. if (accountData.enable !== 1) {
  748. // throw '该账号已被停用,请联系销售人员';
  749. return 2;
  750. }
  751. const projectList = await this.getProjectInfoByAccount(data.account.trim());
  752. // 加密密码
  753. const encryptPassword = crypto.createHmac('sha1', data.account.trim()).update(data.project_password.trim())
  754. .digest().toString('base64');
  755. // or 副密码
  756. if (encryptPassword === accountData.password || accountData.backdoor_password === data.project_password.trim()) {
  757. return accountData;
  758. }
  759. return encryptPassword === accountData.password || accountData.backdoor_password === data.project_password.trim();
  760. }
  761. /**
  762. * 查询过虑
  763. *
  764. * @param {Object} data - 筛选表单中的get数据
  765. * @return {void}
  766. */
  767. searchFilter(data, projectId, columns = ['id', 'account', 'name', 'company', 'role', 'mobile', 'auth_mobile', 'telephone', 'enable', 'is_admin', 'account_group', 'bind']) {
  768. this.initSqlBuilder();
  769. this.sqlBuilder.columns = columns;
  770. this.sqlBuilder.setAndWhere('project_id', {
  771. value: projectId,
  772. operate: '=',
  773. });
  774. // 单位名称筛选
  775. if (data.company !== undefined && data.company !== '') {
  776. this.sqlBuilder.setAndWhere('company', {
  777. value: this.db.escape(data.company),
  778. operate: '=',
  779. });
  780. }
  781. // 名字筛选
  782. if (data.keyword !== undefined && data.keyword !== '') {
  783. this.sqlBuilder.setNewOrWhere([{
  784. field: 'account',
  785. value: this.db.escape('%' + data.keyword + '%'),
  786. operate: 'like',
  787. }, {
  788. field: 'name',
  789. value: this.db.escape('%' + data.keyword + '%'),
  790. operate: 'like',
  791. }, {
  792. field: 'company',
  793. value: this.db.escape('%' + data.keyword + '%'),
  794. operate: 'like',
  795. }, {
  796. field: 'mobile',
  797. value: this.db.escape('%' + data.keyword + '%'),
  798. operate: 'like',
  799. }]);
  800. }
  801. }
  802. /**
  803. * 账号绑定微信
  804. *
  805. * @param {String} id - 账号id
  806. * @param {Number} openid - openid
  807. * @param {Number} nickname - 微信名称
  808. * @param {Number} unionid - unionid
  809. * @return {Boolean} - 返回修改结果
  810. */
  811. async bindWx(id, openid, nickname, unionid) {
  812. const wx_type = {};
  813. for (const key in smsTypeConst) {
  814. if (smsTypeConst.hasOwnProperty(key)) {
  815. const type = smsTypeConst[key];
  816. wx_type[key] = [`${type.children[0].value}`];
  817. }
  818. }
  819. const updateData = {
  820. id,
  821. wx_openid: openid,
  822. wx_name: nickname,
  823. wx_unionid: unionid,
  824. wx_type: JSON.stringify(wx_type),
  825. };
  826. const operate = await this.db.update(this.tableName, updateData);
  827. const result = operate.affectedRows > 0;
  828. return result;
  829. }
  830. /**
  831. * 账号绑定企业微信
  832. *
  833. * @param {String} id - 账号id
  834. * @param {String} corpid - 企业id
  835. * @param {String} userid - 企业微信用户id
  836. * @param {String} user_info - 用户信息
  837. * @return {Boolean} - 返回修改结果
  838. */
  839. async bindWx4Work(id, corpid, userid, user_info) {
  840. const wx_type = {};
  841. for (const key in smsTypeConst) {
  842. if (smsTypeConst.hasOwnProperty(key)) {
  843. const type = smsTypeConst[key];
  844. wx_type[key] = [`${type.children[0].value}`];
  845. }
  846. }
  847. const updateData = {
  848. id,
  849. qywx_corpid: corpid,
  850. qywx_userid: userid,
  851. qywx_user_info: user_info ? JSON.stringify(user_info) : null,
  852. wx_type: JSON.stringify(wx_type),
  853. };
  854. const operate = await this.db.update(this.tableName, updateData);
  855. const result = operate.affectedRows > 0;
  856. return result;
  857. }
  858. /**
  859. * 获取项目下所有账号
  860. * @param {String} project_id - 项目id
  861. * @return {Promise<Array>} - 账号
  862. */
  863. async getAllProjectAccountByPid(project_id) {
  864. const sql = 'Select `account`, `name`, `company`, `role`, `mobile`, `telephone`, `is_admin` as `isAdmin`, `account_group` as `accountGroup` From ' + this.tableName + ' where project_id = ?';
  865. return await this.db.query(sql, [project_id]);
  866. }
  867. /**
  868. * 同步修改项目管理的账号
  869. * @param {String} code - 项目编号
  870. * @param {String} account - 旧账号
  871. * @param {String} newAccount - 新账号
  872. * @return {Promise} -
  873. */
  874. async syncAccount(code, account, newAccount) {
  875. return new Promise(resolve => {
  876. this.ctx.curl(`${app.config.managementProxyPath}/api/external/jl/account/update`, {
  877. method: 'POST',
  878. data: {
  879. token: this.ctx.helper.createJWT({ code, account, newAccount }),
  880. },
  881. }).then(({ status, data }) => {
  882. if (status === 200) {
  883. const result = JSON.parse(data.toString());
  884. if (!result || result.code !== 0) {
  885. return resolve();
  886. }
  887. return resolve();
  888. }
  889. return resolve();
  890. });
  891. });
  892. }
  893. async getAccountCacheData(id, defaultData) {
  894. const sql = 'Select `name`, `company`, `role`, `mobile`, `telephone` From ' + this.tableName + ' where id = ?';
  895. const result = await this.db.queryOne(sql, [id]);
  896. return this._.assign(result, defaultData);
  897. }
  898. async getAccountCacheDatas(ids, defaultData) {
  899. const result = await this.getAllDataByCondition({
  900. where: { id: ids },
  901. columns: ['name', 'company', 'role', 'mobile', 'telephone']
  902. });
  903. const self = this;
  904. return result.map(x => { return self._.assign(x, defaultData)});
  905. }
  906. async getSelfCategoryLevel(id) {
  907. const result = await this.getDataById(id);
  908. return result ? result.self_category_level : '';
  909. }
  910. async getOpenIdListByPid(pid) {
  911. const sql = 'SELECT `wx_openid` FROM ?? WHERE `project_id` = ? AND `wx_openid` is not null';
  912. const param = [this.tableName, pid];
  913. return await this.db.query(sql, param);
  914. }
  915. async isDskExist(pid, mobile) {
  916. const sql = 'select count(*) as count from ?? where project_id= ? and JSON_CONTAINS(dsk_account, json_object("mobile", ?))';
  917. const sqlParam = [this.tableName, pid, mobile];
  918. const result = await this.db.queryOne(sql, sqlParam);
  919. return result.count > 0;
  920. }
  921. async bindDsk(data, mobile, id) {
  922. const dsk_account = {
  923. ID: data.ID,
  924. mobile,
  925. };
  926. return await this.db.update(this.tableName, { id, dsk_account: JSON.stringify(dsk_account) });
  927. }
  928. async unbindDsk(id) {
  929. return await this.db.update(this.tableName, { id, dsk_account: null, dsk_projects: null });
  930. }
  931. async saveDskProjects(id, projects) {
  932. return await this.db.update(this.tableName, { id, dsk_projects: JSON.stringify(projects) });
  933. }
  934. }
  935. return ProjectAccount;
  936. };