user.js 1.19 KB
'use strict';

const _ = require('lodash');
const cookie = global.yoho.cookie;
const authcode = require('../../utils/authcode');

module.exports = () => {
    return (req, res, next) => {
        // 从 SESSION 中获取到当前登录用户的 UID
        if (req.session && _.isNumber(req.session.LOGIN_UID)) {
            // 调用接口传参时切勿使用toString获得字符串
            req.user.uid = {
                toString: () => {
                    return req.session.LOGIN_UID;
                },
                sessionKey: req.session.SESSION_KEY
            };
            let userData = _.get(req.session, 'USER', {});

            _.merge(req.user, userData);
        }

        // session 没有读取到的时候,从 cookie 读取 UID
        if (!req.user.uid && req.cookies._UID) {
            let sessionKey = req.cookies._SESSION_KEY && authcode(req.cookies._SESSION_KEY, '_SESSION_KEY', 2592000000);

            // 调用接口传参时切勿使用toString获得字符串
            req.user.uid = {
                toString: () => {
                    return cookie.getUid(req);
                },
                sessionKey
            };
        }

        next();
    };
};