Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Bitwise middleware
function userCan(req,res,next) { // `req,res,next` is the standard Express middle argument signature (request, response and next middleware)
tempKey = 'userCanTemp', // This can be any value
routeKey = rk(routePrefix,req.route.path), // `rk` joins each argument with a colon, req.route.path is the Express route
user = req.query.user; // In this example, were getting the user from the query string, but you'd get it form another middleware most likely
if (!user) { // if `user` isn't defined, then we'll reject
} else {
userKey = rk(userPrefix,user); // create the user key with `rk`
.multi() // start the multi transaction
.bitop('AND',tempKey,userKey,routeKey) // The result of `userKey` AND'ed with `routeKey` and stored in `tempKey`
.bitop('XOR',tempKey,tempKey,routeKey) // The result of `tempKey` XOR'ed with `routeKey` and stored back in `tempKey`
.bitcount(tempKey) // count the bits in `tempKey`'s value
.bitfield(rk(routeKey,'level'),'GET','u7','9') // grabbing a unsigned 7-bit word from routeKey+':level'
.bitfield(userKey,'GET','u7','9') // grabbing a unsigned 7-bit word from `userKey`
.exec(function(err,responses) {
if (err) { next(err); } else { // handle errors
capMisses = responses[2]; // capability misses are stored in the 2nd result
if (
(capMisses === 0) && // make sure no bits are misses
(responses[3] >= responses[4])) { // that the user level is greater than the route level
next(); // pass it on to the next middleware
} else {
res.status(401).end(); // otherwise reject it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment