-
Notifications
You must be signed in to change notification settings - Fork 6
/
proxy.js
89 lines (63 loc) · 2.18 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
var http = require('http'),
httpProxy = require('http-proxy');
url = require('url');
var uri_root_path = process.env.URI_ROOT_PATH || '/user/default'
var workshop_app = 'http://127.0.0.1:8081';
var terminal_app = 'http://127.0.0.1:8082';
var terminal_url = '^' + uri_root_path + '/terminal/.*$';
var console_app = 'http://127.0.0.1:8083';
var console_url = '^' + uri_root_path + '/console/.*$';
var auth_username = process.env.AUTH_USERNAME;
var auth_password = process.env.AUTH_PASSWORD;
var proxy = httpProxy.createProxyServer();
function on_error(err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong.');
}
var server = http.createServer(function(req, res) {
var auth = req.headers['authorization'];
if (auth_username) {
if (!auth) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Terminal"');
res.end('Login required.');
}
else {
var tmp = auth.split(' ');
var buf = new Buffer(tmp[1], 'base64');
var plain_auth = buf.toString();
var creds = plain_auth.split(':');
var username = creds[0];
var password = creds[1];
if ((username != auth_username) || (password != auth_password)) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Terminal"');
res.end('Access denied.');
}
}
}
var target_app = workshop_app;
var parsed_url = url.parse(req.url);
if (parsed_url.pathname.match(terminal_url))
target_app = terminal_app;
if (parsed_url.pathname.match(console_url))
target_app = console_app;
res.oldWriteHead = res.writeHead;
res.writeHead = function(statusCode, headers) {
res.removeHeader('x-frame-options');
res.oldWriteHead(statusCode, headers);
}
proxy.web(req, res, { target: target_app }, on_error);
});
server.on('upgrade', function (req, socket, head) {
var target_app = workshop_app;
var parsed_url = url.parse(req.url);
if (parsed_url.pathname.match(terminal_url))
target_app = terminal_app;
if (parsed_url.pathname.match(console_url))
target_app = console_app;
proxy.ws(req, socket, head, { target: target_app }, on_error);
});
server.listen(8080, "0.0.0.0");