diff --git a/package-lock.json b/package-lock.json index 442b76f5c..860c7bb58 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3023,7 +3023,7 @@ "color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" }, "colorette": { "version": "2.0.19", @@ -3355,7 +3355,7 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==" }, "eslint": { "version": "8.47.0", @@ -4879,7 +4879,7 @@ "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==" }, "has-property-descriptors": { "version": "1.0.0", @@ -5561,7 +5561,7 @@ "lodash.debounce": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", - "integrity": "sha1-gteb/zCmfEAF/9XiUVMArZyk168=" + "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==" }, "lodash.merge": { "version": "4.6.2", @@ -6898,7 +6898,7 @@ "path-exists": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", - "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=" + "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==" }, "path-is-absolute": { "version": "1.0.1", @@ -8332,7 +8332,7 @@ "yallist": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "integrity": "sha512-ncTzHV7NvsQZkYe1DW7cbDLm0YpzHmZF5r/iyP3ZnQtMiJ+pjzisCiMNI+Sj+xQF5pXhSHxSB3uDbsBTzY/c2A==", "dev": true }, "yaml": { diff --git a/src/controllers/timeZoneAPIController.js b/src/controllers/timeZoneAPIController.js index 3c4df0a22..07c9c0b17 100644 --- a/src/controllers/timeZoneAPIController.js +++ b/src/controllers/timeZoneAPIController.js @@ -1,22 +1,96 @@ +// eslint-disable-next-line import/no-extraneous-dependencies +const fetch = require('node-fetch'); +const ProfileInitialSetupToken = require('../models/profileInitialSetupToken'); const { hasPermission } = require('../utilities/permissions'); +const premiumKey = process.env.TIMEZONE_PREMIUM_KEY; +const commonKey = process.env.TIMEZONE_COMMON_KEY; + +const performTimeZoneRequest = async (req, res, apiKey) => { + const { location } = req.params; + + if (!location) { + res.status(400).send('Missing location'); + return; + } + + try { + const geocodeAPIEndpoint = 'https://api.opencagedata.com/geocode/v1/json'; + const url = `${geocodeAPIEndpoint}?key=${apiKey}&q=${location}&pretty=1&limit=1`; + + const response = await fetch(url); + const data = await response.json(); + + if (data.status.code !== 200) { + const err = new Error(`opencage error- ${data.status.message}`); + err.status = data.status.code; + throw err; + } + + if (data.results && data.results.length) { + const timezone = data.results[0].annotations.timezone.name; + const currentLocation = { + userProvided: location, + coords: { + lat: data.results[0].geometry.lat, + lng: data.results[0].geometry.lng, + }, + country: data.results[0].components.country || '', + city: data.results[0].components.city || '', + }; + res.status(200).send({ timezone, currentLocation }); + } else { + res.status(404).send('No results found'); + } + } catch (err) { + const errorMessage = err?.data?.status?.message + ? `opencage error, ${err?.data?.status?.message}` + : err.message; + const errorCode = err?.status || 500; + res.status(errorCode).send(errorMessage); + } +}; + const timeZoneAPIController = function () { - const getTimeZoneAPIKey = async (req, res) => { - const premiumKey = process.env.TIMEZONE_PREMIUM_KEY; - const commonKey = process.env.TIMEZONE_COMMON_KEY; - if (!req.body.requestor.role) { + const getTimeZone = async (req, res) => { + const { requestor } = req.body; + + if (!requestor.role) { res.status(403).send('Unauthorized Request'); return; } - if (await hasPermission(req.body.requestor, 'getTimeZoneAPIKey')) { - res.status(200).send({ userAPIKey: premiumKey }); + + const userAPIKey = (await hasPermission(requestor, 'getTimeZoneAPIKey')) + ? premiumKey + : commonKey; + if (!userAPIKey) { + res.status(401).send('API Key Missing'); + return; + } + + await performTimeZoneRequest(req, res, userAPIKey); + }; + + const getTimeZoneProfileInitialSetup = async (req, res) => { + const { token } = req.body; + if (!token) { + res.status(400).send('Missing token'); return; } - res.status(200).send({ userAPIKey: commonKey }); + + const foundToken = await ProfileInitialSetupToken.findOne({ token }); + if (!foundToken) { + res.status(403).send('Unauthorized Request'); + return; + } + + const userAPIKey = commonKey; + await performTimeZoneRequest(req, res, userAPIKey); }; return { - getTimeZoneAPIKey, + getTimeZone, + getTimeZoneProfileInitialSetup, }; }; diff --git a/src/routes/timeZoneAPIRoutes.js b/src/routes/timeZoneAPIRoutes.js index 5682ed36f..75e111c3e 100644 --- a/src/routes/timeZoneAPIRoutes.js +++ b/src/routes/timeZoneAPIRoutes.js @@ -4,8 +4,9 @@ const routes = function () { const controller = require('../controllers/timeZoneAPIController')(); const timeZoneAPIRouter = express.Router(); - timeZoneAPIRouter.route('/timezone') - .get(controller.getTimeZoneAPIKey); + timeZoneAPIRouter.route('/timezone/:location') + .get(controller.getTimeZone) + .post(controller.getTimeZoneProfileInitialSetup); return timeZoneAPIRouter; }; diff --git a/src/startup/middleware.js b/src/startup/middleware.js index d75884b98..aa9dff036 100644 --- a/src/startup/middleware.js +++ b/src/startup/middleware.js @@ -21,7 +21,7 @@ module.exports = function (app) { next(); return; } - if (req.originalUrl === '/api/ProfileInitialSetup' || req.originalUrl === '/api/validateToken' || req.originalUrl === '/api/getTimeZoneAPIKeyByToken' && req.method === 'POST' || req.originalUrl === '/api/getTotalCountryCount' && req.method === 'GET' + if (((req.originalUrl === '/api/ProfileInitialSetup' || req.originalUrl === '/api/validateToken' || req.originalUrl === '/api/getTimeZoneAPIKeyByToken') && req.method === 'POST') || (req.originalUrl === '/api/getTotalCountryCount' && req.method === 'GET') || (req.originalUrl.includes('/api/timezone') && req.method === 'POST') ) { next(); return;