login.js 2.23 KB

var config = require('../config/gray');
var request = require('request');
var options=require('../staticConfig.js').staticDir;

var CSS_FILE = '/css/all.css';

var env = process.env.NODE_ENV || 'development';

//设置对于环境环境
if(env!=='development') {
    CSS_FILE = options[env].path+'/all.css';
}

/**
 * 登陆逻辑,跳转处理
 * @param  {Object} data 通过接口获取到的数据
 * @param  {Object} req  请求对象
 * @param  {Object} res  响应对象
 * @return {void}      没有返回
 */
exports.post = function(data, req, res) {
    //在适配的时候,不再走到下一个中间件
    res.adaptersStop = true;
    if(data.code===20003) { //登陆成功!
        //设置session信息
        req.session.user = data.data;
        //设置来源跳转
        var url = req.headers.referer?req.headers.referer:'/';
        //如果是登录页,则跳转首页
        if(url==='/login') {
            url = '/';
        }

        var options = {
            method:"POST",
            url:config.url+"/account/login/sessions",
            form:{
                'account':req.body.user,
                'password':req.body.password,
                'refer':'%2Faccount%2Fprofile%2Fdisplay'
            }
        }
        req.app.logger.log('verbose','gray login options:',options);
        request(options,function(err,ress,body){
            if(!err) {
                //cookie透传到老系统
                var cookie = ress.caseless.get('set-cookie');
                req.app.logger.log('verbose','login old server response http headers:',ress.caseless);
                req.app.logger.log('verbose','login gray cookie:',cookie);
                //如果没有设置到session
                if(cookie && cookie.length>0) {
                    req.session.gray = cookie[0];
                }
                //跳转
                res.redirect(url);

            } else {
                res.render('error/error_nolayout',{message:'用户名或者密码错误!',layout:false,cssfile:CSS_FILE});
            }
        });
        return;
    } else {
        
        //否则跳转错误
        res.render('error/error_nolayout',{message:'用户名或者密码错误!',layout:false,cssfile:CSS_FILE});
        return;
    }
}