Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 1,000,000+ packages pre-installed, including @modnes/access-controller with all npm packages installed. Try it out:

var accessController = require("@modnes/access-controller")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

@modnes/access-controller v1.0.0

Module to Control Access using roles and functions

Access Controller Modules

Coverage Status

Access Controller module provides an utility class to check if an user has access to some resource based in constraints as roles or functions set.

Installing

npm i @modnes/access-controller

Usage

To check if an user has access to something the AccessController.hasAccess() method must be called passing an user object and a constraints object.

import AccessController from 'path/to/@modnes/access-controller/access-controller.js'

const USER = {
  id: 1,
  roles: ['user'],
  isLogged: () => true
}
const CONSTRAINTS = {
  roles: ['user', 'manager'],
  functions: [
    user => user.id === 1,
    USER.isLogged
  ]
}

if AccessController.hasAccess(USER, CONSTRAINTS) console.log('User has access!')

Methods

Access Controller provides more two methods: userHasRoles() and callFunctions(). These methods can be called in isolation in certain circumstances.

userHasRoles

The userHasRoles() method checks if an user has some of passed roles.

const USER = {
  id: 1,
  roles: ['user']
}
const ROLES = ['user', 'manager']

if AccessController.userHasRoles(USER, ROLES) console.log('User has some of these roles!')

callFunctions

The callFunctions() method returns true if all passed functions return true.

const USER = {
  id: 1,
  isLogged: () => true
}
const FUNCTIONS = [
  user => user.id === 1,
  USER.isLogged
]

if AccessController.callFunctions(USER, FUNCTIONS) console.log('All functions returned true!')

See the API documentation

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free