init api rate-limit on geolocation api routes

This commit is contained in:
sedum
2023-01-13 22:28:38 +01:00
parent 749c656784
commit 7fa2e1aa0c
4 changed files with 47 additions and 5 deletions

View File

@@ -0,0 +1,38 @@
const rateLimit = require('express-rate-limit');
const log = require('../../log')
let curReq
const geolocationController = {
rateLimiter: rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
}),
/**
* Limit api usage
* From https://operations.osmfoundation.org/policies/nominatim/
* [Requirements] No heavy uses (an absolute maximum of 1 request per second).
* [Websites and Apps] Note that the usage limits above apply per website/application: the sum of traffic by all your users should not exceed the limits.
*/
apiLimit (req, res, next) {
prevReq = curReq
curReq = Date.now()
deltaTime = (curReq - prevReq)
if (typeof prevReq === 'undefined' || deltaTime > 1000) {
geolocationController.rateLimiter(req, res, next)
} else {
log.warn('More than 1 request per second to geolocation api come from ' + req.ip)
setTimeout(() => {
geolocationController.rateLimiter(req, res, next)
}, 1000 - deltaTime)
}
}
}
module.exports = geolocationController

View File

@@ -19,6 +19,7 @@ const resourceController = require('./controller/resource')
const oauthController = require('./controller/oauth')
const announceController = require('./controller/announce')
const pluginController = require('./controller/plugins')
const geolocationController = require('./controller/geolocation')
const helpers = require('../helpers')
const storage = require('./storage')
@@ -65,7 +66,6 @@ module.exports = () => {
api.get('/ping', (_req, res) => res.sendStatus(200))
api.get('/user', isAuth, (req, res) => res.json(req.user))
api.post('/user/recover', userController.forgotPassword)
api.post('/user/check_recover_code', userController.checkRecoverCode)
api.post('/user/recover_password', userController.updatePasswordWithRecoverCode)
@@ -173,8 +173,8 @@ module.exports = () => {
api.put('/place', isAdmin, placeController.updatePlace)
// - GEOCODING
api.get('/placeOSM/Nominatim/:place_details', helpers.isGeocodingEnabled, placeController._nominatim)
api.get('/placeOSM/Photon/:place_details', helpers.isGeocodingEnabled, placeController._photon)
api.get('/placeOSM/Nominatim/:place_details', helpers.isGeocodingEnabled, geolocationController.apiLimit, placeController._nominatim)
api.get('/placeOSM/Photon/:place_details', helpers.isGeocodingEnabled, geolocationController.apiLimit, placeController._photon)
// - TAGS
api.get('/tags', isAdmin, tagController.getAll)