proxy-middleware: no more a middleware
This commit is contained in:
+26
-18
@@ -6,11 +6,10 @@ exports = module.exports = {
|
||||
|
||||
const assert = require('assert'),
|
||||
BoxError = require('../boxerror.js'),
|
||||
middleware = require('../middleware/index.js'),
|
||||
http = require('http'),
|
||||
HttpError = require('connect-lastmile').HttpError,
|
||||
safe = require('safetydance'),
|
||||
services = require('../services.js'),
|
||||
url = require('url');
|
||||
services = require('../services.js');
|
||||
|
||||
function proxy(kind) {
|
||||
assert(kind === 'mail' || kind === 'volume' || kind === 'app');
|
||||
@@ -25,23 +24,32 @@ function proxy(kind) {
|
||||
case 'mail': id = 'mail'; break;
|
||||
}
|
||||
|
||||
const [error, result] = await safe(services.getContainerDetails('sftp', 'CLOUDRON_SFTP_TOKEN'));
|
||||
const [error, addonDetails] = await safe(services.getContainerDetails('sftp', 'CLOUDRON_SFTP_TOKEN'));
|
||||
if (error) return next(BoxError.toHttpError(error));
|
||||
|
||||
const parsedUrl = url.parse(req.url, true /* parseQueryString */);
|
||||
parsedUrl.query['access_token'] = result.token;
|
||||
const searchParams = new URLSearchParams(req.url.slice(req.url.indexOf('?')+1));
|
||||
searchParams.delete('access_token');
|
||||
searchParams.append('access_token', addonDetails.token);
|
||||
|
||||
req.url = url.format({ pathname: `/files/${id}/${encodeURIComponent(req.params[0])}`, query: parsedUrl.query }); // params[0] already contains leading '/'
|
||||
const opts = {
|
||||
hostname: addonDetails.ip,
|
||||
port: 3000,
|
||||
path: `/files/${id}/${encodeURIComponent(req.params[0])}?${searchParams.toString()}`, // params[0] already contains leading '/'
|
||||
method: req.method,
|
||||
headers: req.headers
|
||||
};
|
||||
|
||||
const fileManagerProxy = middleware.proxy(`http://${result.ip}:3000`);
|
||||
|
||||
fileManagerProxy(req, res, function (error) {
|
||||
if (!error) return; // note: response was already sent by proxy by this point
|
||||
|
||||
if (error.code === 'ECONNREFUSED') return next(new HttpError(424, 'Unable to connect to filemanager server'));
|
||||
if (error.code === 'ECONNRESET') return next(new HttpError(424, 'Unable to query filemanager server'));
|
||||
|
||||
next(new HttpError(500, error));
|
||||
});
|
||||
};
|
||||
const sftpReq = http.request(opts, function (sftpRes) {
|
||||
res.writeHead(sftpRes.statusCode, sftpRes.headers);
|
||||
sftpRes.on('error', (error) => next(new HttpError(500, `filemanager error: ${error.message} ${error.code}`)));
|
||||
sftpRes.on('end', () => next());
|
||||
sftpRes.pipe(res);
|
||||
});
|
||||
sftpReq.on('error', (error) => next(new HttpError(424, `Unable to connect to filemanager: ${error.message} ${error.code}`)));
|
||||
if (!req.readable) {
|
||||
sftpReq.end();
|
||||
} else {
|
||||
req.pipe(sftpReq);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user