project_account.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. result = encryptPassword === accountData.password;
  150. // }
  151. } else if (loginType === 3) {
  152. // 查找项目数据
  153. const projectData = data.project;
  154. projectInfo = {
  155. id: projectData.id,
  156. name: projectData.name,
  157. userAccount: projectData.user_account,
  158. custom: projectData.custom,
  159. };
  160. // 查找对应数据
  161. accountData = data.accountData;
  162. projectList = await this.getProjectInfoByAccount(accountData.account);
  163. result = true;
  164. } else {
  165. // sso登录(演示版)
  166. const sso = new SSO(this.ctx);
  167. result = await sso.loginValid(data.username, data.password.toString());
  168. accountData.account = data.username;
  169. accountData.id = sso.accountID;
  170. }
  171. // 如果成功则更新登录时间
  172. if (result) {
  173. const currentTime = new Date().getTime() / 1000;
  174. // 加密token
  175. const sessionToken = crypto.createHmac('sha1', currentTime + '').update(accountData.account)
  176. .digest('hex').toString('base64');
  177. if (loginType === 2 || loginType === 3) {
  178. const updateData = {
  179. last_login: currentTime,
  180. session_token: sessionToken,
  181. };
  182. await this.update(updateData, { id: accountData.id });
  183. }
  184. // 存入session
  185. this.ctx.session.sessionUser = {
  186. account: accountData.account,
  187. name: accountData.name,
  188. accountId: accountData.id,
  189. loginTime: currentTime,
  190. is_admin: accountData.is_admin,
  191. sessionToken,
  192. loginType,
  193. // permission,
  194. // cooperation,
  195. };
  196. this.ctx.session.sessionProject = projectInfo;
  197. this.ctx.session.sessionProjectList = projectList;
  198. }
  199. } catch (error) {
  200. console.log(error);
  201. result = false;
  202. }
  203. return result;
  204. }
  205. /**
  206. * 根据项目id获取用户列表
  207. *
  208. * @param {Number} projectId - 项目id
  209. * @return {Array} - 返回用户数据
  210. */
  211. async getAccountByProjectId(projectId) {
  212. const condition = {
  213. columns: ['id', 'account', 'name', 'company', 'account_group', 'role', 'mobile', 'telephone', 'enable', 'permission', 'sign_path'],
  214. where: { project_id: projectId, is_admin: 0 },
  215. };
  216. const accountList = await this.getAllDataByCondition(condition);
  217. return accountList;
  218. }
  219. /**
  220. * 根据项目id获取所有类型用户列表
  221. *
  222. * @param {Number} projectId - 项目id
  223. * @return {Array} - 返回用户数据
  224. */
  225. async getAllAccountByProjectId(projectId) {
  226. const condition = {
  227. columns: ['id', 'account', 'name', 'company', 'account_group', 'role', 'mobile', 'telephone', 'enable', 'permission', 'sign_path'],
  228. where: { project_id: projectId},
  229. };
  230. const accountList = await this.getAllDataByCondition(condition);
  231. return accountList;
  232. }
  233. /**
  234. * 停用/启用
  235. *
  236. * @param {Number} accountId - 账号id
  237. * @return {Boolean} - 返回操作结果
  238. */
  239. async enableAccount(accountId) {
  240. let result = false;
  241. const accountData = await this.getDataByCondition({ id: accountId });
  242. if (accountData === null) {
  243. return result;
  244. }
  245. const changeStatus = accountData.enable === 1 ? 0 : 1;
  246. result = await this.update({ enable: changeStatus }, { id: accountId });
  247. return result;
  248. }
  249. /**
  250. * 根据账号id查找对应的项目数据
  251. *
  252. * @param {Number} account - 账号
  253. * @return {Array} - 返回数据
  254. */
  255. async getProjectInfoByAccount(account) {
  256. let column = ['p.name', 'p.id', 'p.user_account'];
  257. column = column.join(',');
  258. const sql = 'SELECT ' + column + ' FROM ' +
  259. '?? AS pa ' +
  260. 'LEFT JOIN ?? AS p ' +
  261. 'ON pa.`project_id` = p.`id` ' +
  262. 'WHERE pa.`account` = ? ' +
  263. 'GROUP BY pa.`project_id`;';
  264. const sqlParam = [this.tableName, this.ctx.service.project.tableName, account];
  265. const projectInfo = await this.db.query(sql, sqlParam);
  266. return projectInfo;
  267. }
  268. /**
  269. * 根据项目Id,用户名查找用户数据
  270. * @param {int} projectId - 项目id
  271. * @param {Object} name - 关键字
  272. * @param {int} type - 查询方式
  273. * @return {Object} 列表或单条数据
  274. */
  275. async getAccountInfoByName(projectId, name, type = 0) {
  276. this.initSqlBuilder();
  277. this.sqlBuilder.columns = ['id', 'name', 'company', 'role'];
  278. this.sqlBuilder.setAndWhere('project_id', {
  279. operate: '=',
  280. value: projectId,
  281. });
  282. this.sqlBuilder.setAndWhere('name', {
  283. operate: 'like',
  284. value: this.db.escape('%' + name + '%'),
  285. });
  286. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
  287. const info = type === 1 ? await this.db.query(sql, sqlParam) : await this.db.queryOne(sql, sqlParam);
  288. return info;
  289. }
  290. async getAccountInfoById(id) {
  291. this.initSqlBuilder();
  292. this.sqlBuilder.columns = ['id', 'name', 'company', 'role'];
  293. this.sqlBuilder.setAndWhere('id', {
  294. operate: '=',
  295. value: id,
  296. });
  297. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
  298. const info = await this.db.queryOne(sql, sqlParam);
  299. return info;
  300. }
  301. async getListByProjectId(columns = '', pid) {
  302. this.initSqlBuilder();
  303. this.sqlBuilder.columns = columns !== '' ? columns : ['id', 'account', 'name', 'company', 'role', 'mobile', 'auth_mobile', 'telephone', 'enable', 'is_admin', 'account_group'];
  304. this.sqlBuilder.setAndWhere('project_id', {
  305. value: pid,
  306. operate: '=',
  307. });
  308. return await this.getListWithBuilder();
  309. }
  310. /**
  311. * 修改用户数据
  312. *
  313. * @param {Object} data - post过来的数据
  314. * @return {Boolean} - 返回修改结果
  315. */
  316. async save(data) {
  317. if (data._csrf !== undefined) {
  318. delete data._csrf;
  319. }
  320. const id = data.id !== undefined ? parseInt(data.id) : 0;
  321. if (id > 0) {
  322. // 修改操作时
  323. delete data.create_time;
  324. data.id = id;
  325. } else {
  326. // 重名检测
  327. const accountData = await this.db.select(this.tableName, {
  328. where: {
  329. account: data.account,
  330. project_id: data.project_id,
  331. },
  332. });
  333. if (accountData.length > 0) {
  334. throw '已存在对应的帐户名';
  335. }
  336. // 加密密码
  337. data.password = crypto.createHmac('sha1', data.account).update(data.password)
  338. .digest().toString('base64');
  339. }
  340. const operate = id === 0 ? await this.db.insert(this.tableName, data) :
  341. await this.db.update(this.tableName, data);
  342. const result = operate.affectedRows > 0;
  343. return result;
  344. }
  345. /**
  346. * 修改账号资料
  347. *
  348. * @param {Object} data - post过来的数据
  349. * @return {Boolean} - 返回修改结果
  350. */
  351. async saveInfo(data, id) {
  352. if (data._csrf !== undefined) {
  353. delete data._csrf;
  354. }
  355. data.id = parseInt(id);
  356. const operate = await this.db.update(this.tableName, data);
  357. const result = operate.affectedRows > 0;
  358. if (result) {
  359. // 存入session
  360. this.ctx.session.sessionUser.name = data.name;
  361. }
  362. return result;
  363. }
  364. /**
  365. * 修改密码
  366. *
  367. * @param {Number} accountId - 账号id
  368. * @param {String} password - 旧密码
  369. * @param {String} newPassword - 新密码
  370. * @return {Boolean} - 返回修改结果
  371. */
  372. async modifyPassword(accountId, password, newPassword) {
  373. // 查找账号
  374. const accountData = await this.getDataByCondition({ id: accountId });
  375. if (accountData.password === undefined) {
  376. throw '不存在对应用户';
  377. }
  378. // 判断是否为sso账号,如果是则不能在此系统修改(后续通过接口修改?)
  379. if (accountData.password === 'SSO password') {
  380. throw 'SSO用户请到SSO系统修改密码';
  381. }
  382. // 加密密码
  383. const encryptPassword = crypto.createHmac('sha1', accountData.account).update(password)
  384. .digest().toString('base64');
  385. if (encryptPassword !== accountData.password) {
  386. throw '密码错误';
  387. }
  388. // 通过密码验证后修改数据
  389. const encryptNewPassword = crypto.createHmac('sha1', accountData.account).update(newPassword)
  390. .digest().toString('base64');
  391. const updateData = { id: accountId, password: encryptNewPassword };
  392. // const result = await this.save(updateData, accountId);
  393. const operate = await this.db.update(this.tableName, updateData);
  394. // 发送短信
  395. if (accountData.auth_mobile) {
  396. const sms = new SMS(this.ctx);
  397. const content = '【纵横计量支付】账号:' + accountData.account + ',密码重置为:' + newPassword;
  398. sms.send(accountData.auth_mobile, content);
  399. }
  400. const result = operate.affectedRows > 0;
  401. return result;
  402. }
  403. /**
  404. * 设置短信验证码
  405. *
  406. * @param {Number} accountId - 账号id
  407. * @param {String} mobile - 电话号码
  408. * @return {Boolean} - 设置结果
  409. */
  410. async setSMSCode(accountId, mobile) {
  411. const cacheKey = 'smsCode:' + accountId;
  412. const randString = this.ctx.helper.generateRandomString(6, 2);
  413. // 缓存15分钟(拼接电话,防止篡改)
  414. this.cache.set(cacheKey, randString + mobile, 'EX', 900);
  415. let result = false;
  416. // 发送短信
  417. try {
  418. const sms = new SMS(this.ctx);
  419. const content = '【纵横计量支付】验证码:' + randString + ',15分钟内有效。';
  420. result = await sms.send(mobile, content);
  421. } catch (error) {
  422. result = false;
  423. }
  424. return result;
  425. }
  426. /**
  427. * 绑定认证手机
  428. *
  429. * @param {Number} accountId - 账号id
  430. * @param {Object} data - post过来的数据
  431. * @param {Object} pid - 项目id
  432. * @return {Boolean} - 绑定结果
  433. */
  434. async bindMobile(accountId, data, pid) {
  435. const cacheKey = 'smsCode:' + accountId;
  436. const cacheCode = await this.cache.get(cacheKey);
  437. if (cacheCode === null || data.code === undefined || cacheCode !== (data.code + data.auth_mobile)) {
  438. throw '验证码错误!';
  439. }
  440. // 查找是否有重复的认证手机
  441. const accountData = await this.getDataByCondition({ project_id: pid, auth_mobile: data.auth_mobile });
  442. if (accountData !== null) {
  443. throw '此手机号码已被使用,请重新输入!';
  444. }
  445. const updateData = { id: accountId, auth_mobile: data.auth_mobile };
  446. // return this.save(updateData, accountId);
  447. const operate = await this.db.update(this.tableName, updateData);
  448. const result = operate.affectedRows > 0;
  449. return result;
  450. }
  451. /**
  452. * 重置密码
  453. *
  454. * @param {Number} accountId - 账号id
  455. * @param {String} password - 重置的密码
  456. * @return {Boolean} - 重置结果
  457. */
  458. async resetPassword(accountId, password) {
  459. // 初始化事务
  460. this.transaction = await this.db.beginTransaction();
  461. let result = false;
  462. try {
  463. // 查找对应账号数据
  464. const accountData = await this.getDataByCondition({ id: accountId });
  465. if (accountData.account === undefined) {
  466. throw '不存在对应账号';
  467. }
  468. // 加密密码
  469. const encryptPassword = crypto.createHmac('sha1', accountData.account).update(password)
  470. .digest().toString('base64');
  471. // 更新账号密码
  472. const sql = 'UPDATE ?? SET password=? WHERE id=? AND password != ?;';
  473. const sqlParam = [this.tableName, encryptPassword, accountId, 'SSO password'];
  474. const operate = await this.transaction.query(sql, sqlParam);
  475. result = operate.affectedRows > 0;
  476. if (!result) {
  477. throw '更新密码失败';
  478. }
  479. // 发送短信
  480. if (accountData.auth_mobile !== '') {
  481. const sms = new SMS(this.ctx);
  482. const content = '【纵横计量支付】账号:' + accountData.account + ',密码重置为:' + password;
  483. sms.send(accountData.auth_mobile, content);
  484. }
  485. this.transaction.commit();
  486. } catch (error) {
  487. this.transaction.rollback();
  488. }
  489. return result;
  490. }
  491. /**
  492. * 判断是否存在对应的账号
  493. *
  494. * @param {String} account - 账号名称
  495. * @param {Number} projectId - 项目id
  496. * @return {Boolean} - 返回是否存在
  497. */
  498. async isAccountExist(account, projectId) {
  499. const accountData = await this.db.get(this.tableName, { account, project_id: projectId });
  500. return accountData;
  501. }
  502. /**
  503. * 保存用户权限数据
  504. *
  505. * @param {Object} data - post过来的数据
  506. * @return {Boolean} - 返回权限修改结果
  507. */
  508. async permissionSave(id, data) {
  509. if (data._csrf !== undefined) {
  510. delete data._csrf;
  511. }
  512. const updateData = {
  513. id,
  514. };
  515. if (data.cooperation !== undefined && data.cooperation !== null) {
  516. updateData.cooperation = data.cooperation;
  517. delete data.cooperation;
  518. } else {
  519. updateData.cooperation = 0;
  520. }
  521. delete data.id;
  522. updateData.permission = JSON.stringify(data);
  523. const operate = await this.db.update(this.tableName, updateData);
  524. const result = operate.affectedRows > 0;
  525. return result;
  526. }
  527. /**
  528. * 短信通知类型设置
  529. *
  530. * @param {String} id - 账号id
  531. * @param {Number} data - 通知类型
  532. * @return {Boolean} - 返回修改结果
  533. */
  534. async smsTypeSet(id, data) {
  535. if (data._csrf !== undefined) {
  536. delete data._csrf;
  537. }
  538. const updateData = {
  539. id,
  540. sms_type: JSON.stringify(data),
  541. };
  542. const operate = await this.db.update(this.tableName, updateData);
  543. const result = operate.affectedRows > 0;
  544. return result;
  545. }
  546. }
  547. return ProjectAccount;
  548. };