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

gesto-auth-middleware

v1.0.0

Published

Gesto authentication middleware using passport

Downloads

22

Readme

gesto-auth-middleware

Configuration:

const config = {
  mysql: {
    host: process.env.MYSQL_HOST,
    user: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE
  },
  jwt: {
    secret: process.env.JWT_SIGNING_KEY
  },
  hawk: {
    algorithm: 'sha256' // Optional: defaults to sha256
  },
  noAuth: process.env.NO_AUTH // Optional: defaults to false
}

This middleware does not provide sensible defaults to the above environment variables

Optional configuration:

  • noAuth: Setting this to true bypasses the authentication step of the middleware. noAuth also adds a fake user to the request to fulfill any testing needs on the user object. This is helpful for testing, but a valid MySQL connection is still required (for now).

Supported auth strategies

  • Hawk (Header name: Authorization)
  • JWT (Header name: Gesto-Authentication)

Add this to your API:

Add the auth config to your environment configuration (see above for example)

{
  auth: {
    mysql: { ... }
    jwt: { ... }
    hawk: { ... }
  },
  ...
}

Be sure to add noAuth: true for your testing environment!

Add the auth middleware to the primary routes

const auth = require('gesto-auth-middleware')(config.auth);
const requiredPermission = 'api:gesto';

router.use(auth(requiredPermission));
router.use('/api', controller);

Note: Each time a permission is added to the route, the user must have all of those permissions.

router.use(auth('api:gesto'));
router.use(auth('admin:reports:view'));
router.use(auth('admin:reports:edit'));
router.use('/reports', reportController);

In that example the user must have api:gesto, admin:reports:view, and admin:reports:edit to access /reports

Add a test

(function IIFE() {
  'use strict';

  const request = require('supertest');

  const app = require('../app');
  const config = require('../config/environment');

  describe('/api/models', function() {
    beforeEach(function() {
      config.auth.noAuth = false;
    });

    afterEach(function() {
      config.auth.noAuth = true;
    });

    it('Use auth middleware', function(done) {
      request(app)
        .get('/api/models')
        .expect(/Missing authorization header/i)
        .expect(401, done);
    });
  });

})();

Note: When testing, be sure to set the environment variable NO_AUTH to true to bypass auth on your endpoints when testing. This allows you to test your endpoint without having to set auth headers.

Customizing permissions on routes

With the middleware, you can add specific permissions for individual routes as needed.

// Unprotected route
router.get('/api/ping', pingCtrl);  

 // Define a global permission requirement for routes defined below this line
router.use(auth('api:gesto'));

// Add a permission to all location routes
router.use('/api/locations', auth('api:locations:view'));

router.get('/api/locations', locationCtrl.view);
router.get('/api/locations/:id', locationCtrl.viewSingle);

// Add a specific permission to this route only
router.post('/api/locations', auth('api:locations:create'), locationCtrl.create);

Accessing the user object

On successful authorization, the middleware adds the user object to the request as req.user. The user object has the following structure:

{
  id: String,
  userId: String,
  contextKey: String,
  firstName: String,
  lastName: String,
  userKinds: [ String ],
  roleIds: [ String ],
  permissions: [ String ]
}

JWT token

On successful authorization, the middleware adds a JWT token for server to server communication. This token expires after 1 hour and can be accessed at req.jwt.

Example:

const options = {
  url: 'https://core.com/api/endpoint',
  method: 'GET',
  headers: {
    'Gesto-Authentication': req.jwt
  }
};

request(options, function(err, res) {
  console.log(res.body);
});