project_account.js 36 KB

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