Commit c4f926e3 authored by Pedro Eduardo Trujillo's avatar Pedro Eduardo Trujillo
Browse files

Agrupa toda la lógica de peticiones externas

En lugar de exportar parte de las funciones necesarias para gestionar
las peticiones de contenidos externos, se agrupa toda esta lógica y
solamente se exportan las funciones finales, que recibirán las
peticiones de las rutas expuestas.

Aprovecha para permitir puntos externos http en config y sitemap.
parent 2b7c4f1d
Loading
Loading
Loading
Loading
+5 −125
Original line number Diff line number Diff line
const express = require('express'),
	bodyParser = require('body-parser'),
	path = require('path'),
	http = require('http'),
	https = require('https'),

	oauthUrl = process.env.OAUTH_URL,
	oauthClientId = process.env.OAUTH_CLIENT_ID,
	oauthClientSecret = process.env.OAUTH_CLIENT_SECRET,
	production = !!parseInt(process.env.PRODUCTION, 10),
	apiUrl = process.env.API_URL,
	configUrl = process.env.CONFIG_URL,
	sitemapUrl = process.env.SITEMAP_URL,
	apiUrl = process.env.API_URL;

	configExpirationMs = 3600000,
	sitemapExpirationMs = 36000000;

let logger, params, version, robotsContent, configContent, configLastUpdated, sitemapContent, sitemapLastUpdated,
	externalRequest;
let logger, params, version, robotsContent, externalRequest;

function getLang(req) {

@@ -65,56 +54,6 @@ function on404Request(req, res) {
	});
}

function onConfigRequest(req, res) {

	res.set('Content-Type', 'application/json');

	const currTimestamp = Date.now();

	if (!configContent || !configContent.length || req.query.forceRefresh ||
		configLastUpdated < currTimestamp - configExpirationMs) {

		const afterResponseCallback = (status, content) => configContent = status ? content : '';

		const internalReq = https.request(configUrl, externalRequest.onOwnRequestResponse.bind(this, {
			originalRes: res,
			afterResponse: afterResponseCallback
		}));

		internalReq.on('error', externalRequest.onOwnRequestError.bind(this, res));

		internalReq.end();

		configLastUpdated = currTimestamp;
	} else {
		res.send(configContent);
	}
}

function onSitemapRequest(_req, res) {

	res.set('Content-Type', 'text/xml');

	const currTimestamp = Date.now();

	if (!sitemapContent || !sitemapContent.length || sitemapLastUpdated < currTimestamp - sitemapExpirationMs) {
		const afterResponseCallback = (status, content) => sitemapContent = status ? content : '';

		const internalReq = https.request(sitemapUrl, externalRequest.onOwnRequestResponse.bind(this, {
			originalRes: res,
			afterResponse: afterResponseCallback
		}));

		internalReq.on('error', externalRequest.onOwnRequestError.bind(this, res));

		internalReq.end();

		sitemapLastUpdated = currTimestamp;
	} else {
		res.send(sitemapContent);
	}
}

function onRobotsRequest(req, res) {

	res.set('Content-Type', 'text/plain');
@@ -153,76 +92,17 @@ function onUnknownRequest(_req, res, _next) {
	res.redirect('/404');
}

function onOauthTokenRequest(req, res) {

	res.set('Content-Type', 'application/json');

	const getTokenUrl = oauthUrl + '/token',
		reqLibrary = getTokenUrl.indexOf('https') === -1 ? http : https;

	const clientCredentials = oauthClientId + ':' + oauthClientSecret,
		base64ClientCredentials = Buffer.from(clientCredentials).toString('base64');

	const options = {
		method: 'POST',
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
			'Authorization': 'Basic ' + base64ClientCredentials
		}
	};

	const bindParams = {
		originalRes: res,
		onError: onOauthRequestError
	};

	const internalReq = reqLibrary.request(getTokenUrl, options, externalRequest.onOwnRequestResponse.bind(this,
		bindParams));

	internalReq.on('error', onOauthRequestError.bind(this, res));

	const body = req.body,
		password = encodeURIComponent(body.password),
		username = encodeURIComponent(body.username),
		bodyData = 'grant_type=password&username=' + username + '&password=' + password + '&scope=write';

	internalReq.write(bodyData);
	internalReq.end();
}

function onOauthRequestError(originalRes, err) {

	const error = JSON.parse(err),
		errorType = error.error,
		errorDescription = error.error_description;

	if (errorType === 'invalid_grant') {
		originalRes.set('Content-Type', 'application/json');

		originalRes.status(401).send({
			code: errorType,
			description: errorDescription
		});

		logger.error(err);

		return;
	}

	externalRequest.onOwnRequestError.bind(this)(originalRes, err);
}

function exposeRoutes(app) {

	app.get('/activateAccount/:token', onActivateAccountRequest)
		.get('/noSupportBrowser', onNoSupportBrowserRequest)
		.get('/404', on404Request)
		.get('/config', onConfigRequest)
		.get('/sitemap.xml', onSitemapRequest)
		.get('/config', externalRequest.onConfigRequest)
		.get('/sitemap.xml', externalRequest.onSitemapRequest)
		.get('/robots.txt', onRobotsRequest)
		.get(/.*\/jquery.js/, onNullableRequest)
		.get(/.*/, onGeneralRequest)
		.post('/oauth/token', onOauthTokenRequest)
		.post('/oauth/token', externalRequest.onOauthTokenRequest)
		.use(onUnknownRequest);
}

+127 −3
Original line number Diff line number Diff line
let logger;
const http = require('http'),
	https = require('https'),

	oauthUrl = process.env.OAUTH_URL,
	oauthClientId = process.env.OAUTH_CLIENT_ID,
	oauthClientSecret = process.env.OAUTH_CLIENT_SECRET,
	configUrl = process.env.CONFIG_URL,
	sitemapUrl = process.env.SITEMAP_URL,

	configExpirationMs = 3600000,
	sitemapExpirationMs = 36000000;

let logger, configContent, configLastUpdated, sitemapContent, sitemapLastUpdated;

function onOwnRequestResponse(bindParams, internalRes) {

@@ -57,12 +69,124 @@ function onOwnRequestError(originalRes, err) {
	logger.error(errorMessage);
}

function onOauthTokenRequest(req, res) {

	res.set('Content-Type', 'application/json');

	const getTokenUrl = oauthUrl + '/token',
		reqLibrary = getTokenUrl.indexOf('https') === -1 ? http : https;

	const clientCredentials = oauthClientId + ':' + oauthClientSecret,
		base64ClientCredentials = Buffer.from(clientCredentials).toString('base64');

	const options = {
		method: 'POST',
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
			'Authorization': 'Basic ' + base64ClientCredentials
		}
	};

	const bindParams = {
		originalRes: res,
		onError: onOauthRequestError
	};

	const internalReq = reqLibrary.request(getTokenUrl, options, onOwnRequestResponse.bind(this,
		bindParams));

	internalReq.on('error', onOauthRequestError.bind(this, res));

	const body = req.body,
		password = encodeURIComponent(body.password),
		username = encodeURIComponent(body.username),
		bodyData = 'grant_type=password&username=' + username + '&password=' + password + '&scope=write';

	internalReq.write(bodyData);
	internalReq.end();
}

function onOauthRequestError(originalRes, err) {

	const error = JSON.parse(err),
		errorType = error.error,
		errorDescription = error.error_description;

	if (errorType === 'invalid_grant') {
		originalRes.set('Content-Type', 'application/json');

		originalRes.status(401).send({
			code: errorType,
			description: errorDescription
		});

		logger.error(err);

		return;
	}

	onOwnRequestError.bind(this)(originalRes, err);
}

function onConfigRequest(req, res) {

	res.set('Content-Type', 'application/json');

	const currTimestamp = Date.now();

	if (!configContent || !configContent.length || req.query.forceRefresh ||
		configLastUpdated < currTimestamp - configExpirationMs) {

		const afterResponseCallback = (status, content) => configContent = status ? content : '',
			reqLibrary = configUrl.indexOf('https') === -1 ? http : https;

		const internalReq = reqLibrary.request(configUrl, onOwnRequestResponse.bind(this, {
			originalRes: res,
			afterResponse: afterResponseCallback
		}));

		internalReq.on('error', onOwnRequestError.bind(this, res));

		internalReq.end();

		configLastUpdated = currTimestamp;
	} else {
		res.send(configContent);
	}
}

function onSitemapRequest(_req, res) {

	res.set('Content-Type', 'text/xml');

	const currTimestamp = Date.now();

	if (!sitemapContent || !sitemapContent.length || sitemapLastUpdated < currTimestamp - sitemapExpirationMs) {
		const afterResponseCallback = (status, content) => sitemapContent = status ? content : '',
			reqLibrary = sitemapUrl.indexOf('https') === -1 ? http : https;

		const internalReq = reqLibrary.request(sitemapUrl, onOwnRequestResponse.bind(this, {
			originalRes: res,
			afterResponse: afterResponseCallback
		}));

		internalReq.on('error', onOwnRequestError.bind(this, res));

		internalReq.end();

		sitemapLastUpdated = currTimestamp;
	} else {
		res.send(sitemapContent);
	}
}

module.exports = function(loggerParameter) {

	logger = loggerParameter;

	return {
		onOwnRequestResponse: onOwnRequestResponse,
		onOwnRequestError: onOwnRequestError
		onOauthTokenRequest: onOauthTokenRequest,
		onConfigRequest: onConfigRequest,
		onSitemapRequest: onSitemapRequest
	};
};