More granular control over query handling
This commit is contained in:
		
							
								
								
									
										27
									
								
								modules/middleware/allowQuery.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										27
									
								
								modules/middleware/allowQuery.js
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,27 @@ | ||||
| import createSearch from '../utils/createSearch.js'; | ||||
|  | ||||
| /** | ||||
|  * Reject URLs with invalid query parameters to increase cache hit rates. | ||||
|  */ | ||||
| export default function allowQuery(validKeys = []) { | ||||
|   if (!Array.isArray(validKeys)) { | ||||
|     validKeys = [validKeys]; | ||||
|   } | ||||
|  | ||||
|   return (req, res, next) => { | ||||
|     const keys = Object.keys(req.query); | ||||
|  | ||||
|     if (!keys.every(key => validKeys.includes(key))) { | ||||
|       const newQuery = keys | ||||
|         .filter(key => validKeys.includes(key)) | ||||
|         .reduce((query, key) => { | ||||
|           query[key] = req.query[key]; | ||||
|           return query; | ||||
|         }, {}); | ||||
|  | ||||
|       return res.redirect(302, req.baseUrl + req.path + createSearch(newQuery)); | ||||
|     } | ||||
|  | ||||
|     next(); | ||||
|   }; | ||||
| } | ||||
| @ -1,29 +0,0 @@ | ||||
| import createSearch from '../utils/createSearch.js'; | ||||
|  | ||||
| const knownQueryParams = { | ||||
|   main: true, // Deprecated, see #63 | ||||
|   meta: true, | ||||
|   module: true | ||||
| }; | ||||
|  | ||||
| function isKnownQueryParam(param) { | ||||
|   return !!knownQueryParams[param]; | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Reject URLs with invalid query parameters to increase cache hit rates. | ||||
|  */ | ||||
| export default function validateQuery(req, res, next) { | ||||
|   const keys = Object.keys(req.query); | ||||
|  | ||||
|   if (!keys.every(isKnownQueryParam)) { | ||||
|     const newQuery = keys.filter(isKnownQueryParam).reduce((query, key) => { | ||||
|       query[key] = req.query[key]; | ||||
|       return query; | ||||
|     }, {}); | ||||
|  | ||||
|     return res.redirect(302, req.path + createSearch(newQuery)); | ||||
|   } | ||||
|  | ||||
|   next(); | ||||
| } | ||||
		Reference in New Issue
	
	Block a user