Skip to content
Snippets Groups Projects
Commit 797a151e authored by Sigmund, Dominik's avatar Sigmund, Dominik Committed by Sigmund, Dominik
Browse files

Added Regex for defined routes

parent 7f92ce41
Branches
Tags
No related merge requests found
Source diff could not be displayed: it is too large. Options to address this: view the blob.
......@@ -10,13 +10,17 @@ const app = express()
app.use(security({
onlyDefinedRoutes: true,
definedRoutes: ['/']
definedRoutes: ['/', 'REGEX:\\/id\\/\\d{1,}']
}))
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.get('/id/:id', function (req, res) {
res.send('Hello numerical id: ' + req.params.id)
})
try {
fs.accessSync(__dirname + '/private.key')
var privateKey = fs.readFileSync(__dirname + '/private.key', 'utf8')
......
......@@ -116,8 +116,21 @@ module.exports = function(options) {
if (!options.definedRoutes) {
options.definedRoutes = []
}
if (!options.definedRoutes.includes(req.originalUrl)) {
let isAllowed = false;
for (const allowedRoute of options.definedRoutes) {
if (allowedRoute.startsWith('REGEX:')) {
let regexString = allowedRoute.split('REGEX:')[1];
let regexp = new RegExp(regexString);
if (regexp.test(req.originalUrl)) {
isAllowed= true;
}
} else {
if (req.originalUrl === allowedRoute) {
isAllowed = true;
}
}
}
if (!isAllowed) {
res.status(405).end()
}
}
......
......@@ -266,6 +266,29 @@ describe('Integration Tests', () => {
done()
})
})
it('should allow regex route if set', (done) => {
startUpServer({
onlyDefinedRoutes: true,
definedRoutes: ['/', 'REGEX:\\/test\\/\\d{1,}']
})
superagent
.get('http://127.0.0.1:7777')
.then(res => {
expect(res.status).toBe(200)
superagent
.get('http://127.0.0.1:7777/test')
.then(res2 => {})
.catch((error) => {
expect(error.status).toBe(405)
superagent
.get('http://127.0.0.1:7777/test/123')
.then(res3 => {
expect(res3.status).toBe(200)
done()
})
})
})
})
})
})
......@@ -345,5 +368,8 @@ function startUpServer(options) {
app.get('/test', function (req, res) {
res.send('Hello Test!')
})
app.get('/test/123', function (req, res) {
res.send('Hello 123!')
})
server = app.listen(7777)
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment