user.js
1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'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();
}
};
};