Coder Social home page Coder Social logo

express-unless's Introduction

Conditionally skip a middleware when a condition is met.

Install

npm i express-unless --save

Usage

With existing middlewares:

var { unless } = require("express-unless");

var static = express.static(__dirname + "/public");
static.unless = unless;

app.use(static.unless({ method: "OPTIONS" }));

If you are authoring a middleware you can support unless as follow:

var { unless } = require("express-unless");

module.exports = function (middlewareOptions) {
  var mymid = function (req, res, next) {};

  mymid.unless = unless;

  return mymid;
};

Current options

  • method it could be an string or an array of strings. If the request method match the middleware will not run.
  • path it could be an string, a regexp or an array of any of those. It also could be an array of object which is url and methods key-pairs. If the request path or path and method match, the middleware will not run. Check Examples for usage.
  • ext it could be an string or an array of strings. If the request path ends with one of these extensions the middleware will not run.
  • custom it must be a function that accepts req and returns true / false. If the function returns true for the given request, the middleware will not run.
  • useOriginalUrl it should be true or false, default is true. if false, path will match against req.url instead of req.originalUrl. Please refer to Express API for the difference between req.url and req.originalUrl.

Examples

Require authentication for every request unless the path is index.html.

app.use(
  requiresAuth.unless({
    path: ["/index.html", { url: "/", methods: ["GET", "PUT"] }],
  })
);

Avoid a fstat for request to routes doesnt end with a given extension.

app.use(
  static.unless(function (req) {
    var ext = url.parse(req.originalUrl).pathname.substr(-4);
    return !~[".jpg", ".html", ".css", ".js"].indexOf(ext);
  })
);

License

MIT 2014 - Jose Romaniello

express-unless's People

Contributors

dennismckinnon avatar dschenkelman avatar humingchun avatar jfromaniello avatar julioolvr avatar pipeline1987 avatar simllll avatar zhiyelee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

express-unless's Issues

Not working

csrf.unless = unless;
const csrf = require('csurf');

then add it to middleware...

....
csrf({
    cookie: true
  }).unless({
    path: [router.get('auth')]
  }),
...

results in ....
unless is not a function

another example...

handleExpiredTokens.unless({
path: [{
url: '/foo',
methods: ['POST']
}]
});
function handleExpiredTokens(err, req, res, next) {
// stuff
}

handleExpiredTokens.unless = unless;

module.exports = handleExpiredTokens;
handleExpiredTokens runs on every request including POST /foo

Params in URL

I have an end point at /v1/report
using express-jwt to enforce authorization.
That end point takes params like this:

router.get('/:type/:email/:date?/', function ...

however, adding the urls to unless after it won't work for that end point. It does work for the other two. My feeling is that it seems to believe that the parameters are, in fact, part of the end point rather than parameters. Is this the case?

app.use(expressJwt({ secret: config.SECRET })
    .unless({ path: [ '/v1/auth', '/v1/is-alive', '/v1/report' ] }));

I'm sure this is just a lack of understanding on my part of the unless implementation, but I'm hoping you can assist in figuring out a way to allow for it.

Unintentionally Bypassing Middleware with Case-Sensitive Negative Regex

In the snippet below, the basicAuth middleware will be applied to all routes beginning with /secure/.

var unless = require('express-unless');
...
app.use(basicAuth.unless({path: /^(?!\/secure\/).*/})); 

However, Express uses case-insensitive routing by default. This means that if we use the above regex and have a route /secure/endpoint, we can bypass the basicAuth middleware by requesting the route /SECURE/endpoint.

The documentation for the path option should be updated to bring this to the developers attention. The developer should always use the case-insensitive 'i' flag when using a negative regular expression (i.e., {path: /^(?!/secure/).*/i} or set the Express case sensitive routing option to true.

An alternate solution is to update the default behavior of the express-unless path option to include the 'i' option by default when using regular expressions. This would make the default express-unless behavior align with the default Express routing behavior; however, this would be a breaking change.

Unless is not working

I have a route which is /authenticate

I have defined it as

app.use(expressjwt({secret: config.sessionSecret}).unless({path: ['/authenticate']}));

But when I do a post to /authenticate path it give me an error saying

UnauthorizedError: No authorization token was found
...

/authenticate is working without express-jwt

chaining unless

Is it possible to chain unless commands? .unless().unless()? I want to put a default unless status in my middleware, but I also want my users to include their own unless as well. Is there an elegant way to do this?

Allow parent path but do-not allow subpath to have access

Hello,
I was trying to avoid token validation for particular urls as shown below
/ - allow without token
/api - allow without token
/api/auth - allow without token
/api/usrs - allow with token
/api/usrs/:id - allow with token

So i tried to set below

const expressJwt = require("express-jwt");
expressJwt({"Tango"}).unless({
		path:[
			'/',
			'/api',
			'/api/usrs/auth'
		]
	});

Any one facing same issue?

"UnhandledPromiseRejectionWarning" if middleware throws exception (Version 1.0.0)

When my authentication middleware is throwing an exception (see code below), an 'UnhandledPromiseRejectionWarning" is issued. The exception is not propagated further, which causes problems in my program.
This problem did not exist in the previous version 0.5.0.

export function requiresAuth(req, res, next) {
  if (req.session && req.session.user && req.session.user.id) {
    return next();
  } else {
    throw new NoValidSessionError('requiresAuth');
  }
}
requiresAuth.unless = require('express-unless');

Possible fix in index.js:

    try {
      middleware(req, res, next);
    } catch(err) {next(err)}

Support GraphQL queries

Is it somehow possible to be able to define GraphQL queries? One might want to whitelist a mutation that resolves into an account signup/signin.

I've tried with Regex but the problem I see there is that the path only applies to either req.originalUrl or req.url which in this case are both / for an url like /?query=query{ping} (url encoded obviously)

Possible "custom" option missing ?

Hi there. Since the last released version of express-unless (2.1.0), it seems that the "custom" option is missing in the package. At least, the "custom" option seems to be missing in the "Type definition" of the package

image

image

Also, the documentation seems to say that this option must be available

image

Thank you for your help

How can I use RegExp?

Hi;

I tried to use RegExp like

.unless({
    path: ['/auth/login', '/auth/signup', '^\/auth\/reset\/[A-Za-z0-9-_]*']
}))

to let /auth/reset/46b957ea7272a916f5d71e79d7fde7dab7a91414

but it is not allowed. How can I do that?

not able to get 'unless' working

Hi there,

Can you please help me out with this code wher I am not yet able to get this working ?

(function(){
  'use strict';
  var unless = require('express-unless');
  var express = require('express');

  var app = express();

  var fun1  = function(req,res,next){
    console.log('fun1 was called');
    next();
  };
  fun1.unless=unless;

  var fun2  = function(req,res,next){
    console.log('fun2 was called');
    console.log(req.method);
    console.log(req.url);
    next();
  };

  app.use(fun1.unless({method : 'GET', 'url':'/'}));

  app.get('/', fun2,function(req, res,next) {
    console.log('root route hit');
    res.send('ok');
  });

  app.listen(process.env.PORT || 5553);


})();

Support for method and path combination

Is there a way to exclude specific methods from a path?

For example suppose I have a /items path, and want to skip the middleware on GET /items and run it on POST | PUT | DELETE /items.

Something like:

app.use(myMiddleware.unless({ path: { "/items": [ 'GET' ] } }));

Recent update may have missing type definition? v2.1.3

I'll add more details as they come in, but we just tried deploying a recent version of express-jwt which includes this module. Starting about 2hrs the build process started failing.

error TS2688: Cannot find type definition file for 'express-unless'.
The file is in the program because:
Entry point for implicit type library 'express-unless'

can't use unless for req.params

Hi,

I have the requirement to unless the endpoint url as below,

/api/sample/:type

here 'type' is the request param. The problem is that i can't unless the url . Its still showing unauthorized. So what is the solution for this?

Can't get it working

handleExpiredTokens.unless({
  path: [{
    url: '/foo',
    methods: ['POST']
  }]
});
function handleExpiredTokens(err, req, res, next) {
 // stuff
}

handleExpiredTokens.unless = unless;

module.exports = handleExpiredTokens;

handleExpiredTokens runs on every request including POST /foo

Exclude a route with uuid v4

I need help to exclude from a JWT protected route the path to /api/v1/auth/verify/:uuid where :uuid is a UUID v4.
I've tried different regex from StackOverflow but none worked.

Here is my code:

import { Router } from 'express';
import jwt from 'express-jwt';
import config from '@app/config';
import auth from './auth';

const router = Router();

router.use(
  '/auth',
  jwt({
    secret: config.SECURITY.JWT.SECRET,
  }).unless({
    path: [
      {
        url: '/api/v1/auth/verify/:uuid',
        methods: ['POST'],
      }
    ],
  }),
  auth
);

Thanks in advance.

Add license to package.json

I was hoping to get MIT listed in the license field of the package.json. I see it listed in the README but license-checker doesn't discover it during an export. Let me know if you want me to submit a PR with this change too.

Thanks.

Is the library no longer supported?

I'm trying to get this library working but it is not.
Is the library no longer supported? If not, no worries, I'll look else where.
Seems there are issues a couple years old..

More examples

It would be nice to see more examples of usage in this README. I am stuck trying to figure a lot of use cases out. :)

404 route?

Is there a way to exclude any routes that aren't registered?

Migrating to v2

Hello @jfromaniello, How do I migrate from v1 to v2 in typescript, from what I can see:

  • Options is now Params
  • unless.RequestHandler has disappeared in v2.1.3, what should I use instead ?

Are there any other breaking change?

The path string passed to unless function is better to be req.url, not req.originalUrl

Hi, first of all, thank you very much for express-jwt and related packages.

I am using express-jwt to protect /api/user endpoints in a small project, and I have created a router tree to manage the route: app.use('/api', apiRouter), apiRouter.use('/user', userRouter)

I am hoping to protect /api/user/endpoints but not /api/user/register and /api/user/login. I could use userRouter.use(express-jwt({}).unless( path: ['', ''])) to do this, but surprisingly it requires me to specify '/api/user/register' and '/api/user/login' instead of just '/register' and '/login'.

In this case, '/api/user/register' violates the intention of using router tree, because it requires the userRouter to be mounted on /api/user exactly.

So I think it would be better to specify '/register' instead of '/api/user/register', and it may related to the use of req.originalUrl instead of req.url.

I would be happy to modify express-unless if you are agree with the new behavior.

Unless params

I have a route for downloading files

router.get('/:id', (req, res) => {
  File
    .findOne({ _id: req.params.id })
    .then(file => res.download(`${__dirname}/../files/${file.fileName}`, `${file.originalName}`))
    .catch(err => res.json(err))
})

i want to use unless on that route but this route have params and unless did not support that.

how can i unless that route?

Thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.