project_account.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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: 13 },
  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. default:
  70. break;
  71. }
  72. return rule;
  73. }
  74. /**
  75. * 账号登录
  76. *
  77. * @param {Object} data - 表单post数据
  78. * @param {Number} loginType - 登录类型 1 | 2
  79. * @return {Boolean} - 返回登录结果
  80. */
  81. async accountLogin(data, loginType) {
  82. let result = false;
  83. try {
  84. // 验证数据
  85. const scene = loginType === 1 ? 'ssoLogin' : 'login';
  86. const rule = this.rule(scene);
  87. this.ctx.validate(rule, data);
  88. let accountData = {};
  89. let projectInfo = {};
  90. let projectList = [];
  91. let permission = '';
  92. if (loginType === 2) {
  93. // 查找项目数据
  94. const projectData = await this.ctx.service.project.getProjectByCode(data.project.toString());
  95. if (projectData === null) {
  96. throw '不存在项目数据';
  97. }
  98. projectInfo = {
  99. id: projectData.id,
  100. name: projectData.name,
  101. userAccount: projectData.user_account,
  102. };
  103. // 查找对应数据
  104. accountData = await this.db.get(this.tableName, {
  105. account: data.account,
  106. project_id: projectData.id,
  107. enable: 1,
  108. });
  109. if (accountData === null) {
  110. throw '不存在对应用户数据';
  111. }
  112. projectList = await this.getProjectInfoByAccount(data.account);
  113. // 判断密码
  114. if (accountData.is_admin === 1) {
  115. // 管理员则用sso通道判断
  116. const sso = new SSO(this.ctx);
  117. result = await sso.loginValid(data.account, data.project_password.toString());
  118. permission = 'all';
  119. } else {
  120. // 加密密码
  121. const encryptPassword = crypto.createHmac('sha1', data.account).update(data.project_password)
  122. .digest().toString('base64');
  123. result = encryptPassword === accountData.password;
  124. permission = accountData.permission;
  125. }
  126. } else {
  127. // sso登录(演示版)
  128. const sso = new SSO(this.ctx);
  129. result = await sso.loginValid(data.username, data.password.toString());
  130. accountData.account = data.username;
  131. accountData.id = sso.accountID;
  132. }
  133. // 如果成功则更新登录时间
  134. if (result) {
  135. const currentTime = new Date().getTime() / 1000;
  136. if (loginType === 2) {
  137. const updateData = {
  138. last_login: currentTime,
  139. };
  140. await this.update(updateData, { id: accountData.id });
  141. }
  142. // 加密token
  143. const sessionToken = crypto.createHmac('sha1', currentTime + '').update(accountData.account)
  144. .digest().toString('base64');
  145. // 存入session
  146. this.ctx.session.sessionUser = {
  147. account: accountData.account,
  148. name: accountData.name,
  149. accountId: accountData.id,
  150. loginTime: currentTime,
  151. sessionToken,
  152. loginType,
  153. permission,
  154. };
  155. this.ctx.session.sessionProject = projectInfo;
  156. this.ctx.session.sessionProjectList = projectList;
  157. }
  158. } catch (error) {
  159. console.log(error);
  160. result = false;
  161. }
  162. return result;
  163. }
  164. /**
  165. * 根据项目id获取用户列表
  166. *
  167. * @param {Number} projectId - 项目id
  168. * @return {Array} - 返回用户数据
  169. */
  170. async getAccountByProjectId(projectId) {
  171. const condition = {
  172. columns: ['id', 'account', 'name', 'company', 'role', 'mobile', 'telephone', 'enable', 'permission'],
  173. where: { project_id: projectId, is_admin: 0 },
  174. };
  175. const accountList = await this.getAllDataByCondition(condition);
  176. return accountList;
  177. }
  178. /**
  179. * 停用/启用
  180. *
  181. * @param {Number} accountId - 账号id
  182. * @return {Boolean} - 返回操作结果
  183. */
  184. async enableAccount(accountId) {
  185. let result = false;
  186. const accountData = await this.getDataByCondition({ id: accountId });
  187. if (accountData === null) {
  188. return result;
  189. }
  190. const changeStatus = accountData.enable === 1 ? 0 : 1;
  191. result = await this.update({ enable: changeStatus }, { id: accountId });
  192. return result;
  193. }
  194. /**
  195. * 根据账号id查找对应的项目数据
  196. *
  197. * @param {Number} account - 账号
  198. * @return {Array} - 返回数据
  199. */
  200. async getProjectInfoByAccount(account) {
  201. let column = ['p.name', 'p.id', 'p.user_account'];
  202. column = column.join(',');
  203. const sql = 'SELECT ' + column + ' FROM ' +
  204. '?? AS pa ' +
  205. 'LEFT JOIN ?? AS p ' +
  206. 'ON pa.`project_id` = p.`id` ' +
  207. 'WHERE pa.`account` = ? ' +
  208. 'GROUP BY pa.`project_id`;';
  209. const sqlParam = [this.tableName, this.ctx.service.project.tableName, account];
  210. const projectInfo = await this.db.query(sql, sqlParam);
  211. return projectInfo;
  212. }
  213. /**
  214. * 根据项目Id,用户名查找用户数据
  215. * @param projectId
  216. * @param name
  217. * @returns {Promise<*>}
  218. */
  219. async getAccountInfoByName(projectId, name) {
  220. this.initSqlBuilder();
  221. this.sqlBuilder.columns = ['id', 'name', 'company', 'role'];
  222. this.sqlBuilder.setAndWhere('project_id', {
  223. operate: '=',
  224. value: projectId,
  225. });
  226. this.sqlBuilder.setAndWhere('name', {
  227. operate: 'like',
  228. value: this.db.escape('%' + name + '%'),
  229. });
  230. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
  231. const info = await this.db.queryOne(sql, sqlParam);
  232. return info;
  233. }
  234. /**
  235. * 修改用户数据
  236. *
  237. * @param {Object} data - post过来的数据
  238. * @param {Number} accountId - 账号id
  239. * @return {Boolean} - 返回修改结果
  240. */
  241. async save(data, accountId) {
  242. if (data._csrf !== undefined) {
  243. delete data._csrf;
  244. }
  245. accountId = parseInt(accountId);
  246. accountId = isNaN(accountId) ? 0 : accountId;
  247. let result = false;
  248. if (accountId <= 0) {
  249. return result;
  250. }
  251. data.id = accountId;
  252. // 更新数据
  253. const operate = await this.db.update(this.tableName, data);
  254. result = operate.affectedRows > 0;
  255. return result;
  256. }
  257. /**
  258. * 修改密码
  259. *
  260. * @param {Number} accountId - 账号id
  261. * @param {String} password - 旧密码
  262. * @param {String} newPassword - 新密码
  263. * @return {Boolean} - 返回修改结果
  264. */
  265. async modifyPassword(accountId, password, newPassword) {
  266. // 查找账号
  267. const accountData = await this.getDataByCondition({ id: accountId });
  268. if (accountData.password === undefined) {
  269. throw '不存在对应用户';
  270. }
  271. // 判断是否为sso账号,如果是则不能在此系统修改(后续通过接口修改?)
  272. if (accountData.password === 'SSO password') {
  273. throw 'SSO用户请到SSO系统修改密码';
  274. }
  275. // 加密密码
  276. const encryptPassword = crypto.createHmac('sha1', accountData.account).update(password)
  277. .digest().toString('base64');
  278. if (encryptPassword !== accountData.password) {
  279. throw '密码错误';
  280. }
  281. // 通过密码验证后修改数据
  282. const encryptNewPassword = crypto.createHmac('sha1', accountData.account).update(newPassword)
  283. .digest().toString('base64');
  284. const updateData = { password: encryptNewPassword };
  285. const result = await this.save(updateData, accountId);
  286. return result;
  287. }
  288. /**
  289. * 设置短信验证码
  290. *
  291. * @param {Number} accountId - 账号id
  292. * @param {String} mobile - 电话号码
  293. * @return {Boolean} - 设置结果
  294. */
  295. async setSMSCode(accountId, mobile) {
  296. const cacheKey = 'smsCode:' + accountId;
  297. const randString = this.ctx.helper.generateRandomString(6, 2);
  298. // 缓存15分钟(拼接电话,防止篡改)
  299. this.cache.set(cacheKey, randString + mobile, 'EX', 900);
  300. let result = false;
  301. // 发送短信
  302. try {
  303. const sms = new SMS(this.ctx);
  304. const content = '【纵横计量支付】验证码:' + randString + ',15分钟有效。';
  305. result = await sms.send(mobile, content);
  306. } catch (error) {
  307. result = false;
  308. }
  309. return result;
  310. }
  311. /**
  312. * 绑定认证手机
  313. *
  314. * @param {Number} accountId - 账号id
  315. * @param {Object} data - post过来的数据
  316. * @return {Boolean} - 绑定结果
  317. */
  318. async bindMobile(accountId, data) {
  319. const cacheKey = 'smsCode:' + accountId;
  320. const cacheCode = await this.cache.get(cacheKey);
  321. if (cacheCode === null || data.code === undefined || cacheCode !== (data.code + data.auth_mobile)) {
  322. return false;
  323. }
  324. // 查找是否有重复的认证手机
  325. const accountData = await this.getDataByCondition({ auth_mobile: data.auth_mobile });
  326. if (accountData !== null) {
  327. throw '已存在对应的手机';
  328. }
  329. const updateData = { auth_mobile: data.auth_mobile };
  330. return this.save(updateData, accountId);
  331. }
  332. }
  333. return ProjectAccount;
  334. };