user-center-auth
Version:
a user-center-auth middleware
106 lines (94 loc) • 2.82 kB
JavaScript
const URL = require('url');
const request = require('superagent');
const pathToRegexp = require('path-to-regexp')
/**
* format querystring
*/
const format = (query) => {
if(!query){
return query;
}
if(query.indexOf('?') >= 0){
const qs = query.split('?');
return qs[0];
}
return query;
}
/**
* 1, 检查有没有session
* 2, 检查query中有没有带有ucTicket
* 3, 没有ucTicket -> GET res.redirect()
* -> OTHER res.error('need login')
* 有ucTicket -> 通过infoUrl请求userinfo -> 写入session
* -> 请求失败 -> GET 请求 -> redirect
* -> OTHERS -> ERROR
*/
module.exports = (app, config) => {
const {loginUrl, infoUrl, exclude, logoutUrl = '/logout'} = config;
let excludePath = [];
if(typeof exclude === 'string'){
excludePath = [exclude];
}
if(Array.isArray(exclude)){
excludePath = exclude;
}
return (req, res, next) => {
if(req.path === logoutUrl){
req.session.user = null;
req.session.ucTicket = null;
return res.redirect(
(app.config && app.config.prefix)
|| '/'
);
}
// 筛选掉不需要监听的路径
if(excludePath.length !== 0){
try{
for(let pathstr of excludePath){
const re = pathToRegexp(pathstr);
if(re.test(req.path)){
return next();
}
}
}catch(e){
console.log(e);
}
}
if(!req.session.user){
let fromHeader = false;
let ucTicket = format(req.query.ucTicket);
if(!ucTicket) {
ucTicket = req.headers['x-uc-ticket'];
fromHeader = true
}
if(!ucTicket){
if(req.method === 'GET'){
return res.redirect(loginUrl + '?callback=http://' + req.headers.host + req.originalUrl);
}
return res.send({code: 'ERROR', data: 'NEED_LOGIN'});
}
if(ucTicket){
request(infoUrl + '?ucTicket=' + ucTicket).then(d => d.body).then(result => {
req.session.user = result.data;
req.session.ucTicket = ucTicket;
const host = req.headers.host;
const originalUrl = req.originalUrl;
const url = URL.parse(originalUrl);
if(fromHeader) {
return next();
} else {
return res.redirect(`http://${host}${url.pathname}`);
}
}).catch(e => {
console.log(e.stack || e.message || e);
if(req.method === 'GET'){
return res.redirect(loginUrl + '?callback=http://' + req.headers.host + req.originalUrl);
}
res.send({code: 'ERROR', message: 'LOGIN_SERVICE_ERROR', detail: e.stack || e.message });
});
}
} else {
next();
}
}
}