@ryanburnette/authorization

4.0.0 • Public • Published

authorization

repo npm

An excruciatingly simple authorization strategy for Node.js http apps.

Installation

npm install @ryanburnette/authorization

Usage

This strategy makes a couple assumptions.

  • req.user is an object that describes this user
  • req.user.roles is an array of strings that describes the roles this user has

A basic implementation looks something like this.

var authorization = require('@ryanburnette/authorization');

// use it on a group of endpoints
app.use(
  '/api/widgets',
  authorization({ methods: ['GET', 'POST'], roles: ['user', 'admin'] }),
  authorization({ methods: ['DELETE'], roles: ['admin'] }),
  function (req, res) {
    res.statusCode = 200;
    res.end();
    return;
  }
);

// use it on a single endpoint
app.get(
  '/api/employees',
  authorization({ roles: ['user', 'admin'] }),
  function (req, res) {
    res.statusCode = 200;
    res.end();
    return;
  }
);

app.use(function (err, req, res, next) {
  // catch errors from this strategy
  if (err.code === 'UNAUTHORIZED') {
    res.statusCode = 401;
    res.end();
    return;
  }
  console.error(err);
  res.statusCode = 500;
  res.end();
});

Test

npm install --no-save express axios
node test.js

Readme

Keywords

none

Package Sidebar

Install

npm i @ryanburnette/authorization

Weekly Downloads

2

Version

4.0.0

License

ISC

Unpacked Size

5.53 kB

Total Files

7

Last publish

Collaborators

  • ryanburnette