user.js 1.75 KB
'use strict';

const _ = require('lodash');
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);
            console.log('req.user.uid', req.user.uid);
        }

        // 从 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.signinAsync(area, account, password);
            }).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();
        }
    };
};