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

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

/**
 * 获取 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');
    }

    remoteIp = _.trim(remoteIp);

    if (!net.isIPv4(remoteIp)) {
        let ipv6String = remoteIp.split(':');

        remoteIp = ipv6String[ipv6String.length - 1];
    }

    return remoteIp;
};

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

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

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

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

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

        // 判断请求是否来自app
        yoho.isNowApp = /yohonow/i.test(req.get('User-Agent') || '');
        yoho.isMarsApp = /yohomars/i.test(req.get('User-Agent') || '');
        yoho.isYohoApp = /YohoBuy/i.test(req.get('User-Agent') || '');
        yoho.isApp = yoho.isMarsApp ||
            req.cookies.app_version ||
            yoho.isNowApp ||
            /YohoBuy/i.test(req.get('User-Agent') || '') ||
            (req.query.app_version && req.query.app_version !== 'false') ||
            (req.query.appVersion && req.query.appVersion !== 'false');
        yoho.isMobile = /(nokia|iphone|android|ipad|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220)/i.test(req.get('User-Agent') || ''); // eslint-disable-line
        yoho.isWechat = /micromessenger/i.test(req.get('User-Agent') || '');
        yoho.isWeibo = /weibo/i.test(req.get('User-Agent') || '');
        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();
    };
};