project_account.js 12 KB

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