project_account.js 37 KB

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