project_account.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. module.exports = app => {
  13. class ProjectAccount extends app.BaseService {
  14. /**
  15. * 构造函数
  16. *
  17. * @param {Object} ctx - egg全局变量
  18. * @return {void}
  19. */
  20. constructor(ctx) {
  21. super(ctx);
  22. this.tableName = 'project_account';
  23. }
  24. /**
  25. * 数据验证规则
  26. *
  27. * @param {String} scene - 场景
  28. * @return {Object} - 返回数据
  29. */
  30. rule(scene) {
  31. let rule = {};
  32. switch (scene) {
  33. case 'login':
  34. rule = {
  35. account: { type: 'string', required: true, min: 2 },
  36. project_password: { type: 'string', required: true, min: 4 },
  37. project: { type: 'string', required: true, min: 13 },
  38. };
  39. break;
  40. default:
  41. break;
  42. }
  43. return rule;
  44. }
  45. /**
  46. * 账号登录
  47. *
  48. * @param {Object} data - 表单post数据
  49. * @return {Boolean} - 返回登录结果
  50. */
  51. async accountLogin(data) {
  52. let result = false;
  53. try {
  54. // 验证数据
  55. const rule = this.rule('login');
  56. this.ctx.validate(rule, data);
  57. // 查找项目数据
  58. const projectData = await this.ctx.service.project.getProjectByCode(data.project.toString());
  59. if (projectData === null) {
  60. throw '不存在项目数据';
  61. }
  62. // 查找对应数据
  63. const accountData = await this.db.get(this.tableName, {
  64. account: data.account,
  65. project_id: projectData.id,
  66. });
  67. if (accountData === null) {
  68. throw '不存在对应用户数据';
  69. }
  70. // 判断密码
  71. if (accountData.is_admin === 1) {
  72. // 管理员则用sso通道判断
  73. const sso = new SSO(this.ctx);
  74. result = await sso.loginValid(data.account, data.project_password.toString());
  75. } else {
  76. // 加密密码
  77. const encryptPassword = crypto.createHmac('sha1', data.account).update(data.project_password)
  78. .digest().toString('base64');
  79. result = encryptPassword === accountData.password;
  80. }
  81. // 如果成功则更新登录时间
  82. if (result) {
  83. const updateData = {
  84. last_login: new Date().getTime() / 1000,
  85. };
  86. await this.update(updateData, { id: accountData.id });
  87. }
  88. } catch (error) {
  89. console.log(error);
  90. result = false;
  91. }
  92. return result;
  93. }
  94. }
  95. return ProjectAccount;
  96. };