'use strict'; /** * 项目账号数据模型 * * @author CaiAoLin * @date 2017/11/16 * @version */ // 加密类 const crypto = require('crypto'); const SSO = require('../lib/sso'); module.exports = app => { class ProjectAccount extends app.BaseService { /** * 构造函数 * * @param {Object} ctx - egg全局变量 * @return {void} */ constructor(ctx) { super(ctx); this.tableName = 'project_account'; } /** * 数据验证规则 * * @param {String} scene - 场景 * @return {Object} - 返回数据 */ rule(scene) { let rule = {}; switch (scene) { case 'login': rule = { account: { type: 'string', required: true, min: 2 }, project_password: { type: 'string', required: true, min: 4 }, project: { type: 'string', required: true, min: 13 }, }; break; default: break; } return rule; } /** * 账号登录 * * @param {Object} data - 表单post数据 * @return {Boolean} - 返回登录结果 */ async accountLogin(data) { let result = false; try { // 验证数据 const rule = this.rule('login'); this.ctx.validate(rule, data); // 查找项目数据 const projectData = await this.ctx.service.project.getProjectByCode(data.project.toString()); if (projectData === null) { throw '不存在项目数据'; } // 查找对应数据 const accountData = await this.db.get(this.tableName, { account: data.account, project_id: projectData.id, }); if (accountData === null) { throw '不存在对应用户数据'; } // 判断密码 if (accountData.is_admin === 1) { // 管理员则用sso通道判断 const sso = new SSO(this.ctx); result = await sso.loginValid(data.account, data.project_password.toString()); } else { // 加密密码 const encryptPassword = crypto.createHmac('sha1', data.account).update(data.project_password) .digest().toString('base64'); result = encryptPassword === accountData.password; } // 如果成功则更新登录时间 if (result) { const updateData = { last_login: new Date().getTime() / 1000, }; await this.update(updateData, { id: accountData.id }); } } catch (error) { console.log(error); result = false; } return result; } } return ProjectAccount; };