Skip to content

Improving RouteHelpers; Better Middleware

Latest
Compare
Choose a tag to compare
@mxriverlynn mxriverlynn released this 17 Dec 18:24
· 6 commits to master since this release

IMPORTANT This is a breaking release, and your existing use of RouteHelpers will likely be broken, but easily fixed.

I've learned a lot about Express middleware since I wrote this module, and have finally gone back to fix the way MustBe produces and uses middleware. The RouteHelper functions now take advantage of next() appropriately, making it easier and cleaner to configure your authorization rules as middleware functions.

Improved Middleware Semantics

With this change, your RouteHelpers use will likely break. However, the changes are simple to fix.

  • Replace mustBe.authorized("activity", pass, fail) with mustBe.authorized("activity", fail), pass as your middleware chain.

For example, if your old code looked like this:

var mustBe = require("mustbe").routeHelpers();
var adminRouter = require("./adminRoutees");

router.use("/admin", mustBe.authorized("admin", adminRouter));

Your new code would move the ) parenthesis back one spot, like this:

var mustBe = require("mustbe").routeHelpers();
var adminRouter = require("./adminRoutees");

router.use("/admin", mustBe.authorized("admin"), adminRouter);

The difference is small but important, and applies to all routeHelper methods.

Custom Authorization Failure Handlers

If you had custom failure handlers, they will still be passed to the authorized or authenticated or whatever other method you are calling:

var mustBe = require("mustbe").routeHelpers();
var adminRouter = require("./adminRoutees");

function noAdmin(req, res){
  res.redirect("/login?msg=must+be+admin");
}

router.use("/admin", mustBe.authorized("admin", noAdmin), adminRouter);