-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathnode-proxy.js
More file actions
50 lines (34 loc) · 1.58 KB
/
node-proxy.js
File metadata and controls
50 lines (34 loc) · 1.58 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
const http = require('http');
const httpProxy = require('http-proxy');
const auth = require('basic-auth');
// Create a proxy server with custom application logic
const proxy = httpProxy.createProxyServer({changeOrigin: true, autoRewrite: true, hostRewrite: true, followRedirects: true});
const server = http.createServer(function(req, res) {
// load from ENVs
const origin = process.env.ORIGIN;
const password = process.env.PASSWORD || null;
const username = process.env.USERNAME || null;
const credentialsConfigured = username && password;
// console.log('ORIGIN:', process.env.ORIGIN);
const credentials = auth(req);
if (credentialsConfigured && (!credentials || !isAuthed(credentials, username, password))) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="example"');
res.end('Access denied.');
} else {
// do nothing
// res.end('Access granted')
}
proxy.on('proxyRes', function(proxyRes, req, res) {
// console.log('Raw [target] response', JSON.stringify(proxyRes.headers, true, 2));
proxyRes.headers['x-proxy'] = "simple-basic-http-auth-proxy-vercel";
// console.log('Updated [proxy] response', JSON.stringify(proxyRes.headers, true, 2));
});
proxy.web(req, res, { target: `${origin}` });
});
const port = process.env.AWS_LAMBDA_RUNTIME_API.split(':')[1];
console.log(`simple-basic-http-auth-proxy for Vercel started on port ${port}`);
server.listen(port);
const isAuthed = function (credentials, username, password) {
return credentials.name === username && credentials.pass === password;
}