user.js 1.93 KB
'use strict';

const _ = require('lodash');
const Fn = require('lodash/fp');
const cookie = global.yoho.cookie;
const cache = global.yoho.cache;
const LoginService = require('../../apps/passport/models/login-service');

/**
 * 已登录用户的信息,包括记住我功能。
 */
module.exports = () => {
    return (req, res, next) => {

        // 从 SESSION 中获取到当前登录用户的 UID
        if (req.session && _.isNumber(req.session._LOGIN_UID)) {
            req.user.uid = req.session._LOGIN_UID;
        }

        // session 没有读取到的时候,从 cookie 读取 UID
        if (!req.user.uid && req.cookies._UID) {
            req.user.uid = cookie.getUid(req);
        }

        if (req.cookies._UID) {
            let uidCookie = req.cookies._UID.split('::');
            let getVip = Fn.nth(3);

            req.user.vip = getVip(uidCookie);
        }

        // 从 SESSION 中获得 USERNAME
        if (req.user.uid) {
            req.user.username = req.session._USERNAME;

            if (!req.user.username) {
                req.user.username = req.cookies._USERNAME;
            }
        }

        // 记住我
        if (req.cookies.isRemember && req.cookies.remem && !req.user.uid) {
            cache.get(req.cookies.remem).then(result => {
                let data = JSON.parse(result);
                let account = data.account;
                let password = data.password;
                let area = data.area;

                return LoginService.signin('PasswordLogin', area, account, password, '', req);
            }).then(result => {
                if (result.code !== 200) {
                    return Promise.reject(new Error(result.message));
                }

                return LoginService.syncUserSession(result.data.uid, req, res);
            }).then(()=> {
                return res.redirect(req.originalUrl);
            }).catch(next);
        } else {
            return next();
        }
    };
};