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

hapi-authorization-feature

v0.0.8

Published

ACL support for hapijs apps

Downloads

81

Readme

hapi-authorization-feature

hapi-authorization-feature only supports hapi 17+

ACL plugin along with features check in hapijs

npm version Build Status Coverage Status Dev Dependencies

You can use this plugin to add ACL and protect your routes. you can configure required roles/functions along with features/subfeatures and allow access to certain endpoints only to specific users.

Usage

Note: To use hapi-authorization-feature you must have an authentication strategy defined.

There are 2 ways to use hapi-authorization-feature:

  1. With the default roles which are: "SUPER_ADMIN", "ADMIN", "USER", "GUEST"
  2. By defining your own roles/functions and features/subfeatures

Using hapi-authorization-feature with default roles

  1. Include the plugin in your hapijs app. Example:
let plugins = [
	{
		plugin: require('hapi-auth-basic')
	},
	{
		plugin: require('hapi-authorization-feature')
		options: {
		  roles: false	// By setting to false, you are not using an authorization hierarchy and you do not need to specify all the potential roles here
		}
	}
];

await server.register(plugins);

Using hapi-authorization-feature with custom roles and features

  1. Include the plugin in your hapijs app. Example:
let plugins = [
	{
		plugin: require('hapi-auth-basic')
	},
	{
		plugin: require('hapi-authorization-feature'),
		options: {
			roles: ['OWNER', 'MANAGER', 'EMPLOYEE'],
			functions:['CREATEMANAGER','CREATEEMPLOYEE','UPDATEMANAGER','UPDATEEMPLOYEE','DELETEMANAGER','DELETEEMPLOYEE'],
			features:['OWNERMANAGEMENT','MANAGERMANAGEMENT','EMPLOYEEMANAGEMENT'],
			subfeatures:['OWNERCREATION','OWNERUPDATION','OWNERDELETION']
		}
	}
];

await server.register(plugins);

Whitelist Routes That Require Authorization

If you want no routes require authorization except for the ones you specify in the route config, add hapiAuthorization instructions with the role(s) that should have access to the route configuration.

Example:

Authorize a single role or function without feature check

server.route({ method: 'GET', path: '/', options: {
  plugins: {'hapiAuthorizationFeature': {role: 'ADMIN',validateFeature:false, function: 'CREATEMANAGER'}},	// Only ADMIN role
  handler: (request, h) => { return "Great!"; }
}});

Authorize multiple roles with one feature

server.route({ method: 'GET', path: '/', options: {
  plugins: {'hapiAuthorizationFeature': {roles: ['USER', 'ADMIN'],feature:'OWNERMANAGEMENT' ,function: 'CREATEMANAGER' }},
  handler: (request, h) => { return "Great!"; }
}});

Blacklist All Routes To Require Authorization

If you want all routes to require authorization except for the ones you specify that should not, add hapiAuthorization instructions with the role(s) that should have access to the server.connection options. Note that these can be overridden on each route individually as well.

Example:

let server = new Hapi.server({
	routes: {
		plugins: {
			hapiAuthorization: { role: 'ADMIN',  feature:'OWNERMANAGEMENT' ,function: 'CREATEMANAGER' ,subfeature:'OWNERCREATION' }
		}
	}
});

Override the authorization to require alternate roles

server.route({ method: 'GET', path: '/', options: {
  plugins: {'hapiAuthorizationFeature': {role: 'USER', feature:'USERMANAGEMENT' ,function: 'CREATEUSER' ,subfeature:'USERCREATION'}},	// Only USER role
  handler: (request, h) => { return "Great!" ;}
}});

Override the authorization to not require any authorization

server.route({ method: 'GET', path: '/', options: {
  plugins: {'hapiAuthorizationFeature': false},
  handler: (request, h) => { return "Great!"; }
}});

Note: Every route that uses hapiAuthorization must be protected by an authentication schema either via auth.strategy.default('someAuthStrategy') or by specifying the auth on the route itself.

Full Example using hapi-auth-basic and hapi-authorization-feature

const Hapi = require('hapi');
const modules = require('./modules');

// Instantiate the server
let server = new Hapi.Server();

/**
 * The hapijs plugins that we want to use and their configs
 */
let plugins = [
	{
		register: require('hapi-auth-basic')
	},
	{
		register: require('hapi-authorization-feature'),
		options: {
			role: 'EMPLOYEE'
		}
	}
];

let validate = (username, password) => {
	// Perform authentication and respond with object that contains a role or an array of roles
	return {username: username, role: 'EMPLOYEE'};
}

/**
 * Setup the server with plugins
 */
await server.register(plugins);
server.start().then(() => {

	server.auth.strategy('simple', 'basic', {validateFunc: validate});
	server.auth.default('simple');

	/**
	 * Add all the modules within the modules folder
	 */
	for(let route in modules) {
		server.route(modules[route]);
	}

	/**
	 * Starts the server
	 */
	server.start()
        .then(() => {
            console.log('Hapi server started @', server.info.uri);
        })
        .catch((err) => {
            console.log(err);
        });
})
.catch((err) => {
  // If there is an error on server startup
  throw err;
});

Gotchas

Auth before routes

You must define your auth strategy before defining your routes, otherwise the route validation will fail.

Plugin Config

  • roles - Array|false: All the possible roles. Defaults to SUPER_ADMIN, ADMIN, USER, GUEST.
  • functions - Array: All the possible functions of the each roles
  • features - Array: All the possible features
  • subfeatures - Array: All the possible subfeatures of each features

Route config of supported parameters:

  • role - String: enforces that only users that have this role can access the route or
  • function - String: enforces that only users that have this function can access the route and
  • feature - String: enforce that only users that have this feature can access the route and
  • subfeature - String: enforce that only users that have this subfeature can access the route

Thanks [toymachiner62]:https://github.com/toymachiner62/hapi-authorization