forked from duxianwei520/react
/
proxy.js
95 lines (84 loc) · 2.8 KB
/
proxy.js
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
var request = require('request'),
url = require('url');
var config = require('./.config.json');
var CAS_SERVER = config.DEFAULT_CAS_SERVER;
var args = process.argv.slice(2),
targetIndex = process.env.PROXY_TARGET || "DEFAULT",
Target, COOKIE = "";
Target = config.TARGET_LIST[targetIndex.toUpperCase()];
module.exports = function() {
return config.proxyPaths.map((path, inndex) => {
return {
path,
target: Target,
secure: false,
bypass: proxyPass
}
})
}
function proxyPass(req, res, options) {
res.on('finish', function(){
if (res.statusCode === 401 && res._headers.urltoredirectto) {
var location = res._headers.urltoredirectto;
console.error('COOKIE expired, redirect to ',location, ' for new COOKIE');
login({
username: config.username,
password: config.password,
location: location
}, function(cookieKV){
console.log('COOKIE has been set as ', cookieKV);
COOKIE = cookieKV;
})
};
});
req.headers.cookie = COOKIE;
}
function login(options, callback) {
var username = options.username,
password = options.password,
CAS_SERVER = options.server || CAS_SERVER,
service = options.service || (Target + "/");
if (options.location) {
var result = url.parse(options.location),
_server = result.protocol+"//"+result.host,
_service = result.query.split("=")[1];
CAS_SERVER = _server,
service = decodeURIComponent(_service)+"/";
}
getTGTLocation(username, password, function(error, location){
getTicket(location, service, function(ticket){
request.get(service+"?ticket="+ticket, function(error, response, body){
var cookieKV;
if (~response.request.uri.href.indexOf('jsessionid')) {
cookieKV = response.request.uri.href.split(";")[1].toUpperCase();
}else {
var referer = response.request.headers.referer,
cookieKV = referer.split(";")[1].toUpperCase();
}
callback(cookieKV);
})
})
})
}
function getTGTLocation(username, password, callback) {
request.post({
url: CAS_SERVER + '/v1/tickets',
form: {
username: username,
password: password
}
}, function(error, response, body){
var location = response.headers.location;
callback(null, location)
})
}
function getTicket(location, service, callback) {
request.post({
url: location,
form: {
service: service
}
}, function(error, response, body){
callback(body);
})
}