Mercutio is a small module to validate user roles by scopes. It assumes an array of roles that can be described as [role]@[scope]
, where role is a non-hierarchical user type, and scopes are path-based domains of influence. Being admin@my/scope
automatically implies that you are also admin@my/scope/area
, but you have no status in @my
.
Roles are not hierarchical. Being admin
will not return true for any other role, so admin
does not imply member
, for instance.
const mercutio = ; const user = ; user; // true, this is the main scopeuser; // true, this is a sub-scopeuser; // true, this is a sub-scopeuser; // false, this scope is aboveuser; // false, member is NOT implied from admin
Mostly, a user will have several roles. You can also feed it arrays, and objects instead of strings:
let user = ;user = ;user = ;
Finally, it can also take and decode a JSON web token. But the decoded payload should have a roles
property that is an array conforming to the above.
Express middleware
Mercutio exposes some middleware functions which can be used in an express
compatible application. Please note that to use this, you need to require mercutio/express
, which is an extended version with middleware functions. This version cannot be required on the frontend, as it relies on the jsonwebtoken
package and verifies the token.
.identity
middleware
This will augment the req
object with a req.identity
object, which contains
const app = ;const mercutio = ; app; app;
The req.identity
object will have these properties:
// decoded user object user: {} // whether a token was verified successfully authenticated: bool // an initialized mercutio Roles object, created from roles on user object roles: Mercutio object
You can customize how mercutio
gets the info necessary for constructing the identity. This is the options and their defaults:
app;
.require
middleware
This middleware will only work as expected if .identity
was added earlier in the chain. It can be used to require a specific role as an access requirement to a route.
const app = ;const mercutio = ; app; // This will pass an `UnauthenticatedError` to next if the user is unauthenticated.app; // This will pass an `UnauthenticatedError` if no user, or an `InsufficientPermissionsError` if wrong role.app; // This will pass an `UnauthenticatedError` if no user, or an `InsufficientPermissionsError` if wrong role.app;