koa-unless
koa-unless copied to clipboard
complex unless
How do you / can you create complex unless clauses?
like:
\/(?!api) => require authentication on the entire /api/ URI node
but then additionally
GET /api/Foo/* => don't require authentication on /api/Foo node
something like unless([{path: [/^\/(?!api\/Foo)/], method: [ 'GET' ]}, { path: [/^\/(?!api)/] } ])
Haven't fully tested this but something like this should work.
const isRegex = require('is-regex');
const matcher = require('matcher');
unless({
custom: ctx => {
const paths = [{
url: '/api/Foo/*',
methods: ['GET', 'POST', 'OPTIONS', 'DELETE']
}];
return paths.filter(path => {
if (isRegex(path.url)) {
return request.originalUrl.match(new RegExp(path.url));
}
return matcher.isMatch(request.originalUrl, path.url);
}).filter(path => {
if (!path) {
return false;
}
// If no methods assume all should be allowed
if (!path.methods) {
return path;
}
return path.methods.includes(request.method);
}).length >= 1;
}
});
@Foxandxss did you want to add my example above to the docs to show how a more advanced unless can work?
https://github.com/Foxandxss/koa-unless/blob/master/index.js#L91
as I read the code, seems this lib supports methods filter