node-user-is
Simple role-based outhorization library that makes no assumptions.
Installation
$ npm install user-is
Quickstart
var UserIs = // Define what it means to have your given roles. Here we have a role called 'admin'.var roleFuncs = { } // Name the actions you care about, and state what roles are needed for themvar actionDefs = 'add new user': 'admin' 'do something else': 'admin' 'user' // Get your authorization instancevar authorization = // Find out if a given user has a certain rolevar user = {} //... You've somehow retrieved this alreadyvar userIs = if userIs // user is an 'admin', so do something with that // Find out if a user can perform a certain actionif userIs // user can do that action, so do something with that
Do you use Express?
Or some other routing layer that uses function(req, res, next)
-style functions for a middleware layer? user-is
has you covered.
// How do you extract the user from a request? { // <---- async in case you need to go to the DB or something } var options = retrieveUserFromRequest: retrieveUserFromRequest // resusing our definitions from abovevar authorization = roleFuncs actionDefs options // Now, wherever you have your routesvar router = Router router
What happens in the middleware if users aren't authorized
user-is
will introduce an Error
object into the queue. The error will have a member code
that depends on what the error is.
- Not authorized: 'E_NOTAUTHORIZED'
- User not found in the request: 'E_USERNOTFOUND'
There error codes are accessible directly off the user-is
module, e.g.:
UserIs.notAuthorizedErrorCode
So you'd want to also have an error-handling middleware for each possibility, e.g.:
{ if errcode !== UserIsnotAuthorizedError return resstatus403} router
Other options
The modules returns a function with the following signature:
You've aleady seen the option for how to transform a request into a user object. There is another option though.
If you ask a question about a role or action that you haven't defined, by default, user-is
will introduce an error with code 'E_MISSINGDEFINITION'
. This error is also accessible directly off the module:
UserIs.missingDefinitionErrorCode
If you'd rather it just return false in your checks, use the following option:
var options = errorOnMissingDefinitions: true var authorization = var userIs = authorization userIs
Tests
./node_modules/mocha/bin/mocha test/theTests.js
Want to contribute?
Fork this repo, make your change, and submit a pull request. It's worth checking the issues first to see if someone else has reported the issue. If you're unsure if a given feature is desired, open up an issue on it, and let's discuss!
Acknowledgements
A big thanks to the fine folks who wrote authorized
. Your library heavily inspried this one.