|
|
/**
|
|
|
* 登录
|
|
|
* @author: Bi Kai<kai.bi@yoho.cn>
|
|
|
* @date: 2016/05/09
|
|
|
*/
|
|
|
'use strict';
|
|
|
|
|
|
const library = '../../../library';
|
|
|
const passport = require('passport');
|
|
|
const cookie = require(`${library}/cookie`);
|
|
|
const helpers = require(`${library}/helpers`);
|
|
|
const log = require(`${library}/logger`);
|
|
|
const config = require('../../../config/common');
|
|
|
const AuthHelper = require('../models/auth-helper');
|
|
|
|
|
|
const loginPage = `${config.siteUrl}/passport/login/index`;
|
|
|
|
|
|
function doPassportCallback(openId, nickname, sourceType, req, res) {
|
|
|
let shoppingKey = cookie.getShoppingKey(req);
|
|
|
let refer = req.cookies.refer;
|
|
|
|
|
|
if (refer) {
|
|
|
refer = decodeURI(req.cookies.refer);
|
|
|
} else {
|
|
|
refer = `${config.siteUrl}/home`;
|
|
|
}
|
|
|
|
|
|
if (openId && nickname) {
|
|
|
AuthHelper.signinByOpenID(nickname, openId, sourceType, shoppingKey).then((result) => {
|
|
|
if (result.data['is_bind'] && result.data['is_bind'] === 'N') { //eslint-disable-line
|
|
|
return helpers.urlFormat('/passport/bind/index', {
|
|
|
openId: openId,
|
|
|
sourceType: sourceType,
|
|
|
refer: refer
|
|
|
});
|
|
|
} else if (result.code === 200 && result.data.uid) {
|
|
|
return AuthHelper.syncUserSession(result.data.uid, req, res).then(() => {
|
|
|
return refer;
|
|
|
});
|
|
|
}
|
|
|
}).then((redirectTo) => {
|
|
|
console.log('redirectTo=', redirectTo);
|
|
|
return res.redirect(redirectTo);
|
|
|
}).catch((e) => {
|
|
|
log.error('频道页面渲染错误:' + JSON.stringify(e));
|
|
|
return res.send('error');
|
|
|
});
|
|
|
}
|
|
|
}
|
|
|
|
|
|
const wechat = {
|
|
|
beforeLogin: (req, res, next) => {
|
|
|
let refer = req.query.refer;
|
|
|
|
|
|
if (!refer) {
|
|
|
refer = req.get('Referer');
|
|
|
}
|
|
|
refer && res.cookie('refer', encodeURI(refer));
|
|
|
next();
|
|
|
},
|
|
|
login: (req, res, next) => {
|
|
|
return passport.authenticate('weixin')(req, res, next);
|
|
|
},
|
|
|
callback: (req, res, next) => {
|
|
|
passport.authenticate('weixin', (err, user) => {
|
|
|
if (err) {
|
|
|
log.error(`wechat authenticate error : ${JSON.stringify(err)}`);
|
|
|
return res.redirect(loginPage);
|
|
|
}
|
|
|
let nickname = user.displayName || user._json.nickname;
|
|
|
let openId = user.id || user._json.unionid;
|
|
|
|
|
|
doPassportCallback(openId, nickname, 'wechat', req, res);
|
|
|
})(req, res, next);
|
|
|
}
|
|
|
};
|
|
|
|
|
|
exports.wechat = wechat; |
...
|
...
|
|