Files
cloudron-box/src/routes/filemanager.js
2021-12-24 15:05:51 -08:00

50 lines
1.7 KiB
JavaScript

'use strict';
exports = module.exports = {
proxy,
};
const assert = require('assert'),
BoxError = require('../boxerror.js'),
middleware = require('../middleware/index.js'),
HttpError = require('connect-lastmile').HttpError,
safe = require('safetydance'),
services = require('../services.js'),
url = require('url');
function proxy(kind) {
assert(kind === 'mail' || kind === 'volume' || kind === 'app');
return async function (req, res, next) {
req.clearTimeout();
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;
}
const [error, result] = await safe(services.getContainerDetails('sftp', 'CLOUDRON_SFTP_TOKEN'));
if (error) return next(BoxError.toHttpError(error));
let parsedUrl = url.parse(req.url, true /* parseQueryString */);
parsedUrl.query['access_token'] = result.token;
req.url = url.format({ pathname: `/files/${id}/${encodeURIComponent(req.params[0])}`, query: parsedUrl.query }); // params[0] already contains leading '/'
const proxyOptions = url.parse(`http://${result.ip}:3000`);
proxyOptions.rejectUnauthorized = false;
const fileManagerProxy = middleware.proxy(proxyOptions);
fileManagerProxy(req, res, function (error) {
if (!error) return next();
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));
});
};
}