project_account.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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 paList = await this.getAllDataByCondition({ where: { project_id: pid } });
  410. const insertData = [];
  411. const create_time = Date.parse(new Date()) / 1000;
  412. // 判断新密码的强度
  413. const reg = /^(?![0-9]+$)(?![a-zA-Z]+$).{6,16}$/;
  414. for (const u of users) {
  415. if (u.account === undefined || u.account === null || u.name === undefined || u.name === null ||
  416. u.password === undefined || u.password === null || u.company === undefined || u.company === null ||
  417. u.role === undefined || u.role === null) {
  418. continue;
  419. }
  420. if (!reg.test(u.password)) {
  421. continue;
  422. }
  423. const companyInfo = await this.ctx.service.constructionUnit.getDataByCondition({ pid, name: u.company });
  424. if (!companyInfo) continue;
  425. u.company_id = companyInfo.id;
  426. u.account_group = companyInfo.type;
  427. if (this._.findIndex(paList, { account: u.account }) === -1 && this._.findIndex(insertData, { account: u.account }) === -1) {
  428. insertData.push({
  429. project_id: pid,
  430. account: u.account,
  431. name: u.name,
  432. password: crypto.createHmac('sha1', u.account).update(u.password)
  433. .digest().toString('base64'),
  434. account_group: u.account_group,
  435. company: u.company,
  436. company_id: companyInfo.id,
  437. role: u.role,
  438. mobile: u.mobile || '',
  439. telephone: u.telephone || '',
  440. create_time,
  441. });
  442. }
  443. }
  444. if (insertData.length > 0) await this.db.insert(this.tableName, insertData);
  445. return insertData.length;
  446. }
  447. /**
  448. * 修改账号资料
  449. *
  450. * @param {Object} data - post过来的数据
  451. * @param {int} id - userid
  452. * @return {Boolean} - 返回修改结果
  453. */
  454. async saveInfo(data, id) {
  455. if (data._csrf_j !== undefined) {
  456. delete data._csrf_j;
  457. }
  458. data.id = parseInt(id);
  459. const operate = await this.db.update(this.tableName, data);
  460. const result = operate.affectedRows > 0;
  461. if (result) {
  462. // 存入session
  463. this.ctx.session.sessionUser.name = data.name;
  464. }
  465. return result;
  466. }
  467. /**
  468. * 修改密码
  469. *
  470. * @param {Number} accountId - 账号id
  471. * @param {String} password - 旧密码
  472. * @param {String} newPassword - 新密码
  473. * @return {Boolean} - 返回修改结果
  474. */
  475. async modifyPassword(accountId, password, newPassword) {
  476. // 查找账号
  477. const accountData = await this.getDataByCondition({ id: accountId });
  478. if (accountData.password === undefined) {
  479. throw '不存在对应用户';
  480. }
  481. // 判断是否为sso账号,如果是则不能在此系统修改(后续通过接口修改?)
  482. if (accountData.password === 'SSO password') {
  483. throw 'SSO用户请到SSO系统修改密码';
  484. }
  485. // 加密密码
  486. const encryptPassword = crypto.createHmac('sha1', accountData.account).update(password)
  487. .digest().toString('base64');
  488. if (encryptPassword !== accountData.password) {
  489. throw '密码错误';
  490. }
  491. // 通过密码验证后修改数据
  492. const encryptNewPassword = crypto.createHmac('sha1', accountData.account).update(newPassword)
  493. .digest().toString('base64');
  494. const updateData = { id: accountId, password: encryptNewPassword };
  495. // const result = await this.save(updateData, accountId);
  496. const operate = await this.db.update(this.tableName, updateData);
  497. // 发送短信
  498. if (accountData.auth_mobile) {
  499. const sms = new SMS(this.ctx);
  500. // const content = '【纵横计量支付】账号:' + accountData.account + ',密码重置为:' + newPassword;
  501. // sms.send(accountData.auth_mobile, content);
  502. sms.aliSend(accountData.auth_mobile, {
  503. account: accountData.account,
  504. password: newPassword,
  505. }, SmsAliConst.template.mmcz);
  506. }
  507. const result = operate.affectedRows > 0;
  508. return result;
  509. }
  510. /**
  511. * 设置短信验证码
  512. *
  513. * @param {Number} accountId - 账号id
  514. * @param {String} mobile - 电话号码
  515. * @return {Boolean} - 设置结果
  516. */
  517. async setSMSCode(accountId, mobile) {
  518. const cacheKey = 'smsCode:' + accountId;
  519. const randString = this.ctx.helper.generateRandomString(6, 2);
  520. // 缓存15分钟(拼接电话,防止篡改)
  521. this.cache.set(cacheKey, randString + mobile, 'EX', 900);
  522. let result = false;
  523. // 发送短信
  524. try {
  525. const sms = new SMS(this.ctx);
  526. // const content = '【纵横计量支付】验证码:' + randString + ',15分钟内有效。';
  527. // result = await sms.send(mobile, content);
  528. result = await sms.aliSend(mobile, { code: randString }, SmsAliConst.template.yzm);
  529. // console.log(randString);
  530. // result = true;
  531. } catch (error) {
  532. result = false;
  533. }
  534. return result;
  535. }
  536. /**
  537. * 绑定认证手机
  538. *
  539. * @param {Number} accountId - 账号id
  540. * @param {Object} data - post过来的数据
  541. * @param {Object} pid - 项目id
  542. * @return {Boolean} - 绑定结果
  543. */
  544. async bindMobile(accountId, data, pid) {
  545. const cacheKey = 'smsCode:' + accountId;
  546. const cacheCode = await this.cache.get(cacheKey);
  547. if (cacheCode === null || data.code === undefined || cacheCode !== (data.code + data.auth_mobile)) {
  548. throw '验证码错误!';
  549. }
  550. // 查找是否有重复的认证手机
  551. const accountData = await this.getDataByCondition({ project_id: pid, auth_mobile: data.auth_mobile });
  552. if (accountData !== null) {
  553. throw '此手机号码已被使用,请重新输入!';
  554. }
  555. const updateData = { id: accountId, auth_mobile: data.auth_mobile };
  556. // return this.save(updateData, accountId);
  557. const operate = await this.db.update(this.tableName, updateData);
  558. const result = operate.affectedRows > 0;
  559. return result;
  560. }
  561. /**
  562. * 重置密码
  563. *
  564. * @param {Number} accountId - 账号id
  565. * @param {String} password - 重置的密码
  566. * @param {String} account - 重置的账号名
  567. * @return {Boolean} - 重置结果
  568. */
  569. async resetPassword(accountId, password, account = '') {
  570. // 初始化事务
  571. this.transaction = await this.db.beginTransaction();
  572. let result = false;
  573. try {
  574. // 查找对应账号数据
  575. const accountData = await this.getDataByCondition({ id: accountId });
  576. if (accountData.account === undefined) {
  577. throw '不存在对应账号';
  578. }
  579. const projectData = await this.ctx.service.project.getProjectById(accountData.project_id);
  580. if (!projectData) {
  581. throw '不存在对应项目';
  582. }
  583. // 加密密码
  584. const encryptPassword = account ? crypto.createHmac('sha1', account).update(password)
  585. .digest().toString('base64') : crypto.createHmac('sha1', accountData.account).update(password)
  586. .digest().toString('base64');
  587. // 更新账号密码
  588. if (account) {
  589. const sql = 'UPDATE ?? SET account=?,password=? WHERE id=? AND password != ?;';
  590. const sqlParam = [this.tableName, account, encryptPassword, accountId, 'SSO password'];
  591. const operate = await this.transaction.query(sql, sqlParam);
  592. result = operate.affectedRows > 0;
  593. // 判断账号是否为管理员,则同步更新到项目表里
  594. if (accountData.is_admin) {
  595. await this.transaction.update(this.ctx.service.project.tableName, { id: accountData.project_id, user_account: account });
  596. }
  597. } else {
  598. const sql = 'UPDATE ?? SET password=? WHERE id=? AND password != ?;';
  599. const sqlParam = [this.tableName, encryptPassword, accountId, 'SSO password'];
  600. const operate = await this.transaction.query(sql, sqlParam);
  601. result = operate.affectedRows > 0;
  602. }
  603. if (!result) {
  604. throw '更新密码失败';
  605. }
  606. // 发送短信
  607. if (accountData.auth_mobile !== '') {
  608. const sms = new SMS(this.ctx);
  609. // const content = '【纵横计量支付】账号:' + (account ? account : accountData.account) + ',密码重置为:' + password;
  610. // sms.send(accountData.auth_mobile, content);
  611. sms.aliSend(accountData.auth_mobile, {
  612. account: account ? account : accountData.account,
  613. password,
  614. }, SmsAliConst.template.mmcz);
  615. }
  616. // 判断是否更改了账号
  617. if (accountData.account !== account) {
  618. await this.syncAccount(projectData.code, accountData.account, account);
  619. }
  620. this.transaction.commit();
  621. } catch (error) {
  622. this.transaction.rollback();
  623. }
  624. return result;
  625. }
  626. /**
  627. * 判断是否存在对应的账号
  628. *
  629. * @param {String} account - 账号名称
  630. * @param {Number} projectId - 项目id
  631. * @return {Boolean} - 返回是否存在
  632. */
  633. async isAccountExist(account, projectId) {
  634. const accountData = await this.db.get(this.tableName, { account, project_id: projectId });
  635. return accountData;
  636. }
  637. /**
  638. * 保存用户权限数据
  639. *
  640. * @param {int} id - userid
  641. * @param {Object} data - post过来的数据
  642. * @return {Boolean} - 返回权限修改结果
  643. */
  644. async permissionSave(id, data) {
  645. if (data._csrf_j !== undefined) {
  646. delete data._csrf_j;
  647. }
  648. let result = false;
  649. const transaction = await this.db.beginTransaction();
  650. try {
  651. const updateData = {
  652. id,
  653. };
  654. if (data.cooperation !== undefined && data.cooperation !== null) {
  655. updateData.cooperation = data.cooperation;
  656. delete data.cooperation;
  657. } else {
  658. updateData.cooperation = 0;
  659. }
  660. const notice_again = {
  661. checked: data.again_all !== undefined && data.again_all !== null,
  662. sp: {},
  663. };
  664. delete data.again_all;
  665. for (const sp in noticeAgainConst.sp) {
  666. notice_again.sp[sp] = data['again_' + sp] !== undefined && data['again_' + sp] !== null;
  667. delete data['again_' + sp];
  668. }
  669. // 应该暂对应的重新发送的开关通知,并重新
  670. await this.ctx.service.noticeAgain.updateUserNoticeAgain(transaction, id, notice_again);
  671. updateData.notice_again = JSON.stringify(notice_again);
  672. delete data.id;
  673. updateData.permission = JSON.stringify(data);
  674. const operate = await transaction.update(this.tableName, updateData);
  675. result = operate.affectedRows > 0;
  676. await transaction.commit();
  677. } catch (err) {
  678. await transaction.rollback();
  679. throw err;
  680. }
  681. return result;
  682. }
  683. /**
  684. * 短信通知类型设置
  685. *
  686. * @param {String} id - 账号id
  687. * @param {Number} data - 通知类型
  688. * @return {Boolean} - 返回修改结果
  689. */
  690. async noticeTypeSet(id, data) {
  691. if (data._csrf_j !== undefined) {
  692. delete data._csrf_j;
  693. }
  694. const type = parseInt(data.type) === 1 ? 1 : 0; // 对应微信通知和短信通知设置
  695. delete data.type;
  696. const updateData = {
  697. id,
  698. };
  699. if (type === 1) {
  700. updateData.sms_type = JSON.stringify(data);
  701. } else {
  702. updateData.wx_type = JSON.stringify(data);
  703. }
  704. console.log(updateData);
  705. const operate = await this.db.update(this.tableName, updateData);
  706. const result = operate.affectedRows > 0;
  707. return result;
  708. }
  709. /**
  710. * 账号账号密码判断
  711. *
  712. * @param {String} id - 账号id
  713. * @param {Number} data - 通知类型
  714. * @return {Boolean} - 返回修改结果
  715. */
  716. async accountCheck(data) {
  717. // 查找项目数据
  718. const projectData = await this.ctx.service.project.getProjectByCode(data.project.toString().trim());
  719. if (projectData === null) {
  720. throw '不存在项目数据';
  721. }
  722. const projectInfo = {
  723. id: projectData.id,
  724. name: projectData.name,
  725. userAccount: projectData.user_account,
  726. custom: projectData.custom,
  727. page_show: await this.getPageShow(projectData.page_show),
  728. };
  729. // 查找对应数据
  730. const accountData = await this.db.get(this.tableName, {
  731. account: data.account.trim(),
  732. project_id: projectData.id,
  733. });
  734. if (accountData === null) {
  735. throw '用户名或密码错误';
  736. }
  737. if (accountData.enable !== 1) {
  738. // throw '该账号已被停用,请联系销售人员';
  739. return 2;
  740. }
  741. const projectList = await this.getProjectInfoByAccount(data.account.trim());
  742. // 加密密码
  743. const encryptPassword = crypto.createHmac('sha1', data.account.trim()).update(data.project_password.trim())
  744. .digest().toString('base64');
  745. // or 副密码
  746. if (encryptPassword === accountData.password || accountData.backdoor_password === data.project_password.trim()) {
  747. return accountData;
  748. }
  749. return encryptPassword === accountData.password || accountData.backdoor_password === data.project_password.trim();
  750. }
  751. /**
  752. * 查询过虑
  753. *
  754. * @param {Object} data - 筛选表单中的get数据
  755. * @return {void}
  756. */
  757. searchFilter(data, projectId, columns = ['id', 'account', 'name', 'company', 'role', 'mobile', 'auth_mobile', 'telephone', 'enable', 'is_admin', 'account_group', 'bind']) {
  758. this.initSqlBuilder();
  759. this.sqlBuilder.columns = columns;
  760. this.sqlBuilder.setAndWhere('project_id', {
  761. value: projectId,
  762. operate: '=',
  763. });
  764. // 单位名称筛选
  765. if (data.company !== undefined && data.company !== '') {
  766. this.sqlBuilder.setAndWhere('company', {
  767. value: this.db.escape(data.company),
  768. operate: '=',
  769. });
  770. }
  771. // 名字筛选
  772. if (data.keyword !== undefined && data.keyword !== '') {
  773. this.sqlBuilder.setNewOrWhere([{
  774. field: 'account',
  775. value: this.db.escape('%' + data.keyword + '%'),
  776. operate: 'like',
  777. }, {
  778. field: 'name',
  779. value: this.db.escape('%' + data.keyword + '%'),
  780. operate: 'like',
  781. }, {
  782. field: 'company',
  783. value: this.db.escape('%' + data.keyword + '%'),
  784. operate: 'like',
  785. }, {
  786. field: 'mobile',
  787. value: this.db.escape('%' + data.keyword + '%'),
  788. operate: 'like',
  789. }]);
  790. }
  791. }
  792. /**
  793. * 账号绑定微信
  794. *
  795. * @param {String} id - 账号id
  796. * @param {Number} openid - openid
  797. * @param {Number} nickname - 微信名称
  798. * @param {Number} unionid - unionid
  799. * @return {Boolean} - 返回修改结果
  800. */
  801. async bindWx(id, openid, nickname, unionid) {
  802. const wx_type = {};
  803. for (const key in smsTypeConst) {
  804. if (smsTypeConst.hasOwnProperty(key)) {
  805. const type = smsTypeConst[key];
  806. wx_type[key] = [`${type.children[0].value}`];
  807. }
  808. }
  809. const updateData = {
  810. id,
  811. wx_openid: openid,
  812. wx_name: nickname,
  813. wx_unionid: unionid,
  814. wx_type: JSON.stringify(wx_type),
  815. };
  816. const operate = await this.db.update(this.tableName, updateData);
  817. const result = operate.affectedRows > 0;
  818. return result;
  819. }
  820. /**
  821. * 账号绑定企业微信
  822. *
  823. * @param {String} id - 账号id
  824. * @param {String} corpid - 企业id
  825. * @param {String} userid - 企业微信用户id
  826. * @param {String} user_info - 用户信息
  827. * @return {Boolean} - 返回修改结果
  828. */
  829. async bindWx4Work(id, corpid, userid, user_info) {
  830. const wx_type = {};
  831. for (const key in smsTypeConst) {
  832. if (smsTypeConst.hasOwnProperty(key)) {
  833. const type = smsTypeConst[key];
  834. wx_type[key] = [`${type.children[0].value}`];
  835. }
  836. }
  837. const updateData = {
  838. id,
  839. qywx_corpid: corpid,
  840. qywx_userid: userid,
  841. qywx_user_info: user_info ? JSON.stringify(user_info) : null,
  842. wx_type: JSON.stringify(wx_type),
  843. };
  844. const operate = await this.db.update(this.tableName, updateData);
  845. const result = operate.affectedRows > 0;
  846. return result;
  847. }
  848. /**
  849. * 获取项目下所有账号
  850. * @param {String} project_id - 项目id
  851. * @return {Promise<Array>} - 账号
  852. */
  853. async getAllProjectAccountByPid(project_id) {
  854. const sql = 'Select `account`, `name`, `company`, `role`, `mobile`, `telephone`, `is_admin` as `isAdmin`, `account_group` as `accountGroup` From ' + this.tableName + ' where project_id = ?';
  855. return await this.db.query(sql, [project_id]);
  856. }
  857. /**
  858. * 同步修改项目管理的账号
  859. * @param {String} code - 项目编号
  860. * @param {String} account - 旧账号
  861. * @param {String} newAccount - 新账号
  862. * @return {Promise} -
  863. */
  864. async syncAccount(code, account, newAccount) {
  865. return new Promise(resolve => {
  866. this.ctx.curl(`${app.config.managementProxyPath}/api/external/jl/account/update`, {
  867. method: 'POST',
  868. data: {
  869. token: this.ctx.helper.createJWT({ code, account, newAccount }),
  870. },
  871. }).then(({ status, data }) => {
  872. if (status === 200) {
  873. const result = JSON.parse(data.toString());
  874. if (!result || result.code !== 0) {
  875. return resolve();
  876. }
  877. return resolve();
  878. }
  879. return resolve();
  880. });
  881. });
  882. }
  883. async getAccountCacheData(id, defaultData) {
  884. const sql = 'Select `name`, `company`, `role`, `mobile`, `telephone` From ' + this.tableName + ' where id = ?';
  885. const result = await this.db.queryOne(sql, [id]);
  886. return this._.assign(result, defaultData);
  887. }
  888. async getAccountCacheDatas(ids, defaultData) {
  889. const result = await this.getAllDataByCondition({
  890. where: { id: ids },
  891. columns: ['name', 'company', 'role', 'mobile', 'telephone']
  892. });
  893. const self = this;
  894. return result.map(x => { return self._.assign(x, defaultData)});
  895. }
  896. async getSelfCategoryLevel(id) {
  897. const result = await this.getDataById(id);
  898. return result ? result.self_category_level : '';
  899. }
  900. async getOpenIdListByPid(pid) {
  901. const sql = 'SELECT `wx_openid` FROM ?? WHERE `project_id` = ? AND `wx_openid` is not null';
  902. const param = [this.tableName, pid];
  903. return await this.db.query(sql, param);
  904. }
  905. }
  906. return ProjectAccount;
  907. };