auth.js 690 Bytes
/**
 * 登录判断
 * @author: TaoHuang
 * @date: 2016/7/15
 */

'use strict';

const _ = require('lodash');
const helpers = global.yoho.helpers;

module.exports = (req, res, next) => {
    req.getUrl = function() {
        return req.protocol + '://' + req.get('host') + req.originalUrl;
    };

    let loginUrl = helpers.urlFormat('/passport/login', {refer: req.getUrl()});

    if (_.isEmpty(req.user) || !req.user.uid) {
        if (req.xhr) {
            return res.json({
                code: 400,
                message: '抱歉,您暂未登录!',
                data: {refer: loginUrl}
            });
        }

        return res.redirect(loginUrl);
    }
    next();
};