user.js 1.37 KB
const _ = require('lodash');
const md5 = require('yoho-md5');
const config = global.yoho.config;

module.exports = () => {
    return (req, res, next) => {
        const uid = req.cookies._YOHOUID;
        const token = req.cookies._YOHOTOKEN;
        const key = `-_-!!!${uid}!!!-_-`;

        if (md5(key) === token) {
            req.user.uid = uid;
            delete req.cookies._YOHOUID;
        }

        // app 内处理
        if (req.yoho.isApp) {
            if (req.cookies.app_uid &&
                req.cookies.app_uid !== '0' &&
                req.cookies.app_session_key &&
                req.cookies.app_version &&
                req.cookies.app_client_type) {
                // 调用接口传参时切勿使用toString获得字符串
                req.user.uid = {
                    toString: () => {
                        return _.parseInt(req.cookies.app_uid);
                    },
                    sessionKey: req.cookies.app_session_key,
                    appVersion: req.cookies.app_version || req.query.app_version || config.appVersion,
                    appSessionType: req.cookies.app_client_type
                };
            }
        }

        delete req.query.app_version;
        delete req.query.client_secret;
        delete req.query.client_type;
        delete req.query.session_key;
        delete req.query.udid;

        next();
    };
};