2020-07-10 14:13:16 +02:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
|
|
exports = module.exports = {
|
2021-09-25 17:19:58 -07:00
|
|
|
proxy,
|
2020-07-10 14:13:16 +02:00
|
|
|
};
|
|
|
|
|
|
2021-01-21 11:31:35 -08:00
|
|
|
const assert = require('assert'),
|
2020-07-10 14:13:16 +02:00
|
|
|
BoxError = require('../boxerror.js'),
|
|
|
|
|
middleware = require('../middleware/index.js'),
|
|
|
|
|
HttpError = require('connect-lastmile').HttpError,
|
2021-08-25 19:41:46 -07:00
|
|
|
safe = require('safetydance'),
|
2021-01-21 11:31:35 -08:00
|
|
|
services = require('../services.js'),
|
2020-07-10 14:13:16 +02:00
|
|
|
url = require('url');
|
|
|
|
|
|
2021-09-25 17:19:58 -07:00
|
|
|
function proxy(kind) {
|
|
|
|
|
assert(kind === 'mail' || kind === 'volume' || kind === 'app');
|
2020-07-10 14:13:16 +02:00
|
|
|
|
2021-09-25 17:19:58 -07:00
|
|
|
return async function (req, res, next) {
|
|
|
|
|
req.clearTimeout();
|
2020-07-13 16:26:42 +02:00
|
|
|
|
2021-09-25 17:19:58 -07:00
|
|
|
let id = null;
|
|
|
|
|
switch (kind) {
|
|
|
|
|
case 'app': id = `app-${req.params.id}`; break;
|
|
|
|
|
case 'volume': id = `volume-${req.params.id}`; break;
|
|
|
|
|
case 'mail': id = 'mail'; break;
|
|
|
|
|
}
|
2020-07-10 14:13:16 +02:00
|
|
|
|
2021-09-25 17:19:58 -07:00
|
|
|
const [error, result] = await safe(services.getContainerDetails('sftp', 'CLOUDRON_SFTP_TOKEN'));
|
|
|
|
|
if (error) return next(BoxError.toHttpError(error));
|
2020-07-10 14:13:16 +02:00
|
|
|
|
2021-09-25 17:19:58 -07:00
|
|
|
let parsedUrl = url.parse(req.url, true /* parseQueryString */);
|
|
|
|
|
parsedUrl.query['access_token'] = result.token;
|
2020-07-10 14:13:16 +02:00
|
|
|
|
2021-09-25 17:19:58 -07:00
|
|
|
req.url = url.format({ pathname: `/files/${id}/${encodeURIComponent(req.params[0])}`, query: parsedUrl.query }); // params[0] already contains leading '/'
|
2020-07-10 14:13:16 +02:00
|
|
|
|
2021-12-24 10:43:39 -08:00
|
|
|
const proxyOptions = url.parse(`http://${result.ip}:3000`);
|
2021-09-25 17:19:58 -07:00
|
|
|
proxyOptions.rejectUnauthorized = false;
|
|
|
|
|
const fileManagerProxy = middleware.proxy(proxyOptions);
|
2020-07-10 14:13:16 +02:00
|
|
|
|
2021-09-25 17:19:58 -07:00
|
|
|
fileManagerProxy(req, res, function (error) {
|
|
|
|
|
if (!error) return next();
|
2020-07-10 14:13:16 +02:00
|
|
|
|
2021-09-25 17:19:58 -07:00
|
|
|
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'));
|
2021-09-25 23:27:25 -07:00
|
|
|
|
2021-09-25 17:19:58 -07:00
|
|
|
next(new HttpError(500, error));
|
|
|
|
|
});
|
|
|
|
|
};
|
2021-09-25 23:27:25 -07:00
|
|
|
}
|