'use strict'; exports = module.exports = { proxy, restart, getLocation, setLocation }; const assert = require('assert'), auditSource = require('../auditsource.js'), BoxError = require('../boxerror.js'), debug = require('debug')('box:routes/mailserver'), HttpError = require('connect-lastmile').HttpError, HttpSuccess = require('connect-lastmile').HttpSuccess, mail = require('../mail.js'), middleware = require('../middleware/index.js'), services = require('../services.js'), url = require('url'); function restart(req, res, next) { mail.restartMail((error) => debug('Error restarting mail container', error)); next(); } 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']; services.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); req.clearTimeout(); // TODO: add timeout to mail server proxy logic instead of this 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 })); }); }