Files
cloudron-box/src/routes/mailserver.js
Girish Ramakrishnan d36b06acf7 Fix mail location route
2020-08-20 23:12:43 -07:00

69 lines
2.4 KiB
JavaScript

'use strict';
exports = module.exports = {
proxy,
getLocation,
setLocation
};
var addons = require('../addons.js'),
assert = require('assert'),
auditSource = require('../auditsource.js'),
BoxError = require('../boxerror.js'),
HttpError = require('connect-lastmile').HttpError,
HttpSuccess = require('connect-lastmile').HttpSuccess,
mail = require('../mail.js'),
middleware = require('../middleware/index.js'),
url = require('url');
function proxy(req, res, next) {
let parsedUrl = url.parse(req.url, true /* parseQueryString */);
const pathname = req.path.split('/').pop();
// do not proxy protected values
delete parsedUrl.query['access_token'];
delete req.headers['authorization'];
delete req.headers['cookies'];
addons.getContainerDetails('mail', 'CLOUDRON_MAIL_TOKEN', function (error, addonDetails) {
if (error) return next(BoxError.toHttpError(error));
parsedUrl.query['access_token'] = addonDetails.token;
req.url = url.format({ pathname: pathname, query: parsedUrl.query });
const proxyOptions = url.parse(`https://${addonDetails.ip}:3000`);
proxyOptions.rejectUnauthorized = false;
const mailserverProxy = middleware.proxy(proxyOptions);
mailserverProxy(req, res, function (error) {
if (!error) return next();
if (error.code === 'ECONNREFUSED') return next(new HttpError(424, 'Unable to connect to mail server'));
if (error.code === 'ECONNRESET') return next(new HttpError(424, 'Unable to query mail server'));
next(new HttpError(500, error));
});
});
}
function getLocation(req, res, next) {
mail.getLocation(function (error, result) {
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(200, { domain: result.domain, subdomain: result.subdomain }));
});
}
function setLocation(req, res, next) {
assert.strictEqual(typeof req.body, 'object');
if (typeof req.body.domain !== 'string') return next(new HttpError(400, 'domain must be a string'));
if (typeof req.body.subdomain !== 'string') return next(new HttpError(400, 'subdomain must be a string'));
mail.setLocation(req.body.subdomain, req.body.domain, auditSource.fromRequest(req), function (error, taskId) {
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(202, { taskId }));
});
}