123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104 |
- 'use strict';
- /**
- * 项目账号数据模型
- *
- * @author CaiAoLin
- * @date 2017/11/16
- * @version
- */
- // 加密类
- const crypto = require('crypto');
- const SSO = require('../lib/sso');
- const SMS = require('../lib/sms');
- const DSK = require('../lib/dsk');
- const SmsAliConst = require('../const/sms_alitemplate');
- const loginWay = require('../const/setting').loginWay;
- const smsTypeConst = require('../const/sms_type').type;
- const pageShowConst = require('../const/page_show').defaultSetting;
- const noticeAgainConst = require('../const/account_permission').noticeAgain;
- 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: 5 },
- };
- break;
- case 'ssoLogin':
- rule = {
- username: { type: 'string', required: true, min: 2 },
- password: { type: 'string', required: true, min: 4 },
- };
- break;
- case 'profileBase':
- rule = {
- name: { type: 'string', allowEmpty: true, max: 10 },
- company: { type: 'string', allowEmpty: true, max: 30 },
- role: { type: 'string', allowEmpty: true, max: 10 },
- mobile: { type: 'mobile', allowEmpty: true },
- telephone: { type: 'string', allowEmpty: true, max: 12 },
- };
- break;
- case 'modifyPassword':
- rule = {
- password: { type: 'password', required: true, min: 6 },
- new_password: { type: 'password', required: true, min: 6, max: 16, format: /^(?![0-9]+$)(?![a-zA-Z]+$).{6,16}$/ },
- confirm_password: { type: 'password', required: true, min: 6, max: 16, compare: 'new_password' },
- };
- break;
- case 'bindMobile':
- rule = {
- code: { type: 'string', required: true, min: 6 },
- auth_mobile: { type: 'mobile', allowEmpty: false },
- };
- break;
- case 'add':
- rule = {
- account: { type: 'string', required: true },
- password: { type: 'string', required: true, min: 6, max: 16, format: /^(?![0-9]+$)(?![a-zA-Z]+$).{6,16}$/ },
- name: { type: 'string', required: true },
- company: { type: 'string', required: true },
- role: { type: 'string', required: true },
- };
- break;
- case 'modify':
- rule = {
- account: { type: 'string', required: true },
- name: { type: 'string', required: true },
- company: { type: 'string', required: true },
- role: { type: 'string', required: true },
- };
- break;
- default:
- break;
- }
- return rule;
- }
- /**
- * 账号登录
- *
- * @param {Object} data - 表单post数据
- * @param {Number} loginType - 登录类型 1(sso登录) | 2(正常或副密码登录) | 3(接口登录或微信登录)
- * @return {Boolean} - 返回登录结果
- */
- async accountLogin(data, loginType) {
- let result = false;
- try {
- if (loginType === 1 || loginType === 2) {
- // 验证数据
- const scene = loginType === 1 ? 'ssoLogin' : 'login';
- const rule = this.rule(scene);
- this.ctx.validate(rule, data);
- }
- let accountData = {};
- let projectInfo = {};
- let projectList = [];
- let loginStatus = 0;
- // let permission = '';
- // let cooperation = 0;
- if (loginType === 2) {
- // 查找项目数据
- const projectData = await this.ctx.service.project.getProjectByCode(data.project.toString().trim());
- if (projectData === null) {
- throw '不存在项目数据';
- }
- projectInfo = {
- id: projectData.id,
- name: projectData.name,
- code: projectData.code,
- userAccount: projectData.user_account,
- custom: projectData.custom,
- page_show: await this.getPageShow(projectData.page_show),
- customType: projectData.customType,
- };
- // 查找对应数据
- accountData = await this.db.get(this.tableName, {
- account: data.account.trim(),
- project_id: projectData.id,
- // enable: 1,
- });
- if (accountData === null) {
- throw '用户名或密码错误';
- }
- if (accountData.enable !== 1) {
- // throw '该账号已被停用,请联系销售人员';
- return 2;
- }
- if (accountData.invalid_time) {
- const date = this.ctx.moment(accountData.invalid_time, 'YYYY-MM-DD').toDate();
- if (date < new Date()) return 2;
- }
- projectList = await this.getProjectInfoByAccount(data.account.trim());
- // permission = accountData.permission;
- // cooperation = accountData.cooperation;
- // 判断密码
- // if (accountData.password === 'SSO password') {
- // // 用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.trim()).update(data.project_password.trim())
- .digest().toString('base64');
- // or 副密码
- result = encryptPassword === accountData.password || accountData.backdoor_password === data.project_password.trim();
- // 区分登录方式, 0:正常登录,1:副密码
- if (encryptPassword === accountData.password) {
- loginStatus = 0;
- } else if (accountData.backdoor_password === data.project_password.trim()) {
- loginStatus = 1;
- }
- // dev-qa下默认副密码登录,规避验证码
- if (this.ctx.app.config.is_debug) loginStatus = 1;
- // }
- } else if (loginType === 3) {
- // 查找项目数据
- const projectData = data.project;
- projectInfo = {
- id: projectData.id,
- code: projectData.code,
- name: projectData.name,
- userAccount: projectData.user_account,
- custom: projectData.custom,
- dataCollect: projectData.data_collect,
- page_show: await this.getPageShow(projectData.page_show),
- };
- // 查找对应数据
- accountData = data.accountData;
- projectList = await this.getProjectInfoByAccount(accountData.account);
- result = true;
- } else {
- // sso登录(演示版)
- const sso = new SSO(this.ctx);
- result = await sso.loginValid(data.username, data.password.toString());
- accountData.account = data.username;
- accountData.id = sso.accountID;
- }
- // 如果成功则更新登录时间
- if (result) {
- const currentTime = new Date().getTime() / 1000;
- // 加密token
- const sessionToken = crypto.createHmac('sha1', currentTime + '').update(accountData.account)
- .digest('hex').toString('base64');
- if (loginType === 2 || loginType === 3) {
- const updateData = {
- last_login: currentTime,
- session_token: sessionToken,
- };
- await this.update(updateData, { id: accountData.id });
- }
- // 存入session
- this.ctx.session.sessionUser = {
- account: accountData.account,
- name: accountData.name,
- accountId: accountData.id,
- loginTime: currentTime,
- is_admin: accountData.is_admin,
- sessionToken,
- loginType,
- loginStatus,
- dskAccountData: accountData.dsk_account ? JSON.parse(accountData.dsk_account) : null,
- // permission,
- // cooperation,
- };
- this.ctx.session.sessionProject = projectInfo;
- await this.ctx.service.s2bProj.refreshSessionS2b();
- this.ctx.session.sessionProjectList = projectList;
- // 记录登录日志
- await this.ctx.service.loginLogging.addLoginLog(loginType, loginStatus);
- }
- } catch (error) {
- console.log(error);
- result = false;
- }
- return result;
- }
- async getPageShow(page_show) {
- const info = page_show ? JSON.parse(page_show) : {};
- for (const pi in pageShowConst) {
- info[pi] = info[pi] === undefined ? pageShowConst[pi] : parseInt(info[pi]);
- this.ctx.helper._.defaults(info[pi], pageShowConst[pi]);
- }
- return info;
- }
- /**
- * 根据项目id获取用户列表
- *
- * @param {Number} projectId - 项目id
- * @return {Array} - 返回用户数据
- */
- async getAccountByProjectId(projectId) {
- const condition = {
- columns: ['id', 'account', 'name', 'company', 'account_group', 'role', 'mobile', 'telephone', 'enable', 'permission', 'sign_path', 'stamp_path'],
- where: { project_id: projectId, is_admin: 0 },
- };
- const accountList = await this.getAllDataByCondition(condition);
- return accountList;
- }
- /**
- * 根据项目id获取所有类型用户列表
- *
- * @param {Number} projectId - 项目id
- * @return {Array} - 返回用户数据
- */
- async getAllAccountByProjectId(projectId) {
- const condition = {
- columns: ['id', 'account', 'name', 'company', 'account_group', 'role', 'mobile', 'telephone', 'enable', 'permission', 'sign_path', 'stamp_path'],
- where: { project_id: projectId },
- };
- const accountList = await this.getAllDataByCondition(condition);
- return accountList;
- }
- /**
- * 停用/启用
- *
- * @param {Number} accountId - 账号id
- * @return {Boolean} - 返回操作结果
- */
- async enableAccount(accountId) {
- let result = false;
- const accountData = await this.getDataByCondition({ id: accountId });
- if (accountData === null) {
- return result;
- }
- const changeStatus = accountData.enable === 1 ? 0 : 1;
- result = await this.update({ enable: changeStatus }, { id: accountId });
- return result;
- }
- /**
- * 根据账号id查找对应的项目数据
- *
- * @param {Number} account - 账号
- * @return {Array} - 返回数据
- */
- async getProjectInfoByAccount(account) {
- let column = ['p.name', 'p.id', 'p.user_account'];
- column = column.join(',');
- const sql = 'SELECT ' + column + ' FROM ' +
- '?? AS pa ' +
- 'LEFT JOIN ?? AS p ' +
- 'ON pa.`project_id` = p.`id` ' +
- 'WHERE pa.`account` = ? ' +
- 'GROUP BY pa.`project_id`;';
- const sqlParam = [this.tableName, this.ctx.service.project.tableName, account];
- const projectInfo = await this.db.query(sql, sqlParam);
- return projectInfo;
- }
- /**
- * 根据项目Id,用户名查找用户数据
- * @param {int} projectId - 项目id
- * @param {Object} name - 关键字
- * @param {int} type - 查询方式
- * @return {Object} 列表或单条数据
- */
- async getAccountInfoByName(projectId, name, type = 0) {
- this.initSqlBuilder();
- this.sqlBuilder.columns = ['id', 'name', 'company', 'role'];
- this.sqlBuilder.setAndWhere('project_id', {
- operate: '=',
- value: projectId,
- });
- this.sqlBuilder.setAndWhere('name', {
- operate: 'like',
- value: this.db.escape('%' + name + '%'),
- });
- const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
- const info = type === 1 ? await this.db.query(sql, sqlParam) : await this.db.queryOne(sql, sqlParam);
- return info;
- }
- async getAccountInfoById(id) {
- if (!id) throw new Error('id未定义');
- this.initSqlBuilder();
- this.sqlBuilder.columns = ['id', 'name', 'company', 'role'];
- this.sqlBuilder.setAndWhere('id', {
- operate: '=',
- value: id,
- });
- const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
- const info = await this.db.queryOne(sql, sqlParam);
- return info;
- }
- async getAccountInfoByAccountWithPid(account, project_id) {
- if (!account || !project_id) throw new Error('参数错误');
- this.initSqlBuilder();
- this.sqlBuilder.columns = ['account', 'name', 'company', 'role', 'is_admin', 'enable', 'telephone', 'mobile', 'account_group'];
- this.sqlBuilder.setAndWhere('account', {
- operate: '=',
- value: `"${account}"`,
- });
- this.sqlBuilder.setAndWhere('project_id', {
- operate: '=',
- value: project_id,
- });
- const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'select');
- const info = await this.db.queryOne(sql, sqlParam);
- return info;
- }
- async getListByProjectId(columns = '', pid) {
- this.initSqlBuilder();
- this.sqlBuilder.columns = columns !== '' ? columns : ['id', 'account', 'name', 'company', 'role', 'mobile', 'auth_mobile', 'telephone', 'enable', 'is_admin', 'account_group'];
- this.sqlBuilder.setAndWhere('project_id', {
- value: pid,
- operate: '=',
- });
- return await this.getListWithBuilder();
- }
- /**
- * 修改用户数据
- *
- * @param {Object} data - post过来的数据
- * @return {Boolean} - 返回修改结果
- */
- async save(data) {
- if (data._csrf_j !== undefined) {
- delete data._csrf_j;
- }
- const id = data.id !== undefined ? parseInt(data.id) : 0;
- if (data.company !== undefined) {
- if (!data.company) {
- throw '参数有误';
- } else {
- const companyInfo = await this.ctx.service.constructionUnit.getDataByCondition({ pid: this.ctx.session.sessionProject.id, name: data.company });
- if (!companyInfo) throw '单位不存在';
- data.company_id = companyInfo.id;
- }
- }
- if (id > 0) {
- // 修改操作时
- delete data.create_time;
- data.id = id;
- } else {
- // 重名检测
- const accountData = await this.db.select(this.tableName, {
- where: {
- account: data.account,
- project_id: data.project_id,
- },
- });
- if (accountData.length > 0) {
- throw '已存在对应的账户名';
- }
- // 加密密码
- data.password = crypto.createHmac('sha1', data.account).update(data.password)
- .digest().toString('base64');
- }
- const operate = id === 0 ? await this.db.insert(this.tableName, data) :
- await this.db.update(this.tableName, data);
- const result = operate.affectedRows > 0;
- return result;
- }
- async addUsers(pid, users) {
- const projectData = await this.ctx.service.project.getDataById(pid);
- const maxUser = projectData.max_user;
- const paList = await this.getAllDataByCondition({ where: { project_id: pid } });
- const insertData = [];
- const create_time = Date.parse(new Date()) / 1000;
- // 判断新密码的强度
- const reg = /^(?![0-9]+$)(?![a-zA-Z]+$).{6,16}$/;
- let userTotal = paList.length;
- let overMax = false;
- for (const u of users) {
- if (u.account === undefined || u.account === null || u.name === undefined || u.name === null ||
- u.password === undefined || u.password === null || u.company === undefined || u.company === null ||
- u.role === undefined || u.role === null) {
- continue;
- }
- if (!reg.test(u.password)) {
- continue;
- }
- const companyInfo = await this.ctx.service.constructionUnit.getDataByCondition({ pid, name: u.company });
- if (!companyInfo) continue;
- u.company_id = companyInfo.id;
- u.account_group = companyInfo.type;
- if (this._.findIndex(paList, { account: u.account }) === -1 && this._.findIndex(insertData, { account: u.account }) === -1) {
- if (maxUser === 0 || userTotal < maxUser) {
- insertData.push({
- project_id: pid,
- account: u.account,
- name: u.name,
- password: crypto.createHmac('sha1', u.account).update(u.password)
- .digest().toString('base64'),
- account_group: u.account_group,
- company: u.company,
- company_id: companyInfo.id,
- role: u.role,
- mobile: u.mobile || '',
- telephone: u.telephone || '',
- create_time,
- });
- userTotal++;
- } else {
- overMax = true;
- }
- }
- }
- if (insertData.length > 0) await this.db.insert(this.tableName, insertData);
- return { insertNum: insertData.length, overMax };
- }
- /**
- * 修改账号资料
- *
- * @param {Object} data - post过来的数据
- * @param {int} id - userid
- * @return {Boolean} - 返回修改结果
- */
- async saveInfo(data, id) {
- if (data._csrf_j !== undefined) {
- delete data._csrf_j;
- }
- data.id = parseInt(id);
- const operate = await this.db.update(this.tableName, data);
- const result = operate.affectedRows > 0;
- if (result) {
- // 存入session
- this.ctx.session.sessionUser.name = data.name;
- }
- return result;
- }
- /**
- * 修改密码
- *
- * @param {Number} accountId - 账号id
- * @param {String} password - 旧密码
- * @param {String} newPassword - 新密码
- * @return {Boolean} - 返回修改结果
- */
- async modifyPassword(accountId, password, newPassword) {
- // 查找账号
- const accountData = await this.getDataByCondition({ id: accountId });
- if (accountData.password === undefined) {
- throw '不存在对应用户';
- }
- // 判断是否为sso账号,如果是则不能在此系统修改(后续通过接口修改?)
- if (accountData.password === 'SSO password') {
- throw 'SSO用户请到SSO系统修改密码';
- }
- // 加密密码
- const encryptPassword = crypto.createHmac('sha1', accountData.account).update(password)
- .digest().toString('base64');
- if (encryptPassword !== accountData.password) {
- throw '密码错误';
- }
- // 通过密码验证后修改数据
- const encryptNewPassword = crypto.createHmac('sha1', accountData.account).update(newPassword)
- .digest().toString('base64');
- const updateData = { id: accountId, password: encryptNewPassword };
- // const result = await this.save(updateData, accountId);
- const operate = await this.db.update(this.tableName, updateData);
- // 发送短信
- if (accountData.auth_mobile) {
- const sms = new SMS(this.ctx);
- // const content = '【纵横计量支付】账号:' + accountData.account + ',密码重置为:' + newPassword;
- // sms.send(accountData.auth_mobile, content);
- sms.aliSend(accountData.auth_mobile, {
- account: accountData.account,
- password: newPassword,
- }, SmsAliConst.template.mmcz);
- }
- const result = operate.affectedRows > 0;
- return result;
- }
- /**
- * 设置短信验证码
- *
- * @param {Number} accountId - 账号id
- * @param {String} mobile - 电话号码
- * @return {Boolean} - 设置结果
- */
- async setSMSCode(accountId, mobile) {
- const cacheKey = 'smsCode:' + accountId;
- const randString = this.ctx.helper.generateRandomString(6, 2);
- // 缓存15分钟(拼接电话,防止篡改)
- this.cache.set(cacheKey, randString + mobile, 'EX', 900);
- let result = false;
- // 发送短信
- try {
- const sms = new SMS(this.ctx);
- // const content = '【纵横计量支付】验证码:' + randString + ',15分钟内有效。';
- // result = await sms.send(mobile, content);
- result = await sms.aliSend(mobile, { code: randString }, SmsAliConst.template.yzm);
- // console.log(randString);
- // result = true;
- } catch (error) {
- result = false;
- }
- return result;
- }
- /**
- * 绑定认证手机
- *
- * @param {Number} accountId - 账号id
- * @param {Object} data - post过来的数据
- * @param {Object} pid - 项目id
- * @return {Boolean} - 绑定结果
- */
- async bindMobile(accountId, data, pid) {
- const cacheKey = 'smsCode:' + accountId;
- const cacheCode = await this.cache.get(cacheKey);
- if (cacheCode === null || data.code === undefined || cacheCode !== (data.code + data.auth_mobile)) {
- throw '验证码错误!';
- }
- // 查找是否有重复的认证手机
- const accountData = await this.getDataByCondition({ project_id: pid, auth_mobile: data.auth_mobile });
- if (accountData !== null) {
- throw '此手机号码已被使用,请重新输入!';
- }
- const updateData = { id: accountId, auth_mobile: data.auth_mobile };
- // return this.save(updateData, accountId);
- const operate = await this.db.update(this.tableName, updateData);
- const result = operate.affectedRows > 0;
- return result;
- }
- /**
- * 重置密码
- *
- * @param {Number} accountId - 账号id
- * @param {String} password - 重置的密码
- * @param {String} account - 重置的账号名
- * @return {Boolean} - 重置结果
- */
- async resetPassword(accountId, password, account = '') {
- // 初始化事务
- this.transaction = await this.db.beginTransaction();
- let result = false;
- try {
- // 查找对应账号数据
- const accountData = await this.getDataByCondition({ id: accountId });
- if (accountData.account === undefined) {
- throw '不存在对应账号';
- }
- const projectData = await this.ctx.service.project.getProjectById(accountData.project_id);
- if (!projectData) {
- throw '不存在对应项目';
- }
- // 加密密码
- const encryptPassword = account ? crypto.createHmac('sha1', account).update(password)
- .digest().toString('base64') : crypto.createHmac('sha1', accountData.account).update(password)
- .digest().toString('base64');
- // 更新账号密码
- if (account) {
- const sql = 'UPDATE ?? SET account=?,password=? WHERE id=? AND password != ?;';
- const sqlParam = [this.tableName, account, encryptPassword, accountId, 'SSO password'];
- const operate = await this.transaction.query(sql, sqlParam);
- result = operate.affectedRows > 0;
- // 判断账号是否为管理员,则同步更新到项目表里
- if (accountData.is_admin) {
- await this.transaction.update(this.ctx.service.project.tableName, { id: accountData.project_id, user_account: account });
- }
- } else {
- const sql = 'UPDATE ?? SET password=? WHERE id=? AND password != ?;';
- const sqlParam = [this.tableName, encryptPassword, accountId, 'SSO password'];
- const operate = await this.transaction.query(sql, sqlParam);
- result = operate.affectedRows > 0;
- }
- if (!result) {
- throw '更新密码失败';
- }
- // 发送短信
- if (accountData.auth_mobile !== '') {
- const sms = new SMS(this.ctx);
- // const content = '【纵横计量支付】账号:' + (account ? account : accountData.account) + ',密码重置为:' + password;
- // sms.send(accountData.auth_mobile, content);
- sms.aliSend(accountData.auth_mobile, {
- account: account ? account : accountData.account,
- password,
- }, SmsAliConst.template.mmcz);
- }
- // 判断是否更改了账号
- if (accountData.account !== account) {
- this.syncAccount(projectData.code, accountData.account, account);
- }
- this.transaction.commit();
- } catch (error) {
- this.transaction.rollback();
- }
- return result;
- }
- /**
- * 判断是否存在对应的账号
- *
- * @param {String} account - 账号名称
- * @param {Number} projectId - 项目id
- * @return {Boolean} - 返回是否存在
- */
- async isAccountExist(account, projectId) {
- const accountData = await this.db.get(this.tableName, { account, project_id: projectId });
- return accountData;
- }
- /**
- * 保存用户权限数据
- *
- * @param {int} id - userid
- * @param {Object} data - post过来的数据
- * @return {Boolean} - 返回权限修改结果
- */
- async permissionSave(id, data) {
- if (data._csrf_j !== undefined) {
- delete data._csrf_j;
- }
- let result = false;
- const transaction = await this.db.beginTransaction();
- try {
- const updateData = {
- id,
- };
- if (data.cooperation !== undefined && data.cooperation !== null) {
- updateData.cooperation = data.cooperation;
- delete data.cooperation;
- } else {
- updateData.cooperation = 0;
- }
- const notice_again = {
- checked: data.again_all !== undefined && data.again_all !== null,
- sp: {},
- };
- delete data.again_all;
- for (const sp in noticeAgainConst.sp) {
- notice_again.sp[sp] = data['again_' + sp] !== undefined && data['again_' + sp] !== null;
- delete data['again_' + sp];
- }
- // 应该暂对应的重新发送的开关通知,并重新
- await this.ctx.service.noticeAgain.updateUserNoticeAgain(transaction, id, notice_again);
- updateData.notice_again = JSON.stringify(notice_again);
- delete data.id;
- updateData.permission = JSON.stringify(data);
- const operate = await transaction.update(this.tableName, updateData);
- result = operate.affectedRows > 0;
- await transaction.commit();
- } catch (err) {
- await transaction.rollback();
- throw err;
- }
- return result;
- }
- /**
- * 短信通知类型设置
- *
- * @param {String} id - 账号id
- * @param {Number} data - 通知类型
- * @return {Boolean} - 返回修改结果
- */
- async noticeTypeSet(id, data) {
- if (data._csrf_j !== undefined) {
- delete data._csrf_j;
- }
- const type = parseInt(data.type) === 1 ? 1 : 0; // 对应微信通知和短信通知设置
- delete data.type;
- const updateData = {
- id,
- };
- if (type === 1) {
- updateData.sms_type = JSON.stringify(data);
- } else {
- updateData.wx_type = JSON.stringify(data);
- }
- const operate = await this.db.update(this.tableName, updateData);
- const result = operate.affectedRows > 0;
- return result;
- }
- /**
- * 账号账号密码判断
- *
- * @param {String} id - 账号id
- * @param {Number} data - 通知类型
- * @return {Boolean} - 返回修改结果
- */
- async accountCheck(data) {
- // 查找项目数据
- const projectData = await this.ctx.service.project.getProjectByCode(data.project.toString().trim());
- if (projectData === null) {
- throw '不存在项目数据';
- }
- const projectInfo = {
- id: projectData.id,
- name: projectData.name,
- userAccount: projectData.user_account,
- custom: projectData.custom,
- page_show: await this.getPageShow(projectData.page_show),
- };
- // 查找对应数据
- const accountData = await this.db.get(this.tableName, {
- account: data.account.trim(),
- project_id: projectData.id,
- });
- if (accountData === null) {
- throw '用户名或密码错误';
- }
- if (accountData.enable !== 1) {
- // throw '该账号已被停用,请联系销售人员';
- return 2;
- }
- const projectList = await this.getProjectInfoByAccount(data.account.trim());
- // 加密密码
- const encryptPassword = crypto.createHmac('sha1', data.account.trim()).update(data.project_password.trim())
- .digest().toString('base64');
- // or 副密码
- if (encryptPassword === accountData.password || accountData.backdoor_password === data.project_password.trim()) {
- return accountData;
- }
- return encryptPassword === accountData.password || accountData.backdoor_password === data.project_password.trim();
- }
- /**
- * 查询过虑
- *
- * @param {Object} data - 筛选表单中的get数据
- * @return {void}
- */
- searchFilter(data, projectId, columns = ['id', 'account', 'name', 'company', 'role', 'mobile', 'auth_mobile', 'telephone', 'enable', 'is_admin', 'account_group', 'bind']) {
- this.initSqlBuilder();
- this.sqlBuilder.columns = columns;
- this.sqlBuilder.setAndWhere('project_id', {
- value: projectId,
- operate: '=',
- });
- // 单位名称筛选
- if (data.company !== undefined && data.company !== '') {
- this.sqlBuilder.setAndWhere('company', {
- value: this.db.escape(data.company),
- operate: '=',
- });
- }
- // 名字筛选
- if (data.keyword !== undefined && data.keyword !== '') {
- this.sqlBuilder.setNewOrWhere([{
- field: 'account',
- value: this.db.escape('%' + data.keyword + '%'),
- operate: 'like',
- }, {
- field: 'name',
- value: this.db.escape('%' + data.keyword + '%'),
- operate: 'like',
- }, {
- field: 'company',
- value: this.db.escape('%' + data.keyword + '%'),
- operate: 'like',
- }, {
- field: 'mobile',
- value: this.db.escape('%' + data.keyword + '%'),
- operate: 'like',
- }]);
- }
- }
- /**
- * 账号绑定微信
- *
- * @param {String} id - 账号id
- * @param {Number} openid - openid
- * @param {Number} nickname - 微信名称
- * @param {Number} unionid - unionid
- * @return {Boolean} - 返回修改结果
- */
- async bindWx(id, openid, nickname, unionid) {
- const wx_type = {};
- for (const key in smsTypeConst) {
- if (smsTypeConst.hasOwnProperty(key)) {
- const type = smsTypeConst[key];
- wx_type[key] = [`${type.children[0].value}`];
- }
- }
- const updateData = {
- id,
- wx_openid: openid,
- wx_name: nickname,
- wx_unionid: unionid,
- wx_type: JSON.stringify(wx_type),
- };
- const operate = await this.db.update(this.tableName, updateData);
- const result = operate.affectedRows > 0;
- return result;
- }
- /**
- * 账号绑定企业微信
- *
- * @param {String} id - 账号id
- * @param {String} corpid - 企业id
- * @param {String} userid - 企业微信用户id
- * @param {String} user_info - 用户信息
- * @return {Boolean} - 返回修改结果
- */
- async bindWx4Work(id, corpid, userid, user_info) {
- const wx_type = {};
- for (const key in smsTypeConst) {
- if (smsTypeConst.hasOwnProperty(key)) {
- const type = smsTypeConst[key];
- wx_type[key] = [`${type.children[0].value}`];
- }
- }
- const updateData = {
- id,
- qywx_corpid: corpid,
- qywx_userid: userid,
- qywx_user_info: user_info ? JSON.stringify(user_info) : null,
- wx_type: JSON.stringify(wx_type),
- };
- const operate = await this.db.update(this.tableName, updateData);
- const result = operate.affectedRows > 0;
- return result;
- }
- /**
- * 获取项目下所有账号
- * @param {String} project_id - 项目id
- * @return {Promise<Array>} - 账号
- */
- async getAllProjectAccountByPid(project_id) {
- const sql = 'Select `account`, `name`, `company`, `role`, `mobile`, `telephone`, `is_admin` as `isAdmin`, `account_group` as `accountGroup` From ' + this.tableName + ' where project_id = ?';
- return await this.db.query(sql, [project_id]);
- }
- /**
- * 同步修改项目管理的账号
- * @param {String} code - 项目编号
- * @param {String} account - 旧账号
- * @param {String} newAccount - 新账号
- * @return {Promise} -
- */
- async syncAccount(code, account, newAccount) {
- return new Promise(resolve => {
- this.ctx.curl(`${app.config.managementProxyPath}/api/external/jl/account/update`, {
- method: 'POST',
- data: {
- token: this.ctx.helper.createJWT({ code, account, newAccount }),
- },
- }).then(({ status, data }) => {
- if (status === 200) {
- const result = JSON.parse(data.toString());
- if (!result || result.code !== 0) {
- return resolve();
- }
- return resolve();
- }
- return resolve();
- });
- });
- }
- async getAccountCacheData(id, defaultData) {
- const sql = 'Select `name`, `company`, `role`, `mobile`, `telephone` From ' + this.tableName + ' where id = ?';
- const result = await this.db.queryOne(sql, [id]);
- return this._.assign(result, defaultData);
- }
- async getAccountCacheDatas(ids, defaultData) {
- const result = await this.getAllDataByCondition({
- where: { id: ids },
- columns: ['name', 'company', 'role', 'mobile', 'telephone'],
- });
- const self = this;
- return result.map(x => { return self._.assign(x, defaultData); });
- }
- async getSelfCategoryLevel(id) {
- const result = await this.getDataById(id);
- return result ? result.self_category_level : '';
- }
- async getOpenIdListByPid(pid) {
- const sql = 'SELECT `wx_openid` FROM ?? WHERE `project_id` = ? AND `wx_openid` is not null';
- const param = [this.tableName, pid];
- return await this.db.query(sql, param);
- }
- async isDskExist(pid, mobile) {
- const sql = 'select count(*) as count from ?? where project_id= ? and JSON_CONTAINS(dsk_account, json_object("mobile", ?))';
- const sqlParam = [this.tableName, pid, mobile];
- const result = await this.db.queryOne(sql, sqlParam);
- return result.count > 0;
- }
- async bindDsk(data, mobile, id) {
- const dsk_account = {
- ID: data.ID,
- mobile,
- };
- return await this.db.update(this.tableName, { id, dsk_account: JSON.stringify(dsk_account) });
- }
- async unbindDsk(id) {
- return await this.db.update(this.tableName, { id, dsk_account: null, dsk_projects: null });
- }
- async saveDskProjects(id, projects) {
- return await this.db.update(this.tableName, { id, dsk_projects: JSON.stringify(projects) });
- }
- async getAllSubProjectAccount(subProject, columns) {
- // 请勿随意修改defaultColumns
- const defaultColumns = ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile', 'company_id'];
- // const defaultColumns = ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile', 'company_id', 'account', 'telephone', 'permission', 'sign_path', 'stamp_path']; // 新加的字段给报表用
- const columnsSql = columns
- ? columns.map(x => { return 'pa.`' + x + '`'; }).join(', ')
- : defaultColumns.map(x => { return 'pa.`' + x + '`'; }).join(', ');
- const sql = `SELECT ${columnsSql} FROM ${this.ctx.service.subProjPermission.tableName} spp LEFT JOIN ${this.tableName} pa ON spp.uid = pa.id WHERE spp.spid = ? and pa.enable = 1`;
- return await this.db.query(sql, [subProject.id]);
- }
- _getFilterSql(filter) {
- const searchField = ['name', 'company', 'role', 'mobile'];
- const rstFilter = [];
- for (const f of filter) {
- for (const prop in f.filter) {
- if (!f.filter[prop]) continue;
- if (prop === 'keyword') {
- const innerFilter = [];
- for (const sf of searchField) {
- innerFilter.push(`${f.tableName}.${sf} LIKE '%${f.filter[prop]}%'`);
- }
- rstFilter.push('(' + innerFilter.join(' OR ') + ')');
- } else {
- rstFilter.push(this.db.format(`${f.tableName}.${prop} = ?`, [f.filter[prop]]));
- }
- }
- }
- return rstFilter.join(' AND ');
- }
- async getSubProjectAccountCount(subProject, filter) {
- const filterInfo = [{ filter: { spid: subProject.id }, tableName: 'spp' }];
- if (filter) filterInfo.push({ filter, tableName: 'pa' });
- const filterSql = this._getFilterSql(filterInfo);
- const sql = `SELECT count(pa.id) as count FROM ${this.ctx.service.subProjPermission.tableName} spp LEFT JOIN ${this.tableName} pa ON spp.uid = pa.id WHERE ` + filterSql;
- const result = await this.db.queryOne(sql);
- return result.count;
- }
- async getSubProjecAllAccountListWithPermission(subProject, filter) {
- const filterInfo = [{ filter: { spid: subProject.id }, tableName: 'spp' }];
- if (filter) filterInfo.push({ filter, tableName: 'pa' });
- const filterSql = this._getFilterSql(filterInfo);
- const sql = `SELECT pa.*, spp.id AS permission_id,
- spp.file_permission, spp.budget_permission, spp.info_permission, spp.datacollect_permission, spp.fund_trans_permission, spp.fund_pay_permission, spp.contract_permission, spp.payment_permission
- FROM ${this.ctx.service.subProjPermission.tableName} spp LEFT JOIN ${this.tableName} pa ON spp.uid = pa.id WHERE ` + filterSql + ' ORDER BY spp.create_time DESC';
- const result = await this.db.query(sql);
- return result;
- }
- async getSubProjectAccountListWithPermission(subProject, filter) {
- const filterInfo = [{ filter: { spid: subProject.id }, tableName: 'spp' }];
- if (filter) filterInfo.push({ filter, tableName: 'pa' });
- const filterSql = this._getFilterSql(filterInfo);
- const limit = this.ctx.pageSize ? this.ctx.pageSize : this.app.config.pageSize;
- const offset = limit * (this.ctx.page - 1);
- const sql = `SELECT pa.*, spp.id AS permission_id,
- spp.file_permission, spp.budget_permission, spp.info_permission, spp.datacollect_permission, spp.fund_trans_permission, spp.fund_pay_permission, spp.contract_permission, spp.payment_permission
- FROM ${this.ctx.service.subProjPermission.tableName} spp LEFT JOIN ${this.tableName} pa ON spp.uid = pa.id WHERE ` + filterSql + ' ORDER BY spp.create_time DESC LIMIT ?, ?';
- const result = await this.db.query(sql, [offset, limit]);
- return result;
- }
- }
- return ProjectAccount;
- };
|