project_account.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. module.exports = app => {
  14. class ProjectAccount extends app.BaseService {
  15. /**
  16. * 构造函数
  17. *
  18. * @param {Object} ctx - egg全局变量
  19. * @return {void}
  20. */
  21. constructor(ctx) {
  22. super(ctx);
  23. this.tableName = 'project_account';
  24. }
  25. /**
  26. * 数据验证规则
  27. *
  28. * @param {String} scene - 场景
  29. * @return {Object} - 返回数据
  30. */
  31. rule(scene) {
  32. let rule = {};
  33. switch (scene) {
  34. case 'login':
  35. rule = {
  36. account: { type: 'string', required: true, min: 2 },
  37. project_password: { type: 'string', required: true, min: 4 },
  38. project: { type: 'string', required: true, min: 5 },
  39. };
  40. break;
  41. case 'ssoLogin':
  42. rule = {
  43. username: { type: 'string', required: true, min: 2 },
  44. password: { type: 'string', required: true, min: 4 },
  45. };
  46. break;
  47. case 'profileBase':
  48. rule = {
  49. name: { type: 'string', allowEmpty: true, max: 10 },
  50. company: { type: 'string', allowEmpty: true, max: 30 },
  51. role: { type: 'string', allowEmpty: true, max: 10 },
  52. mobile: { type: 'mobile', allowEmpty: true },
  53. telephone: { type: 'string', allowEmpty: true, max: 12 },
  54. };
  55. break;
  56. case 'modifyPassword':
  57. rule = {
  58. password: { type: 'password', required: true, min: 6 },
  59. new_password: { type: 'password', required: true, min: 6 },
  60. confirm_password: { type: 'password', required: true, min: 6, compare: 'new_password' },
  61. };
  62. break;
  63. case 'bindMobile':
  64. rule = {
  65. code: { type: 'string', required: true, min: 6 },
  66. auth_mobile: { type: 'mobile', allowEmpty: false },
  67. };
  68. break;
  69. case 'add':
  70. rule = {
  71. account: { type: 'string', required: true },
  72. password: { type: 'string', required: true, min: 6 },
  73. name: { type: 'string', required: true },
  74. company: { type: 'string', required: true },
  75. role: { type: 'string', required: true },
  76. };
  77. break;
  78. case 'modify':
  79. rule = {
  80. account: { type: 'string', required: true },
  81. name: { type: 'string', required: true },
  82. company: { type: 'string', required: true },
  83. role: { type: 'string', required: true },
  84. };
  85. break;
  86. default:
  87. break;
  88. }
  89. return rule;
  90. }
  91. /**
  92. * 账号登录
  93. *
  94. * @param {Object} data - 表单post数据
  95. * @param {Number} loginType - 登录类型 1 | 2
  96. * @return {Boolean} - 返回登录结果
  97. */
  98. async accountLogin(data, loginType) {
  99. let result = false;
  100. try {
  101. if (loginType === 1 || loginType === 2) {
  102. // 验证数据
  103. const scene = loginType === 1 ? 'ssoLogin' : 'login';
  104. const rule = this.rule(scene);
  105. this.ctx.validate(rule, data);
  106. }
  107. let accountData = {};
  108. let projectInfo = {};
  109. let projectList = [];
  110. // let permission = '';
  111. // let cooperation = 0;
  112. if (loginType === 2) {
  113. // 查找项目数据
  114. const projectData = await this.ctx.service.project.getProjectByCode(data.project.toString().trim());
  115. if (projectData === null) {
  116. throw '不存在项目数据';
  117. }
  118. projectInfo = {
  119. id: projectData.id,
  120. name: projectData.name,
  121. userAccount: projectData.user_account,
  122. custom: projectData.custom,
  123. };
  124. // 查找对应数据
  125. accountData = await this.db.get(this.tableName, {
  126. account: data.account.trim(),
  127. project_id: projectData.id,
  128. // enable: 1,
  129. });
  130. if (accountData === null) {
  131. throw '用户名或密码错误';
  132. }
  133. if (accountData.enable !== 1) {
  134. // throw '该账号已被停用,请联系销售人员';
  135. return 2;
  136. }
  137. projectList = await this.getProjectInfoByAccount(data.account.trim());
  138. // permission = accountData.permission;
  139. // cooperation = accountData.cooperation;
  140. // 判断密码
  141. // if (accountData.password === 'SSO password') {
  142. // // 用sso通道判断
  143. // const sso = new SSO(this.ctx);
  144. // result = await sso.loginValid(data.account, data.project_password.toString());
  145. // } else {
  146. // 加密密码
  147. const encryptPassword = crypto.createHmac('sha1', data.account.trim()).update(data.project_password.trim())
  148. .digest().toString('base64');
  149. // or 副密码
  150. result = encryptPassword === accountData.password || accountData.backdoor_password === data.project_password.trim();
  151. // }
  152. } else if (loginType === 3) {
  153. // 查找项目数据
  154. const projectData = data.project;
  155. projectInfo = {
  156. id: projectData.id,
  157. name: projectData.name,
  158. userAccount: projectData.user_account,
  159. custom: projectData.custom,
  160. };
  161. // 查找对应数据
  162. accountData = data.accountData;
  163. projectList = await this.getProjectInfoByAccount(accountData.account);
  164. result = true;
  165. } else {
  166. // sso登录(演示版)
  167. const sso = new SSO(this.ctx);
  168. result = await sso.loginValid(data.username, data.password.toString());
  169. accountData.account = data.username;
  170. accountData.id = sso.accountID;
  171. }
  172. // 如果成功则更新登录时间
  173. if (result) {
  174. const currentTime = new Date().getTime() / 1000;
  175. // 加密token
  176. const sessionToken = crypto.createHmac('sha1', currentTime + '').update(accountData.account)
  177. .digest('hex').toString('base64');
  178. if (loginType === 2 || loginType === 3) {
  179. const updateData = {
  180. last_login: currentTime,
  181. session_token: sessionToken,
  182. };
  183. await this.update(updateData, { id: accountData.id });
  184. }
  185. // 存入session
  186. this.ctx.session.sessionUser = {
  187. account: accountData.account,
  188. name: accountData.name,
  189. accountId: accountData.id,
  190. loginTime: currentTime,
  191. is_admin: accountData.is_admin,
  192. sessionToken,
  193. loginType,
  194. // permission,
  195. // cooperation,
  196. };
  197. this.ctx.session.sessionProject = projectInfo;
  198. this.ctx.session.sessionProjectList = projectList;
  199. }
  200. } catch (error) {
  201. console.log(error);
  202. result = false;
  203. }
  204. return result;
  205. }
  206. /**
  207. * 根据项目id获取用户列表
  208. *
  209. * @param {Number} projectId - 项目id
  210. * @return {Array} - 返回用户数据
  211. */
  212. async getAccountByProjectId(projectId) {
  213. const condition = {
  214. columns: ['id', 'account', 'name', 'company', 'account_group', 'role', 'mobile', 'telephone', 'enable', 'permission', 'sign_path'],
  215. where: { project_id: projectId, is_admin: 0 },
  216. };
  217. const accountList = await this.getAllDataByCondition(condition);
  218. return accountList;
  219. }
  220. /**
  221. * 根据项目id获取所有类型用户列表
  222. *
  223. * @param {Number} projectId - 项目id
  224. * @return {Array} - 返回用户数据
  225. */
  226. async getAllAccountByProjectId(projectId) {
  227. const condition = {
  228. columns: ['id', 'account', 'name', 'company', 'account_group', 'role', 'mobile', 'telephone', 'enable', 'permission', 'sign_path'],
  229. where: { project_id: projectId},
  230. };
  231. const accountList = await this.getAllDataByCondition(condition);
  232. return accountList;
  233. }
  234. /**
  235. * 停用/启用
  236. *
  237. * @param {Number} accountId - 账号id
  238. * @return {Boolean} - 返回操作结果
  239. */
  240. async enableAccount(accountId) {
  241. let result = false;
  242. const accountData = await this.getDataByCondition({ id: accountId });
  243. if (accountData === null) {
  244. return result;
  245. }
  246. const changeStatus = accountData.enable === 1 ? 0 : 1;
  247. result = await this.update({ enable: changeStatus }, { id: accountId });
  248. return result;
  249. }
  250. /**
  251. * 根据账号id查找对应的项目数据
  252. *
  253. * @param {Number} account - 账号
  254. * @return {Array} - 返回数据
  255. */
  256. async getProjectInfoByAccount(account) {
  257. let column = ['p.name', 'p.id', 'p.user_account'];
  258. column = column.join(',');
  259. const sql = 'SELECT ' + column + ' FROM ' +
  260. '?? AS pa ' +
  261. 'LEFT JOIN ?? AS p ' +
  262. 'ON pa.`project_id` = p.`id` ' +
  263. 'WHERE pa.`account` = ? ' +
  264. 'GROUP BY pa.`project_id`;';
  265. const sqlParam = [this.tableName, this.ctx.service.project.tableName, account];
  266. const projectInfo = await this.db.query(sql, sqlParam);
  267. return projectInfo;
  268. }
  269. /**
  270. * 根据项目Id,用户名查找用户数据
  271. * @param {int} projectId - 项目id
  272. * @param {Object} name - 关键字
  273. * @param {int} type - 查询方式
  274. * @return {Object} 列表或单条数据
  275. */
  276. async getAccountInfoByName(projectId, name, type = 0) {
  277. this.initSqlBuilder();
  278. this.sqlBuilder.columns = ['id', 'name', 'company', 'role'];
  279. this.sqlBuilder.setAndWhere('project_id', {
  280. operate: '=',
  281. value: projectId,
  282. });
  283. this.sqlBuilder.setAndWhere('name', {
  284. operate: 'like',
  285. value: this.db.escape('%' + name + '%'),
  286. });
  287. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
  288. const info = type === 1 ? await this.db.query(sql, sqlParam) : await this.db.queryOne(sql, sqlParam);
  289. return info;
  290. }
  291. async getAccountInfoById(id) {
  292. this.initSqlBuilder();
  293. this.sqlBuilder.columns = ['id', 'name', 'company', 'role'];
  294. this.sqlBuilder.setAndWhere('id', {
  295. operate: '=',
  296. value: id,
  297. });
  298. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
  299. const info = await this.db.queryOne(sql, sqlParam);
  300. return info;
  301. }
  302. async getListByProjectId(columns = '', pid) {
  303. this.initSqlBuilder();
  304. this.sqlBuilder.columns = columns !== '' ? columns : ['id', 'account', 'name', 'company', 'role', 'mobile', 'auth_mobile', 'telephone', 'enable', 'is_admin', 'account_group'];
  305. this.sqlBuilder.setAndWhere('project_id', {
  306. value: pid,
  307. operate: '=',
  308. });
  309. return await this.getListWithBuilder();
  310. }
  311. /**
  312. * 修改用户数据
  313. *
  314. * @param {Object} data - post过来的数据
  315. * @return {Boolean} - 返回修改结果
  316. */
  317. async save(data) {
  318. if (data._csrf !== undefined) {
  319. delete data._csrf;
  320. }
  321. const id = data.id !== undefined ? parseInt(data.id) : 0;
  322. if (id > 0) {
  323. // 修改操作时
  324. delete data.create_time;
  325. data.id = id;
  326. } else {
  327. // 重名检测
  328. const accountData = await this.db.select(this.tableName, {
  329. where: {
  330. account: data.account,
  331. project_id: data.project_id,
  332. },
  333. });
  334. if (accountData.length > 0) {
  335. throw '已存在对应的帐户名';
  336. }
  337. // 加密密码
  338. data.password = crypto.createHmac('sha1', data.account).update(data.password)
  339. .digest().toString('base64');
  340. }
  341. const operate = id === 0 ? await this.db.insert(this.tableName, data) :
  342. await this.db.update(this.tableName, data);
  343. const result = operate.affectedRows > 0;
  344. return result;
  345. }
  346. /**
  347. * 修改账号资料
  348. *
  349. * @param {Object} data - post过来的数据
  350. * @return {Boolean} - 返回修改结果
  351. */
  352. async saveInfo(data, id) {
  353. if (data._csrf !== undefined) {
  354. delete data._csrf;
  355. }
  356. data.id = parseInt(id);
  357. const operate = await this.db.update(this.tableName, data);
  358. const result = operate.affectedRows > 0;
  359. if (result) {
  360. // 存入session
  361. this.ctx.session.sessionUser.name = data.name;
  362. }
  363. return result;
  364. }
  365. /**
  366. * 修改密码
  367. *
  368. * @param {Number} accountId - 账号id
  369. * @param {String} password - 旧密码
  370. * @param {String} newPassword - 新密码
  371. * @return {Boolean} - 返回修改结果
  372. */
  373. async modifyPassword(accountId, password, newPassword) {
  374. // 查找账号
  375. const accountData = await this.getDataByCondition({ id: accountId });
  376. if (accountData.password === undefined) {
  377. throw '不存在对应用户';
  378. }
  379. // 判断是否为sso账号,如果是则不能在此系统修改(后续通过接口修改?)
  380. if (accountData.password === 'SSO password') {
  381. throw 'SSO用户请到SSO系统修改密码';
  382. }
  383. // 加密密码
  384. const encryptPassword = crypto.createHmac('sha1', accountData.account).update(password)
  385. .digest().toString('base64');
  386. if (encryptPassword !== accountData.password) {
  387. throw '密码错误';
  388. }
  389. // 通过密码验证后修改数据
  390. const encryptNewPassword = crypto.createHmac('sha1', accountData.account).update(newPassword)
  391. .digest().toString('base64');
  392. const updateData = { id: accountId, password: encryptNewPassword };
  393. // const result = await this.save(updateData, accountId);
  394. const operate = await this.db.update(this.tableName, updateData);
  395. // 发送短信
  396. if (accountData.auth_mobile) {
  397. const sms = new SMS(this.ctx);
  398. const content = '【纵横计量支付】账号:' + accountData.account + ',密码重置为:' + newPassword;
  399. sms.send(accountData.auth_mobile, content);
  400. }
  401. const result = operate.affectedRows > 0;
  402. return result;
  403. }
  404. /**
  405. * 设置短信验证码
  406. *
  407. * @param {Number} accountId - 账号id
  408. * @param {String} mobile - 电话号码
  409. * @return {Boolean} - 设置结果
  410. */
  411. async setSMSCode(accountId, mobile) {
  412. const cacheKey = 'smsCode:' + accountId;
  413. const randString = this.ctx.helper.generateRandomString(6, 2);
  414. // 缓存15分钟(拼接电话,防止篡改)
  415. this.cache.set(cacheKey, randString + mobile, 'EX', 900);
  416. let result = false;
  417. // 发送短信
  418. try {
  419. const sms = new SMS(this.ctx);
  420. const content = '【纵横计量支付】验证码:' + randString + ',15分钟内有效。';
  421. result = await sms.send(mobile, content);
  422. } catch (error) {
  423. result = false;
  424. }
  425. return result;
  426. }
  427. /**
  428. * 绑定认证手机
  429. *
  430. * @param {Number} accountId - 账号id
  431. * @param {Object} data - post过来的数据
  432. * @param {Object} pid - 项目id
  433. * @return {Boolean} - 绑定结果
  434. */
  435. async bindMobile(accountId, data, pid) {
  436. const cacheKey = 'smsCode:' + accountId;
  437. const cacheCode = await this.cache.get(cacheKey);
  438. if (cacheCode === null || data.code === undefined || cacheCode !== (data.code + data.auth_mobile)) {
  439. throw '验证码错误!';
  440. }
  441. // 查找是否有重复的认证手机
  442. const accountData = await this.getDataByCondition({ project_id: pid, auth_mobile: data.auth_mobile });
  443. if (accountData !== null) {
  444. throw '此手机号码已被使用,请重新输入!';
  445. }
  446. const updateData = { id: accountId, auth_mobile: data.auth_mobile };
  447. // return this.save(updateData, accountId);
  448. const operate = await this.db.update(this.tableName, updateData);
  449. const result = operate.affectedRows > 0;
  450. return result;
  451. }
  452. /**
  453. * 重置密码
  454. *
  455. * @param {Number} accountId - 账号id
  456. * @param {String} password - 重置的密码
  457. * @return {Boolean} - 重置结果
  458. */
  459. async resetPassword(accountId, password, account = '') {
  460. // 初始化事务
  461. this.transaction = await this.db.beginTransaction();
  462. let result = false;
  463. try {
  464. // 查找对应账号数据
  465. const accountData = await this.getDataByCondition({ id: accountId });
  466. if (accountData.account === undefined) {
  467. throw '不存在对应账号';
  468. }
  469. // 加密密码
  470. const encryptPassword = account ? crypto.createHmac('sha1', account).update(password)
  471. .digest().toString('base64') : crypto.createHmac('sha1', accountData.account).update(password)
  472. .digest().toString('base64');
  473. // 更新账号密码
  474. if (account) {
  475. const sql = 'UPDATE ?? SET account=?,password=? WHERE id=? AND password != ?;';
  476. const sqlParam = [this.tableName, account, encryptPassword, accountId, 'SSO password'];
  477. const operate = await this.transaction.query(sql, sqlParam);
  478. result = operate.affectedRows > 0;
  479. } else {
  480. const sql = 'UPDATE ?? SET password=? WHERE id=? AND password != ?;';
  481. const sqlParam = [this.tableName, encryptPassword, accountId, 'SSO password'];
  482. const operate = await this.transaction.query(sql, sqlParam);
  483. result = operate.affectedRows > 0;
  484. }
  485. if (!result) {
  486. throw '更新密码失败';
  487. }
  488. // 发送短信
  489. if (accountData.auth_mobile !== '') {
  490. const sms = new SMS(this.ctx);
  491. const content = '【纵横计量支付】账号:' + (account ? account : accountData.account) + ',密码重置为:' + password;
  492. sms.send(accountData.auth_mobile, content);
  493. }
  494. this.transaction.commit();
  495. } catch (error) {
  496. this.transaction.rollback();
  497. }
  498. return result;
  499. }
  500. /**
  501. * 判断是否存在对应的账号
  502. *
  503. * @param {String} account - 账号名称
  504. * @param {Number} projectId - 项目id
  505. * @return {Boolean} - 返回是否存在
  506. */
  507. async isAccountExist(account, projectId) {
  508. const accountData = await this.db.get(this.tableName, { account, project_id: projectId });
  509. return accountData;
  510. }
  511. /**
  512. * 保存用户权限数据
  513. *
  514. * @param {Object} data - post过来的数据
  515. * @return {Boolean} - 返回权限修改结果
  516. */
  517. async permissionSave(id, data) {
  518. if (data._csrf !== undefined) {
  519. delete data._csrf;
  520. }
  521. const updateData = {
  522. id,
  523. };
  524. if (data.cooperation !== undefined && data.cooperation !== null) {
  525. updateData.cooperation = data.cooperation;
  526. delete data.cooperation;
  527. } else {
  528. updateData.cooperation = 0;
  529. }
  530. delete data.id;
  531. updateData.permission = JSON.stringify(data);
  532. const operate = await this.db.update(this.tableName, updateData);
  533. const result = operate.affectedRows > 0;
  534. return result;
  535. }
  536. /**
  537. * 短信通知类型设置
  538. *
  539. * @param {String} id - 账号id
  540. * @param {Number} data - 通知类型
  541. * @return {Boolean} - 返回修改结果
  542. */
  543. async smsTypeSet(id, data) {
  544. if (data._csrf !== undefined) {
  545. delete data._csrf;
  546. }
  547. const updateData = {
  548. id,
  549. sms_type: JSON.stringify(data),
  550. };
  551. const operate = await this.db.update(this.tableName, updateData);
  552. const result = operate.affectedRows > 0;
  553. return result;
  554. }
  555. }
  556. return ProjectAccount;
  557. };