user.js
3.21 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict';
const Fn = require('lodash/fp');
const cookie = global.yoho.cookie;
const authcode = require(`${global.utils}/authcode`);
const Promise = require('bluebird');
const co = Promise.coroutine;
const config = require('../../config/common');
const cache = global.yoho.cache;
const logger = global.yoho.logger;
// const loginService = require('../../apps/passport/models/login-service');
// const _ = require('lodash');
// const cache = global.yoho.cache;
function decrypt(word) {
return authcode(word, '_SESSION_KEY', 0, 'decode');
}
module.exports = () => {
return (req, res, next) => {
// 获得原始请求 url
req.fullUrl = () => req.protocol + '://' + req.get('host') + req.originalUrl;
co(function *() {
// memcached中session的key
let cKey = `${config.sessionMemcachedPrefix}${req.sessionID}`,
// 用户信息session存储使用标志: true: memcached;false: cookie (只有当memcached不可用时)
sessionFlag = true,
uid = 0;
yield cache.get(cKey).catch(err => {
logger.error(`product query save cache data fail:${err.toString()}`);
sessionFlag = false;
}).then((session) => {
if (session) {
uid = JSON.parse(session).LOGIN_UID_;
}
});
// 从 cookie 读取 UID
if (req.cookies._UID && req.cookies._SESSION_KEY) {
let uidCookie = req.cookies._UID.split('::');
let getName = Fn.nth(0);
let getVip = Fn.nth(2);
let getToken = Fn.nth(3);
req.user.name = getName(uidCookie); // 0
req.user.vip = getVip(uidCookie); // 2
req.user.token = getToken(uidCookie); // 3
req.user.isStudent = req.cookies.isStudent || 0;
req.user.uid = {
toString() {
return this.uid;
},
uid: sessionFlag ? uid : cookie.getUid(req),
sessionKey: decodeURIComponent(decrypt(req.cookies._SESSION_KEY)),
isValid() {
return this.uid && this.sessionKey;
}
};
}
next();
})();
// 记住我
// if (_.isEmpty(req.user) && req.cookies.isRemember === 'true' && req.cookies.remem) {
// return cache.get(req.cookies.remem).then((result) => {
// let data = JSON.parse(result || '{}');
// let area = data.area;
// let account = data.account;
// let password = data.password;
// return loginService.signin('password', area, account, password);
// }).then((result) => {
// if (result.code !== 200) {
// return Promise.reject();
// }
// return loginService.syncUserSession(result.data.uid, req, res);
// }).then(() => {
// return res.redirect(req.fullUrl());
// }).catch(next);
// } else {
// return next();
// }
};
};