diff --git a/README.md b/README.md index f636b7c..09c6b2a 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,20 @@ NLU_URL= NLU_API_KEY= ``` +In the same `.env` file, add a comma separated list of origins that will be allowed to make cross site requests. + +If any origin can make the requests, just use the "*" value. + +``` +ALLOWED_ORIGINS= +``` + +For example: +``` +ALLOWED_ORIGINS=http://localhost:3001 +``` + + ### Customize Create an `.env` file to start the application in [cluster mode](https://nodejs.org/api/cluster.html#cluster_cluster), change its running port, log level, directory and maximum size. The variable names and default values are: diff --git a/src/controllers/translations/retrieve.js b/src/controllers/translations/retrieve.js index e58046b..fac5271 100644 --- a/src/controllers/translations/retrieve.js +++ b/src/controllers/translations/retrieve.js @@ -3,15 +3,17 @@ const mongo = require('src/databases/mongo') const NotFoundError = require('src/errors/not-found') module.exports = async (language, signed) => { + const translationData = { signed, spoken: null } const signedProcessedText = await text.process(signed) - const translation = await retrieveData(language, 'translations', { signed: signedProcessedText.hash }) - if (!translation) throw new NotFoundError() + if (!translation) { + throw new NotFoundError() + } const spoken = await retrieveData(language, 'spoken', { hash: translation.spoken }) - - return { signed, spoken: spoken.text } + translationData.spoken = spoken ? spoken.text : null + return translationData } function retrieveData (language, collection, query) { diff --git a/src/routes/translate/get.js b/src/routes/translate/get.js index 4e7a3e6..b4afeae 100644 --- a/src/routes/translate/get.js +++ b/src/routes/translate/get.js @@ -29,6 +29,7 @@ const joi = require('joi') const translations = require('src/controllers/translations') const BadRequestError = require('src/errors/bad-request') +require('dotenv').config() const schema = joi.object({ params: { @@ -47,6 +48,18 @@ module.exports = (req, res, next) => { translations.retrieve(value.params.language, sanitize(value.query.text)) .then(response => { res.locals = response + const allowedOriginsString = process.env.ALLOWED_ORIGINS + if (allowedOriginsString) { + if (allowedOriginsString === '*') { + res.set('Access-Control-Allow-Origin', '*') + } else { + const allowedOriginsArray = allowedOriginsString.split(',') + const requestOrigin = req.headers.origin + if (allowedOriginsArray.includes(requestOrigin)) { + res.set('Access-Control-Allow-Origin', requestOrigin) + } + } + } next(null, req, res) }) .catch(error => next(error))