user.js 1.81 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) => {
        req.getUrl = function() {
            return req.protocol + '://' + req.get('host') + req.originalUrl;
        };

        // 从 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);
        }

        // 从 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(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.getUrl());
            }).catch(next);
        } else {
            return next();
        }
    };
};