project_account.js 18 KB

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