| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782 | 'use strict';/** * 项目账号数据模型 * * @author CaiAoLin * @date 2017/11/16 * @version */// 加密类const crypto = require('crypto');const SSO = require('../lib/sso');const SMS = require('../lib/sms');const SmsAliConst = require('../const/sms_alitemplate');const thirdPartyConst = require('../const/third_party');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 },                        confirm_password: { type: 'password', required: true, min: 6, 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 },                        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: projectData.page_show ? JSON.parse(projectData.page_show) : null,                    };                    // 查找对应数据                    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;                    }                    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;                    }                    // }                } 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,                        page_show: projectData.page_show ? JSON.parse(projectData.page_show) : null,                    };                    // 查找对应数据                    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,                        // permission,                        // cooperation,                    };                    const thirdParty = await this.db.get('zh_s2b_proj', { pid: projectInfo.id });                    if (thirdParty) {                        thirdParty.gxby_option = thirdParty.gxby_option ? JSON.parse(thirdParty.gxby_option) : null;                        projectInfo.gxby = thirdParty.gxby;                        projectInfo.gxby_status = thirdParty.gxby_option && thirdParty.gxby_option.status                            ? thirdParty.gxby_option.status : thirdPartyConst.gxby;                        thirdParty.dagl_option = thirdParty.dagl_option ? JSON.parse(thirdParty.dagl_option): null;                        projectInfo.dagl = thirdParty.dagl;                        projectInfo.dagl_status = thirdParty.dagl_option && thirdParty.dagl_option.status                            ? thirdParty.dagl_option.status : thirdPartyConst.dagl;                    }                    this.ctx.session.sessionProject = projectInfo;                    this.ctx.session.sessionProjectList = projectList;                }            } catch (error) {                console.log(error);                result = false;            }            return result;        }        /**         * 根据项目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'],                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'],                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) {            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 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 !== undefined) {                delete data._csrf;            }            const id = data.id !== undefined ? parseInt(data.id) : 0;            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;        }        /**         * 修改账号资料         *         * @param {Object} data - post过来的数据         * @param {int} id - userid         * @return {Boolean} - 返回修改结果         */        async saveInfo(data, id) {            if (data._csrf !== undefined) {                delete data._csrf;            }            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);            } 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 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;                } 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);                }                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 !== undefined) {                delete data._csrf;            }            const updateData = {                id,            };            if (data.cooperation !== undefined && data.cooperation !== null) {                updateData.cooperation = data.cooperation;                delete data.cooperation;            } else {                updateData.cooperation = 0;            }            delete data.id;            updateData.permission = 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 noticeTypeSet(id, data) {            if (data._csrf !== undefined) {                delete data._csrf;            }            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);            }            console.log(updateData);            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: projectData.page_show ? JSON.parse(projectData.page_show) : null,            };            // 查找对应数据            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) {            this.initSqlBuilder();            const columns = ['id', 'account', 'name', 'company', 'role', 'mobile', 'auth_mobile', 'telephone', 'enable', 'is_admin', 'account_group', 'bind'];            this.sqlBuilder.columns = columns;            this.sqlBuilder.setAndWhere('project_id', {                value: projectId,                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 - 微信名称         * @return {Boolean} - 返回修改结果         */        async bindWx(id, openid, nickname) {            const updateData = {                id,                wx_openid: openid,                wx_name: nickname,                wx_type: null,            };            const operate = await this.db.update(this.tableName, updateData);            const result = operate.affectedRows > 0;            return result;        }    }    return ProjectAccount;};
 |