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

@scandinave/access-control-middleware

v4.2.2

Published

Express Middleware for AccessControl library that support generics, specifics and dynamics permissions check

Downloads

24

Readme

AccessControlMiddleware

Express Middleware for AccessControl library that support generics, specifics and dynamics permissions check.

Build Status npm version Coverage Status Licence

Disclaimer

  • This middleware is not part of the AccessControl library, and it is not developed by the author of AccessControl.
  • This middleware was developed to be used in a REST architecture with the use of an access token and refresh token.

Permission Type

  • Generics : Permissions that applied to a list of resources.(eg: findAll)
  • Specifics: Permissions that applied to a specific resource. (eg: find)

How to use

  • Install AccessControlMiddleware
npm install @scandinave/accessControlMiddleware
  • Create a new instance of AccessControlMiddleware
    // ac = ... Initialisation of the AccessControl instance.
    const acm = new AccessControlMiddleware({secret: "MySecret", accessControl: ac});

AccessControlMiddleware parameters are the following :

  • secret: The secret access token key used to sign the token.
  • accessControl: The AccessControl instance.
  • filter: A custom filter function that will be used to filter findAll resources when user only have access on a subset of resources.
  • tokenFormat: The format of the token ( eg: Bearer, JWT) (default: Bearer)
  • userKey: The request param key used to store the user (default: user)
  • usernameKey: THe key of the request user object that hold the user name. (default: name)
  • userIdKey: THe key of the request user object that hold the user id. (default: id)
  • transformUserName: A function to apply on the AccessControl instance roles name to handle role and user in it.( default : prefix with u-)

filter function

By default, AccessControl will filter resource by checking the resource entry of the access token payload. It will then inject parameter into the query to filter the request. AccessControlMiddleware follow the jsonapi, so the produce query will be

req: {
    query : {
        filters: {
            id: {"value":"[1,2,3]","operator":"in"}
        }
    }
}

If you want change this functionality simply pass your custom filter function to the AccessControlMiddleware constructor.To disable this feature and post filter resource in your route, just pass an empty function :

transformUserName

This middleware handle the use of User right in AccessControl like Role. To differentiate between Role and User with the same name (eg: Admin role and Admin user), you can pass a function that will updates all the users names. For example, you can prefix all the users names with u-.

How you load your users and roles inside accessControl is up to you and out of the scope of this middleware. AccessControl does not provide any support of user's base authorization, but it's work really well.

Specifics/dynamics resources

To grant authorizations to a specific resource or a set of resources, you must tell to AccessControlMiddleware, which resources a user can access. To do that, define a resource's entry in your access token payload in this form:

resources: [
    {type: "foo", fkey:"1"}
    {type: "foo", fkey:"2"}
    {type: "foo", fkey:"3"}
    {type: "bar", fkey:"1"}
]

AccessControlMiddleware handle specifics and dynamics permissions in the same way. Just merge all resources into a unique list and register it, into the access token.

Protect route

Use the check method on every route you want to protect.

/**
* Access to a list of resources
*/
findAll() {
    this.router.route(`/foos`).get([passport.authenticate("jwt", {session: false}), acm.check([{
            resource: "foo",
            action: "read"
        }])], async(req, res) => {
    });
}

/**
* Access to a list of resources with multiple permissions
*/
findAll() {
    this.router.route(`/foos`).get([passport.authenticate("jwt", {session: false}), acm.check([
        {resource: "foo", action: "read"}
        {resource: "bar", action: "read"}
        ])], async(req, res) => {
    });
}

/**
* Action on a specific/dynamic resource
*/
find() {
    this.router.route(`/foo/:fooId`).get([passport.authenticate("jwt", {session: false}), acm.check([{
            resource: "foo",
            action: "read",
            context: {type: "foo", source: "params", key: `fooId`}
        }])], (req, res) => {
    });
}
  • context.source is the key used to hold request parameters.
  • context.key is the resource key in the request parameters object.
  • context.type is the resource type.

Special case of related resources loading.

You want user to be able to create a resource of type Foo. So you give the authorization to create the resource Foo for this user. This resource depends on of another resource of type Bar. So in the Foo resource create form you have a select box with all the resources of type Bar in it. This is great, but your user can't read this list of Bar resource because, it has not authorization on it. So to solve this problem, you have two solution :

  • The first, is to tell you competent administrator to also add an authorization to let the user see the Bar resource name.
  • The second, is to use application triggers to update dependants authorizations.

In the above example, the creation of an authorization for the resource Foo will also trigger an authorization for the type Bar.

  • The third, is to use the related mechanism incorporated with this middleware.

AccessControlMiddleware will check for the presence of a field token in the request query. If it found one, the token is verify, and the resource accessed is compared against the information contains in the token. This following code is an example of how generate this kind of token. How you use it, is your responsibility.

const jwt = require("jsonwebtoken");
// ...

const relatedToken = jwt.sign({
    data: {resource, user: user.id, typeAction, possession, attributes}
    }, "MySecret", {expiresIn: 60});

The expiresIn parameter must be short but enough long to take into account request latency as the client will need to fetch the related resources after the main resources. You must send this token with the response of the main resource. If you follow the jsonapi.org, this must be place inside the links.related field.

 {
    links.related = [
        `https://www.myDomain.org/api/bar?token=${relatedToken}`
    ]
 }

In our example

Note

This middleware use jsonwebtoken to handle token verification.