set-yoho-data.js 1.75 KB
/**
 * 设置 YOHO 数据
 * @author: 赵彪<bill.zhao@yoho.cn>
 * @date: 2016/6/16
 */

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

/**
 * 获取 IP
 * @param {*} req
 */
const _getClientIp = req => {
    let remoteIp = req.get('X-Forwarded-For') || req.get('X-Real-IP') || req.ip;

    if (remoteIp.indexOf(',') > 0) {
        let arr = remoteIp.split(',');

        remoteIp = _.trim(arr[arr.length - 1]);
    }

    if (_.startsWith(remoteIp, '10.66.')) {
        remoteIp = req.get('X-Real-IP');
    }

    return _.trim(remoteIp);
};

module.exports = () => {
    return (req, res, next) => {
        let yoho = {
            pageChannel: {}
        };

        let ua = (req.get('User-Agent') || '').toLowerCase();

        const channel = req.query.channel || req.cookies._Channel || 'boys';

        // IP 地址
        yoho.clientIp = _getClientIp(req);

        // 用于头部颜色控制
        yoho.pageChannel[channel] = true;

        // 当前频道设置
        yoho.channel = channel;

        // 判断请求是否来自app
        yoho.isApp = req.query.app_version || req.query.appVersion;
        yoho.isWechat = /micromessenger/i.test(req.get('User-Agent') || '');
        yoho.isWeibo = ua.indexOf('weibo') !== -1;
        yoho.isqq = /MQQBrowser/i.test(req.get('User-Agent') || '');

        Object.assign(res.locals, yoho);
        Object.assign(req.yoho, yoho);

        // App 内请求支持跨域
        if (yoho.isApp) {
            res.set('Access-Control-Allow-Origin', '*');
        }

        res.locals.cartUrl = helpers.urlFormat('/cart/index/index'); // 悬挂购物车
        res.locals.indexUrl = helpers.urlFormat('/?go=1'); // 悬挂首页
        res.locals.showHeader = true;

        next();
    };
};