koa-unless icon indicating copy to clipboard operation
koa-unless copied to clipboard

complex unless

Open robbiemu opened this issue 8 years ago • 3 comments

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)/] } ])

robbiemu avatar Feb 01 '17 20:02 robbiemu

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;
    }
});

OmgImAlexis avatar Oct 12 '17 01:10 OmgImAlexis

@Foxandxss did you want to add my example above to the docs to show how a more advanced unless can work?

OmgImAlexis avatar Oct 12 '17 01:10 OmgImAlexis

https://github.com/Foxandxss/koa-unless/blob/master/index.js#L91

as I read the code, seems this lib supports methods filter

raphaelsoul avatar Oct 08 '18 09:10 raphaelsoul