diff --git a/backend/routes/utils.js b/backend/routes/utils.js new file mode 100644 index 0000000..12d5bf8 --- /dev/null +++ b/backend/routes/utils.js @@ -0,0 +1,50 @@ +// api.js +const https = require("https"); +const axios = require("axios"); +const express = require("express"); + +const router = express.Router(); + +const geoliteUrlBase = 'https://geolite.info/geoip/v2.1/city'; + +const geoliteAccountId = process.env.GEOLITE_ACCOUNT_ID; +const geoliteLicenseKey = process.env.GEOLITE_LICENSE_KEY; + +//https://stackoverflow.com/questions/5284147/validating-ipv4-addresses-with-regexp +const ipRegex = new RegExp(`^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$`); + +const agent = new https.Agent({ + rejectUnauthorized: (process.env.REJECT_SELF_SIGNED_CERTIFICATES || 'true').toLowerCase() ==='true' +}); + +const axios_instance = axios.create({ + httpsAgent: agent +}); + +router.get("/geolocateIp", async (req, res) => { + try { + if(!(geoliteAccountId && geoliteLicenseKey)) { + return res.status(501).send('GeoLite information missing!'); + } + + const { ipAddress } = req.body; + ipRegex.lastIndex = 0; + + if(!ipAddress || !ipRegex.test(ipAddress)) { + return res.status(400).send('Invalid IP address sent!'); + } + + const response = await axios_instance.get(`${geoliteUrlBase}/${ipAddress}`, { + auth: { + username: geoliteAccountId, + password: geoliteLicenseKey + } + }); + return res.send(response.data); + } catch (error) { + res.status(503); + res.send(error); + } +}); + +module.exports = router; \ No newline at end of file diff --git a/backend/server.js b/backend/server.js index 435635a..1e2a357 100644 --- a/backend/server.js +++ b/backend/server.js @@ -15,6 +15,7 @@ const ActivityMonitor = require('./tasks/ActivityMonitor'); const SyncTask = require('./tasks/SyncTask'); const BackupTask = require('./tasks/BackupTask'); const logRouter = require('./routes/logging'); +const utilsRouter = require('./routes/utils'); const dbInstance = require("./db"); @@ -109,6 +110,7 @@ app.use('/sync', authenticate , syncRouter.router,()=>{/* #swagger.tags = ['Syn app.use('/stats', authenticate , statsRouter,()=>{/* #swagger.tags = ['Stats']*/}); // mount the API router at /stats, with JWT middleware app.use('/backup', authenticate , backupRouter.router,()=>{/* #swagger.tags = ['Backup']*/}); // mount the API router at /backup, with JWT middleware app.use('/logs', authenticate , logRouter.router,()=>{/* #swagger.tags = ['Logs']*/}); // mount the API router at /logs, with JWT middleware +app.use('/utils', authenticate, utilsRouter, ()=>{/* #swagger.tags = ['Utils']*/}); // mount the API router at /utils, with JWT middleware const swaggerUi = require('swagger-ui-express'); const swaggerDocument = require('./swagger.json');