login.js 13.6 KB
var request = require('request');
var _ = require('lodash');
var fs = require('fs');
// var Geetest = require('gt3-sdk');

var Iaccount = global.Register.system;
// var pcGeetest = new Geetest({
//     geetest_id: '4bf7f911856073c1347247667790e7c4',
//     geetest_key: '8d41283971d071216f1cef3d190d6b44'
// });

var Utils = {
    createrMenus: function (data) {
        var menu = [];
        for (var key in data) {
            
            var v = data[key];
            var item = {
                title: v.menu_name,
            }
            if (v.parent_id === 0) {
                item.parent = 'menu-template';
                var itemSubs = [];
                _.forEach(v.sub, function (val) {
                    var sub = {
                        title: val.menu_name,
                        href: val.menu_url,
                        icon: 'list-alt'
                    }
                    itemSubs.push(sub);
                });
                
                item.menu = itemSubs;
            }
            menu.push(item);
        }
        return menu;
    }
}

module.exports = {
    namespace: "common",
    apis: {
        Ilogin: {
            title:'登录接口',
            url: Iaccount.loginEx,
            // form: '["{{account}}","{{password}}",{{platform}}]',   北京erp java登录接口,只接受application/json
            params: {
                account: { type: String },
                password: { type: String },
                platform: {type:Number,default: Iaccount.WEBSITE}
            }
        },
        getResourceByPid: {
            title:'菜单接口',
            // url: Iaccount.getResourceByPid,
            url: Iaccount.getResourceByPidEx,
            // form: '[{{pid}},{{role_id}},{{website}}]',
            params: {
                pid: { type: Number },
                // role_id: { type: Number },
                // website: { type: Number, default: Iaccount.WEBSITE }
                platform_id: { type: Number, default: Iaccount.WEBSITE }
            }
        },
        allRight: {
            title: '获取权限',
            // url: Iaccount.allRight,
            url: Iaccount.allRightEx,
            form: '[false]'
        },
        sessionAsync: {
            title:'与老系统session同步',
            // url: Iaccount.url + '/account/login/sessions',
            url: Iaccount.erpUrl + '/account/login/session',
            outobj: "response",
            form: {'account':'{{user}}','password':'{{password}}','refer': '{{refer}}'},
            params: {
                user: { type: String },
                password: { type: String },
                refer:{type:String,default:'%2Faccount%2Fprofile%2Fdisplay'}
            }
        },
        queryAllAuth: {
            title:'获取当前账号的品牌和店铺权限',
            url: Iaccount.queryAllAuth,
            //form: {'pid':'{{user}}'},
            params: {
                pid: { type: Number },
                type:{ type: Number, default : 1 }
            }
        },
        queryProfilePurviewPaths: {
            title: '获取当前账号所有授权的权限',
            url: Iaccount.queryProfilePurviewPaths,
            params: {
              pid: { type: Number },
              role_id: { type: Number },
              platform_id: { type: Number, default: Iaccount.WEBSITE }
            }
        },
        login: function (req, callback, common) {

             console.log("begin enter login function --------------------------------------------------------------------------------------"  + req);
            console.log(req.session);
            var userInfo = {},result = { code: 400, message: "登录失败" },isSuccess=false;
            
            var user = req.body.user||req.query.user;
            var password = req.body.password||req.query.password;
            // var captcha = req.body.captcha || req.query.captcha;
            // var verifyCode = captcha.split(',');
            var errcallback = function (err) { 
                result.code = err.errorCode;
                return callback(null, result);
            }

            // if (!captcha) {
            //     return callback(null, {
            //         message: '图形验证失败',
            //         code: 405
            //     });
            // }

            // pcGeetest.validate(req.session.fallback, {
            //     geetest_challenge: verifyCode[0],
            //     geetest_validate: verifyCode[1],
            //     geetest_seccode: verifyCode[2]
            // }, function(err, success) {
            //     if (err) {
            //         return callback(null, {
            //             message: '网络失败',
            //             code: 405
            //         });
            //     } else if (!success) {
            //         return callback(null, {
            //             message: '图形验证失败',
            //             code: 405
            //         });
            //     } else {
                    console.log("begin enter common Ilogin --------------------------------------------------------------------------------------");
                    
                    common.Ilogin(user, password).allRight().sessionAsync(user, password).done(function (IloginRes,allRes,sesRes) {
                        var userData = IloginRes.data, cookie = sesRes.caseless.dict["set-cookie"];

                        console.log("enter common Ilogin, code: " + IloginRes.code + ", pwdComplexRate: " + IloginRes.data.pwdComplexRate);

                        result.code = IloginRes.code;

                        if (result.code != 200) {
                             return callback(null, {
                                message: '密码错误',
                                code: 500
                            });
                        }

                        result.pwdComplexRate = IloginRes.data.pwdComplexRate;
                        result.passwd_time = IloginRes.data.pwdExpirationDays;

                        userInfo = { auth: userData, uid: userData.pid, name: userData.truename, role: userData.roleName, right: {},shopList:[],brands:[]};
                        common.queryAllAuth(userData.pid).getResourceByPid(userData.pid).queryProfilePurviewPaths(userData.pid, userData.role_id).done(function (allAuthResp, getRRes, allPPRes) {
                            console.log("enter common queryAllAuth, allAuthResp: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^", allAuthResp.data.brand.list);
                            if(true){
                                var arrList = [];
                                console.log("enter common queryAllAuth, allAuthResp list: ******************************************************************" + (JSON.stringify(allAuthResp.data.brand.list) == "{}"));
                                if (JSON.stringify(allAuthResp.data.brand.list) == "{}") {
                                    userInfo.brands=allAuthResp.data.brand.is_all?"0": Object.keys(arrList);
                                    console.log("enter common queryAllAuth arrList (((((((((((((((((((((((((((((((((((((");
                                } else {
                                    var test1 = {"hh" : {"2": "2", "144" : "144", "349":"349","1572":"1572"}}; // 2,144,349,1572
                                    userInfo.brands=allAuthResp.data.brand.is_all?"0": Object.keys(allAuthResp.data.brand.list);
                                    console.log("enter common queryAllAuth list ((((((((((((((((((((((((((((((((((((()))))))" + Object.keys(allAuthResp.data.brand.list) + "************" + Object.keys(test1.hh));
                                    // userInfo.brands=userData.data_authority.brand.is_all?"0":Object.keys(userData.data_authority.brand.list);
                                    //userInfo.brands = [2,144,349,1572];
                                }
                                
                                console.log("userInfo.brands set success ; userInfo.brands is " +  userInfo.brands + "(" + (typeof userInfo.brands==="string") + ")" + "*******");
                            }
                            _.forEach(allRes.data,  item => {
                                if (item.platform_id == Iaccount.WEBSITE ){
                                  userInfo.right[item.path] = true;
                                }
                            })
                            // allRes.data.forEach(function (data) {
                            //     if (data.platform_id == Iaccount.WEBSITE) {
                            //         userInfo.right[data.path] = true;
                            //     }
                            // });

                            //组织用户的菜单(切换了新接口)
                            userInfo.menu = Utils.createrMenus(getRRes.data);

                            //获取用户的所有权限(原为每次根据访问路径去请求接口,现改成将用户所有访问的路径都保存到session中) lzhy 2020-08-04
                            userInfo.purviewPaths = _.get(allPPRes, 'data', []);

                            // 如果是要过期,则需要提示用户密码要过期
                            console.log("enter getResourceByPid, passwd_time: " + result.passwd_time);
                            if (result.passwd_time != undefined && result.passwd_time > 0) {
                                userInfo.passwordMsg = '密码' + result.passwd_time + '天后过期,请尽快修改';
                            } else if (result.passwd_time != undefined && result.passwd_time <= 0) {
                                userInfo.passwordMsg = '密码已过期,请尽快修改';
                            }
                            console.log("enter getResourceByPid, passwordMsg: " + userInfo.passwordMsg);
                            console.log(req.session.user);
                            req.session.user = userInfo;
                            if (cookie && cookie.length > 0) {
                                req.session.gray = cookie[0];
                                result = { code: 200, message: "登录成功" ,data:req.session.user,pwdComplexRate :IloginRes.data.pwdComplexRate};
                            }
                            return callback(null, result);
                        });
                    }, errcallback);   // common.Ilogin(user, password).allRight().sessionAsync(user, password).done(
            //     } // else 结束
            // });
        },
        // geeCaptcha: function(req, callback, common) {
        //     return pcGeetest.register({
        //         client_type: 'web'
        //     }, function(err, data) {
        //         if (err) {
        //             return callback(null, {
        //                 code: 500,
        //                 message: "极验证注册失败"
        //             });
        //         }
        //
        //         callback(null, data);
        //     });
        // },
        isUsedMenuAuth:{
            title:'检查有没有权限',
            url:Iaccount.isUsedMenuAuth,
            form:'[{{pid}},{{role_id}},"{{path}}","","",' + Iaccount.WEBSITE + ']',
            params:{
                pid:{type:Number},
                role_id:{type:Number},
                path:{type:String}
            }
        },
        gray: function (req, callback,common) {
            var result = { code: 201, message: "没有权限" };
            console.log("enter gray filter...");
            if (req.session && req.session.user) {
                var user = req.session.user;
                var path = req.route?req.route.path[0]:req.originalUrl.replace(/\?.+/, '');
                console.log("enter gray filter, user: " + user + ", path: " + path + ", brands" + user.brands);
                req._yoheaders = {
                    'x-user-id': user.auth.pid,
                    'x-user-name': user.auth.account,//防止header中包含中文
                    'x-site-type': Iaccount.WEBSITE,
                    'x-client-ip': req.ip,
                    'x-user-brands':typeof user.brands==="string"?user.brands: user.brands.join(',')
                };

                if (path && user.right[path]) {
                    // 改成从缓存中读取用户所有的授权路径进行判断
                    if(_.indexOf(req.session.user.purviewPaths, path) > -1){
                      result = { code: 200, message: "具有权限" };
                    }
                    return callback(null, result);
                    // common.isUsedMenuAuth(user.auth.pid,user.auth.role_id,path).done(function(isURes){
                    //     result = { code: 200, message: "具有权限" };
                    //     if(isURes.data){
                    //         result={code:isURes.data.code,message:isURes.data.errmsg};
                    //     }
                    //     console.log("return result: " + JSON.stringify(isURes));
                    //     console.log("code 200, result: " + JSON.stringify(result));
                    //     return callback(null, result);
                    // },function(error){
                    //     console.log("error: " + error);
                    //     return callback(error, result);
                    // });
                } else {
                    result = { code: 200, message: "不受权限控制" };
                    console.log(result);
                    return callback(null, result);
                }
            } else {
                console.log("no session..");
                //result = { code: 200, message: "不受权限控制" };
                //console.log(result);
                return callback(null, result);
            }
        }
    }
}