npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

connect-ensure-authorization

v1.0.8

Published

User authorization ensuring middleware for Connect for API's.

Downloads

29

Readme

connect-ensure-authorization

NPM version Build Status codecov devDependencies Status Greenkeeper badge

This middleware ensures that a user is authorized. If the user is unauthorized, the request returns a JSON error by default or redirects the user with additional configuration.

Table of contents

Install

Yarn

$ yarn add connect-ensure-authorization

NPM

$ npm install connect-ensure-authorization

Usage

Ensure scope

In this example, an application has a todos API endpoint. A user must be authorized before accessing this endpoint.

const express = require('express');
const { ensureScope } = require('connect-ensure-authorization');

const app = express();

// req.user should be like:
// {
//   username: 'bob', <-- dummy data
//   fullName: 'Bob', <-- dummy data
//   scopes: ['todos:read'] <-- used for scope checking
// }

app.get('/api/todos', ensureScope('todos:read'), (req, res) => {
  res.json([
    {
      text: 'First todo',
      completed: false,
    },
    {
      text: 'Second todo',
      completed: true,
    }
  ]);
});

If a user is not authorized when attempting to access this API, the request will return the default 403 status code with the default message "Forbidden".

Ensure functions

The following ensure functions are available:

| Function | User property | | - | - | | ensureScope | scopes | | ensurePermission | permissions | | ensureRole | roles | | ensureGroup | groups |

All functions will check its corresponding user property. The user property should contain an array with strings. The ensure function does an Array.includes check. This default implementation can be modified to your custom requirement.

Custom ensure implementation

The ensure implementation can be overwritten with a custom implementation. This function must return a Promise or a Boolean.

const express = require('express');
const {
  initialize: initializeAuthorization,
  ensureScope
} = require('connect-ensure-authorization');

const app = express();

const onEnsureScope = ({ user, scope }) => new Promise((resolve, reject) => {
  if (user.scopes.includes(scope)) {
    resolve();
  } else {
    reject();
  }
});

initializeAuthorization({ onEnsureScope });

app.get('/api/todos', ensureScope('todos:read'), (req, res) => {
  res.json([
    {
      text: 'First todo',
      completed: false,
    },
    {
      text: 'Second todo',
      completed: true,
    }
  ]);
});

The other ensure implementations are also supported to be overwritten (by passing onEnsurePermission, onEnsureRole and onEnsureGroup).

Custom status code and/or message

The middleware can be configured to return another status code and/or message when unauthorized.

const express = require('express');
const { initialize: initializeAuthorization } = require('connect-ensure-authorization');

const app = express();

initializeAuthorization({
  statusCode: 418, // default = 403
  message: 'I\'m a teapot!', // default = "Forbidden"
});

app.get('/api/todos', ensureScope('todos:read'), (req, res) => {
  res.json([
    {
      text: 'First todo',
      completed: false,
    },
    {
      text: 'Second todo',
      completed: true,
    }
  ]);
});

Redirect instead of return JSON

The following example redirects to /forbidden instead of returning a JSON message.

const express = require('express');
const { initialize: initializeAuthorization } = require('connect-ensure-authorization');

const app = express()

initializeAuthorization({
  redirectTo: '/forbidden', // default = null
});

app.get('/api/todos', ensureScope('todos:read'), (req, res) => {
  res.json([
    {
      text: 'First todo',
      completed: false,
    },
    {
      text: 'Second todo',
      completed: true,
    }
  ]);
});

Custom user property

If you are using Passport, this defaultly sets the req.user after logging in. This can be modified to for example req.account.

const express = require('express');
const { initialize: initializeAuthorization } = require('connect-ensure-authorization');

const app = express()

initializeAuthorization({
  userProperty: 'account', // default = "user"
});

// req.account should be like:
// {
//   accountName: 'bob', // dummy data
//   fullName: 'Bob', // dummy data
//   scopes: ['todos:read'] <-- used for scope checking
// }

app.get('/api/todos', ensureScope('todos:read'), (req, res) => {
  res.json([
    {
      text: 'First todo',
      completed: false,
    },
    {
      text: 'Second todo',
      completed: true,
    }
  ]);
});

Usage with Passport

Take a look at the integration test for some inspiration.
I have also created a single file example repository using this module: https://github.com/allardvanderouw/express-api-passport-local-mongo-session-example/blob/master/server.js