project_account.js 22 KB

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