project_account.js 21 KB

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