passport.js
7.68 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
const _ = require('lodash');
const url = require('url');
const uuid = require('uuid');
const passport = require('passport');
const TaobaoStrategy = require('./passport-taobao');
const authcode = require('../../utils/authcode');
const aes = require('./aes');
const log = global.yoho.logger;
const sign = global.yoho.sign;
const config = global.yoho.config;
const loginPage = `${config.siteUrl}/signin.html`;
const homePage = `${config.siteUrl}/xianyu/channel`;
// taobao 登录
passport.use('taobao', new TaobaoStrategy({
clientID: '27930297',
clientSecret: '29b30287153a02f531c160df17da8078',
callbackURL: `${config.siteUrl}/xianyu/passport/callback/taobao`,
requireState: false
}, (accessToken, refreshToken, profile, done) => {
done(null, profile);
}));
class passportModel extends global.yoho.BaseModel {
constructor(ctx) {
super(ctx);
}
signinByOpenID({ nickname, openId, sourceType, businessLine}) {
let param = {
nickname: nickname || '',
openId: openId,
source_type: sourceType, // esline-disable-line
method: 'app.passport.signinByOpenID'
};
if (businessLine) {
param.business_line = businessLine;
}
return this.get({ data: param });
}
syncUserSession({uid, sessionKey, req, res}) {
let userId = {
toString: () => {
return uid;
}
};
if (sessionKey) {
req.session.LOGIN_UID_ = uid;
req.session.SESSION_KEY = sessionKey;
res.cookie('_SESSION_KEY', authcode(sessionKey, '_SESSION_KEY', 2592000000, 'encode'), {
domain: 'yohobuy.com',
expires: new Date(Date.now() + 2592000000), // 有效期一年
httpOnly: true
});
userId.sessionKey = sessionKey;
}
return this.get({
data: {
uid,
method: 'app.passport.profile'
}
}).then((userInfo) => {
let salt = uuid.v4().substr(0, 8);
let saltedUid = uid + salt;
let saltedToken = sign.makeToken(saltedUid);
let publicToken = saltedToken + salt;
let data = userInfo.data;
let encryptionUid = aes.encryptionUid(uid);
if (data) {
data.profile_name = (data.profile_name || '').replace(/::/g, '');
let uidCookie = `${data.profile_name}::${encryptionUid}::${data.vip_info && data.vip_info.title}::${saltedToken}`;
res.cookie('_UID', uidCookie, {
domain: 'yohobuy.com',
expires: new Date(Date.now() + 2592000000) // 有效期一年
});
req.session.AVATAR = data.head_ico;
_.set(req.session, 'USER.AVATAR', data.head_ico);
_.set(req.session, 'USER.NAME', data.profile_name);
}
req.session.TOKEN = publicToken;
req.session.LOGIN_UID_ = uid;
_.set(req.session, 'USER.ENCRYPTION_UID', encryptionUid);
res.cookie('_TOKEN', publicToken, {
httpOnly: true,
domain: 'yohobuy.com',
expires: new Date(Date.now() + 2592000000) // 有效期一年
});
});
}
sendTaobaoBindCode(mobile) {
return this.post({
data: {
method: 'app.bind.sendCodeByTB',
source_type: 'taobao',
mobile
}
});
}
bindTaobaoAccountByCode({ mobile, code, openId }) {
return this.post({
data: {
method: 'app.bind.bindTBByCode',
source_type: 'taobao',
mobile,
code,
open_id: openId
}
});
}
};
const login = {
taobaoLogin(req, res, next) {
req.session.authState = uuid.v4();
return passport.authenticate('taobao', {
state: req.session.authState,
failWithError: true
})(req, res, next);
},
taobaoCallback(req, res, next) {
passport.authenticate('taobao', (err, user) => {
if (err || !user) {
log.error(`[authenticate error] source_type: taobao | err: ${JSON.stringify(err)}`);
return res.redirect(loginPage);
}
const model = req.ctx(passportModel);
return model.signinByOpenID({
openId: user.open_uid,
sourceType: 'taobao'
}).then(result => {
let redirectUrl = loginPage;
if (result.code === 200) {
if (_.get(result, 'data.is_bind') === 'N') {
redirectUrl = req.cookies.third_backurl ? url.parse(req.cookies.third_backurl) : homePage;
redirectUrl += redirectUrl.indexOf('?') > 0 ? '&' : '?';
redirectUrl += 'bind_code=' + encodeURIComponent(aes.dynamicEncryption(`taobao::${user.open_uid}`));
} else if (+_.get(result, 'data.uid') > 0) {
return model.syncUserSession({
uid: result.data.uid,
sessionKey: result.data.session_key,
req,
res
}).finally(() => {
let refer = req.cookies.third_backurl ? url.parse(req.cookies.third_backurl) : homePage;
return res.redirect(refer);
});
}
} else {
log.info(`[third login error] source_type: taobao | open_uid: ${user.open_uid} | msg: ${result.message}`);
}
return res.redirect(redirectUrl);
});
})(req, res, next);
}
};
const bind = {
getBindThirdInfo(bindCode) {
let info = aes.dynamicDecrypt(bindCode);
let bindInfo = {
timestamp: info.timestamp
};
if (info.val) {
let splitArr = info.val.split('::');
bindInfo.type = splitArr[0];
bindInfo.openId = splitArr[1];
}
return bindInfo;
},
sendSms(req, res, next) {
let { mobile, bindCode } = req.body || {};
let info = bind.getBindThirdInfo(bindCode);
if (info.type === 'taobao') {
req.ctx(passportModel).sendTaobaoBindCode(mobile).then(res.json).catch(next);
} else {
res.json({
code: 200,
message: `${info.type || ''} not found`
});
}
},
bindByCode(req, res, next) {
let { mobile, code, bindCode } = req.body || {};
let info = bind.getBindThirdInfo(bindCode);
if (info.type === 'taobao') {
const model = req.ctx(passportModel);
model.bindTaobaoAccountByCode({
mobile,
code,
openId: info.openId
}).then(result => {
if (_.get(result, 'data.is_bind') === 'Y') {
model.syncUserSession({
uid: result.data.uid,
sessionKey: result.data.session_key,
req,
res
}).finally(() => {
delete result.data;
res.json(result);
});
} else {
res.json(result);
}
}).catch(next);
} else {
res.json({
code: 400,
message: '登录失败请稍后重试'
});
}
}
}
module.exports = {
login,
bind
};