Skip to content

Instantly share code, notes, and snippets.

@joshnuss
Last active November 4, 2025 22:39
Show Gist options
  • Select an option

  • Save joshnuss/37ebaf958fe65a18d4ff to your computer and use it in GitHub Desktop.

Select an option

Save joshnuss/37ebaf958fe65a18d4ff to your computer and use it in GitHub Desktop.
Express.js role-based permissions middleware
// the main app file
import express from "express";
import loadDb from "./loadDb"; // dummy middleware to load db (sets request.db)
import authorize from "./authorization"; // middleware for doing authorization
import permit from "./permission"; // middleware for checking if user's role is permitted to make request
let app = express(),
api = app.Router();
// first middleware will setup db connection
app.use(loadDb);
// check authorization for each request
// will set `request.user`
app.use(authorize);
// setup permission middleware,
// check `request.user.role` and decide if ok to continue
app.use("/api/private", permit("admin"));
app.use(["/api/foo", "/api/bar"], permit("account-owner", "account-member"));
// setup requests handlers
api.get("/private/whatever", (req, res) => response.json({whatever: true}));
api.get("/foo", (req, res) => response.json({currentUser: req.user}));
api.get("/bar", (req, res) => response.json({currentUser: req.user}));
// setup permissions based on HTTP Method
// account creation is public
api.post("/account", (req, res) => req.json({message: "created"}));
// account update & delete (PATCH & DELETE) are only available to account owner
api.patch("/account", permit('account-owner'), (req, res) => req.json({message: "updated"}));
api.delete("/account", permit('account-owner'), (req, res) => req.json({message: "deleted"}));
// viewing account "GET" available to account owner and account member
api.get("/account", permit('account-member', 'account-owner'), (req, res) => req.json({currentUser: request.user}));
// mount api router
app.use("/api", api);
// start 'er up
app.listen(process.env.PORT || 3000);
// middleware for authentication
export default function authorize(req, res, next) {
let apiToken = req.header['x-api-token'];
req.db
.users
.findByApiKey(apiToken)
.then(user => req.user = user) // set user on-success
.finally(() => next()); // always continue to next middleware
}
// dummy middleware for db (set's request.db)
export default function loadDb(req, res, next) {
// dummy db
request.db = {
users: {
findByApiKey: token => new Promise((resolve, reject) => {
switch {
case (token == '1234') {
resolve({role: 'account-owner', id: 1234});
break;
case (token == '5678') {
resolve({role: 'account-member', id: 5678});
break;
default:
reject();
}
})
}
};
next();
}
// middleware for doing role-based permissions
export default function permit(...allowedRoles) {
let isValidRole = role => _.indexOf(allowed, role) > -1;
// return a middleware
return (req, res, next) => {
if (req.user && isValidRole(req.user.role))
next(); // role is allowed, so continue on the next middleware
else {
response.status(403).json({message: "Forbidden"}); // user is forbidden
}
}
}
@HamzaKazmi43
Copy link

...allowed can you explain this to me i am new at this

@joshnuss
Copy link
Author

joshnuss commented Aug 1, 2019

@HamzaKazmi43 f(...args) is called "rest parameters". It allows the function to consume the parameters as if it was an array.
For more info, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

@xuxucode
Copy link

very useful, thank you!

@mosmartin
Copy link

Thank you @joshnuss, this is brilliant!

@staminna
Copy link

staminna commented Sep 28, 2019

Can I see some example usage of this code?
I also tried to replace 'api' with app and I get some unexpected circular error of some kind. I am not using router directly. I am only using app=express();

@AdriaanRoets
Copy link

Thanks man, this just saved me hours of work today!

@xocialize
Copy link

Ditto on this being very helpful. And I learned about rest parameters so that was a big bonus for me.

Thanks for sharing.

@jose-matias
Copy link

Thank you for sharing.

@marlonfsolis
Copy link

Thank you! This was extremely helpful for me.

@Juanmadepalacios
Copy link

thanks! save me"

@zartre
Copy link

zartre commented Jul 3, 2020

This is helpful. I have adapted mine based on your work. Thanks!

@Dahkenangnon
Copy link

Thank

@jalakpatoliya
Copy link

jalakpatoliya commented Jul 30, 2020

Just here to Thank... awsome buddy thanks 👊️😎️

@Pipoupi
Copy link

Pipoupi commented Jul 31, 2020

Here to thank you too ! :)

@anurag-tiwari-builtio
Copy link

This is great, was looking for something similar.

Thanks man

@Hyllesen
Copy link

I looked at other implementations but this is the most simple and useful one so far

@Kibria7533
Copy link

@hardik-itoneclick
Copy link

Extremely Useful. Works like a charm.

@TheBrown
Copy link

Nice, Thank you

@sergey-shpak
Copy link

By using 'owner' role I would expect the user who created(own) the doc is trying to access, otherwise it is confusing and misleading.
I would suggest to rename 'owner' role to something else, because 'owner' in this pattern is not what you expect.

@skang
Copy link

skang commented Apr 1, 2021

Excellent design - simple, beautiful and powerful. Thank you very much for sharing!

@richardscarrott
Copy link

@sergey-shpak yeh me too, I think it's just an unfortunately named role?

@katonahmike
Copy link

Very helpful. Thanks for sharing.

@Cool-Programmer
Copy link

This is perfect, thank you a ton.

@irpanrain
Copy link

thank you bro..

@luong12g
Copy link

I got an error. Please advice.

import authenticate from "./authentication.js"; // middleware for doing authentication
^^^^^^

SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (vm.js:344:18)

@katonahmike
Copy link

I got an error. Please advice.

import authenticate from "./authentication.js"; // middleware for doing authentication ^^^^^^

SyntaxError: Cannot use import statement outside a module at Object.compileFunction (vm.js:344:18)

Take a look at https://stackoverflow.com/questions/58384179/syntaxerror-cannot-use-import-statement-outside-a-module or update your syntax to use require. For example, const {authorize} = require('./authentication.js')

@luong12g
Copy link

I got an error. Please advice.
import authenticate from "./authentication.js"; // middleware for doing authentication ^^^^^^
SyntaxError: Cannot use import statement outside a module at Object.compileFunction (vm.js:344:18)

Take a look at https://stackoverflow.com/questions/58384179/syntaxerror-cannot-use-import-statement-outside-a-module or update your syntax to use require. For example, const {authorize} = require('./authentication.js')

Thank you.

@harshavardhannarla
Copy link

Thank you , this is very helpful

@mataverrick
Copy link

Thank you man!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment