user.js
12.5 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/**
* 用户controller
* @author: leo <qi.li@yoho.cn>
* @date: 2017/06/26
*/
'use strict';
const _ = require('lodash');
const UserModel = require('../models/user');
const request = require('request-promise');
const INVALID_SESSION = '用户SESSION信息缺失, 请重新验证';
const INVALID_PARAM = '参数错误!';
const GET_USER_INFO_SUCCESS = '获取用户信息成功';
const GET_USER_INFO_FAILED = '授权失败,请重新授权';
const OUT_OF_EXPIRED = '授权已过期';
const INVALID_REFERER = '无效的来源';
const USER_NOT_FOUNT = '未寻找到用户信息';
const WECHAT_LOGIN_URL_YOHOBOYS = 'http://www.yohoboys.com/yohonow/WechatAuthController/authorize?callbackurl=';
const DEFAULT_REDIRECT_URL = 'http://www.yoho.cn';
const config = global.yoho.config;
let siteUrl = config.siteUrl.indexOf('//') === 0 ? 'http:' + config.siteUrl : config.siteUrl;
const userController = {
/**
* 获取用户信息
* @param req
* @param res
* @param next
*/
userInfo(req, res, next) {
const mobile = _.get(req.session, 'smsSend.mobile', '');
if (!mobile) {
res.json({
code: 403,
message: INVALID_SESSION
});
}
req.ctx(UserModel).getUser(mobile)
.then(result => {
let userInfo = {};
if (result.length) {
let user = result[0];
// 用户ID
_.set(req.session, 'user.id', user.id);
_.set(req.session, 'user.phone', user.user_phone);
res.json({
code: 200,
data: {
id: user.id,
name: user.user_name,
mobile: user.user_phone,
avatar: user.user_avatar
},
message: GET_USER_INFO_SUCCESS
});
} else {
let name = '用户' + mobile.substr(7);
let avatar = 'http://img12.static.yhbimg.com/' +
'imserver/2016/11/17/11/02bc3c3de856432175c01d937342a1f2ce.jpg';
userInfo = {
name,
avatar,
mobile
};
req.ctx(UserModel).createUser(userInfo)
.then((id) => {
// 用户ID
_.set(req.session, 'user.id', id);
_.set(req.session, 'user.phone', mobile);
res.json({
code: 200,
data: _.assign(userInfo, {id}),
message: GET_USER_INFO_SUCCESS
});
})
.catch(next);
}
})
.catch(next);
},
/**
* 获取微信用户信息(直接调用)
* @param req
* @param res
*/
newWechatUserInfo(req, res) {
res.json({
message: '获取用户信息成功'
});
},
/**
* 授权后跳转回调方法,获取授权信息,保存到数据库
* @param req
* @param res
* @param next
*/
async newWechatUserCallback(req, res) {
let {code = 10005, state} = req.query;
// console.log(req.session);
try {
if (code.toString().length > 5 && state === _.get(req.session, 'user.wechatState', '')) {
let appId = config.wechatLogin.appID;
let appSecret = config.wechatLogin.appSecret;
let WECHAT_GET_TOKEN = 'https://api.weixin.qq.com/sns/oauth2/access_token';
let WECHAT_GET_USERINFO = 'https://api.weixin.qq.com/sns/userinfo';
// console.log(WECHAT_GET_TOKEN + '?appid=' + appId + '&secret=' + appSecret + '&code=' + code + '&grant_type=authorization_code');
let tokenResult = await request({
url: WECHAT_GET_TOKEN,
qs: {
appid: appId,
secret: appSecret,
code: code,
grant_type: 'authorization_code'
},
json: true
});
// console.log('newWechatCallback', tokenResult);
if (!tokenResult.errcode) {
let access_token = tokenResult.access_token;
let union_id = tokenResult.unionid || tokenResult.openid;
let userInfo = await request({
url: WECHAT_GET_USERINFO,
qs: {
access_token: access_token,
openid: union_id,
lang: 'zh_CN'
},
json: true
});
let userInfoStr = JSON.stringify(userInfo);
// console.log('userInfoStr:', userInfoStr);
let referer = `${siteUrl}/passport/user/wechatCallback`;
let note = referer.indexOf('?') > 0 ? '&' : '?';
let redirectUrl = referer + note + 'wechatUserInfo=' + userInfoStr;
res.redirect(redirectUrl);
} else {
res.send({
code: 400,
message: '获取授权信息失败'
});
}
}
} catch (err) {
res.send(err);
}
},
/**
* 跳转微信授权(原生的)
* @param req
* @param res
*/
newWechatLogin(req, res) {
const referer = req.get('Referer') || 'http://www.yoho.cn';
let appId = config.wechatLogin.appID;
let scope = 'snsapi_userinfo';
let state = Math.random().toString(36).substr(2, 15);
let redirect_uri = encodeURIComponent(`${siteUrl}/passport/user/newWechatCallback`);
let WECHAT_LOGIN_URL =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
// console.log('WECHAT_LOGIN_URL:', WECHAT_LOGIN_URL);
// console.log('referer', referer, referer.indexOf('yoho.cn'));
if (referer && (referer.indexOf('yoho.cn') >= 0)) {
_.set(req.session, 'user.wechatReferer', referer);
_.set(req.session, 'user.wechatState', state);
// console.log(req.session);
res.redirect(WECHAT_LOGIN_URL);
} else {
res.json({
code: 200,
message: INVALID_REFERER
});
}
},
/**
* 获取微信用户信息(yohoboys)
* @param req
* @param res
*/
wechatUserInfo(req, res) {
const union_id = req.query.union_id;
if (!union_id) {
return res.json({
code: 403,
message: INVALID_PARAM
});
}
let session_union_id = _.get(req.session, 'user.union_id', '0');
// session_union_id = union_id;// 临时用,要删!!!!
if (union_id === session_union_id) { // 判断传过来的union_id和session中保存的union_id是否相同
return req.ctx(UserModel).getWechatUser(union_id)
.then(result => { // 获取用户的uid
if (result && result.length > 0) {
return res.json({
code: 200,
uid: result[0].id,
union_id: _.get(req.session, 'user.union_id', '0'),
head_img: _.get(req.session, 'user.head_img', ''),
user_name: _.get(req.session, 'user.user_name', '')
});
} else {
return res.json({
code: 204,
message: USER_NOT_FOUNT
});
}
});
} else {
return res.json({
code: 203,
message: OUT_OF_EXPIRED
});
}
},
/**
* 跳转微信授权(yohoboys)
* @param req
* @param res
*/
wechatUserLogin(req, res) {
const referer = req.get('Referer');
let redirect_url = `${siteUrl}/passport/user/wechatCallback`;
if (referer && (referer.indexOf('yoho.cn') || referer.indexOf('yhurl.com'))) {
_.set(req.session, 'npnp', referer);
res.redirect(WECHAT_LOGIN_URL_YOHOBOYS + encodeURIComponent(redirect_url));
} else {
res.json({
code: 401,
message: INVALID_REFERER
});
}
},
/**
* 授权后跳转回调方法,获取授权信息,保存到数据库
* @param req
* @param res
*/
wechatUserCallback(req, res, next) {
let wechatUserInfo;
try {
wechatUserInfo = JSON.parse(req.query.wechatUserInfo);
} catch (err) {
wechatUserInfo = {};
}
// console.log('wechatUserCallBack:', wechatUserInfo);
let user_name = '',
head_img = '',
union_id = '';
if (wechatUserInfo && wechatUserInfo.nickname) {
user_name = wechatUserInfo.nickname;
head_img = wechatUserInfo.headimgurl;
union_id = wechatUserInfo.unionid || wechatUserInfo.openid;
_.set(req.session, 'user.union_id', union_id);
_.set(req.session, 'user.head_img', head_img);
_.set(req.session, 'user.user_name', user_name);
// console.log(req.session);
return req.ctx(UserModel).getWechatUser(union_id)
.then(result => {
if (result.length > 0) { // 发现数据库有用户信息,则更新用户头像及昵称
return req.ctx(UserModel).modifyWechatUser(union_id, user_name, head_img)
.then(() => {
return Promise.resolve();
});
} else {
return req.ctx(UserModel).createWechatUser(union_id, user_name, head_img, 1)
.then(c_result => { // 发现数据库没有用户信息,则插入用户信息
if (c_result) {
return Promise.resolve();
} else {
return Promise.reject({code: 301, message: GET_USER_INFO_FAILED});
}
});
}
})
.then(() => { // 处理完毕后跳转回活动页面
let referer = _.get(req.session, 'user.wechatReferer', DEFAULT_REDIRECT_URL);
let note = referer.indexOf('?') >= 0 ? '&' : '?';
referer += note + 'union_id=' + union_id;
res.redirect(referer);
}, (result) => {
res.json(result);
}).catch(next);
} else {
res.json({
code: 301,
message: GET_USER_INFO_FAILED
});
}
},
/**
* 通过用户的union_id更新用户的手机号码
* @param req
* @param res
* @returns {Promise.<void>}
*/
async updateUserMobileByUnionId(req, res) {
let {unionId, phone, force = 0, token} = req.body;
let regPhone = /^1[3-9][0-9]{9}$/g;
if (!unionId || !phone || (!force && !token)) {
return res.json({
code: 400,
message: INVALID_PARAM
});
} else if (!phone.match(regPhone)) {
return res.json({
code: 400,
message: '手机号码格式错误'
});
}
let session_token = req.session.shoesToken;
let result = {};
console.log(token, session_token);
if (token === session_token) {
result = await req.ctx(UserModel).updateUserMobileByUnionId(unionId, phone, force);
} else {
result = {
code: 205,
message: '保存手机号失败,请重新扫码后再试'
};
}
return res.json(result);
}
};
module.exports = userController;