2.2.5 • Published 8 months ago

@nextnm/nestjs-next-guard v2.2.5

Weekly downloads
32
License
MIT
Repository
github
Last release
8 months ago

Introduction

This is simple guard which can protect your routes by Role (RBAC) and also has the ability to check the ownership chain of the requested entity.

Example

As an example consider that you are a user belonging to an organization which has some books associated. Now, if you request a book by id this guard will check if the book that you are trying to fetch belongs to the organization that you are associated and so on. You only need to pass the models chain as well as the property chain.

Installation

npm i @nextnm/nestjs-next-guard

Usage

Caveats

  1. We only support applications using mongodb.
  2. You must be sure that in every request that the guard is used there is a user property in the request with an array of roles.
  3. It will only contemplates situations where you a have an id as request param (GET ("/:id")) or in the body (PUT updating object {_id:"...", "property1":....})

Interface Decorator

export interface ICheckOwnerShip {
  requestParam: string; // name of param that has the id mentioned in caveat 3
  modelChain: string[]; // the chain of ownership between models
  propertyChain: string[]; // array of the properties that link the models
  godRole?: string; // the role that will overcome the verification
}

Importing module

import * as mongoose from 'mongoose';
import { NextGuardModule } from '@nextnm/nestjs-next-guard';

...
@Module({
  imports: [
    DbModule,
    NextGuardModule.forRoot(),
  ],
  controllers: [],
  providers: [],
  exports: [NestjsNextGuardModule],
})
export class YOURModule {}

Importing module (Redis integration)

We support Redis cache to improve performance when we have multiple chain nodes to verify ownership

import * as mongoose from 'mongoose';
import { NextGuardModule } from '@nextnm/nestjs-next-guard';

...
@Module({
  imports: [
    DbModule,
    NextGuardModule.forRoot(
      {
        redisConfiguration: {
          url: 'redis://localhost:6379'
          retry_strategy: () => 1000,
          mongooseInstance: mongoose,
        },
      }
    ),
  ],
  controllers: [],
  providers: [],
  exports: [NestjsNextGuardModule],
})
export class YOURModule {}

Using decorators

Be aware that both decorators (Roles and CheckOwnerShip) are optional so use them as you want.

1. Use Case

User:
{
  _id:ObjectId
}

Site:
{
  _id:ObjectId,
  user:ObjectId
}

Page:
{
  _id:ObjectId,
  site:ObjectId
}
Description (A user belongs to an Site)
  1. The guard will take a look if you have role based permission to use this route
  2. The guard will look for an "Page" (modelChain0) by id equals to the request param;
  3. From the found Page it will try to grab the property 'site' (propertyChain0) and find a Site (modelChain1) by id equal to that property (propertyChain0).
  4. From the Site found it will check if the property "user" matches the id of the user making the request.
  import { CheckOwnerShip, Roles } from '@nextnm/nestjs-next-guard';

  ...

  @CheckOwnerShip({
    requestParam: 'modelId',
    propertyChain: ['site', 'user'], // The last property will be compared with the Id of the user making the request
    modelChain: ['Page','Site'],
    godRole: ExistingRoles.SYS_ADMIN, // If the user has this role not check will be done by the guard
  })
  @Roles(ExistingRoles.USER, ExistingRoles.ADMIN) // Provide the roles that you allow to execute this method,example: 'USER', 'ADMIN'
  @UseGuards(NextGuard)
  @Get(':modelId')
  async findPageById(@Param('id') id: string) {
    //...
  }

2. Use case

User:
{
_id:ObjectId,
organization:ObjectId
}


Organization:
{
  _id:ObjectId
}
Description (A user belongs to an organization)
  1. The guard will take a look if you have role based permission to use this route
  2. The guard will look for an Organization (modelChain0) by id equals to the request param;
  3. From the found Organization it will try to grab the property '_id' (propertyChain0) and find a User (modelChain1) by id equal to the that property (propertyChain0).
  4. Since there isn't any, it will try to find a User with a property "organization" (propertyChain1) equals to the organization "_id" property(propertyChain0)
  5. From the User found it will check if the property "_id" matches the id of the user making the request.
  import { CheckOwnerShip, Roles } from '@nextnm/nestjs-next-guard';

    ...

    @CheckOwnerShip({
    requestParam: 'id',
    propertyChain: ['_id','organization','_id'], // The last property will be compared with the Id of the user making the request
    modelChain: ['Organization','User'],
    godRole: ExistingRoles.SYS_ADMIN, // If the user has this role not check will be done by the guard
  })
  @Roles(ExistingRoles.USER, ExistingRoles.ADMIN) // Provide the roles that you allow to execute this method,example: 'USER', 'ADMIN'
  @UseGuards(AuthGuard('jwt'),NextGuard)
  @Get('/:id')
  findOrganizationById(@Param() params): Promise<ReadOrganizationDto> {
    //...
  }

Contributing

Contributions are welcome! See Contributing.

Next steps

  1. Improve documentation
  2. Add some tests using Jest and supertest
  3. Add full support do many to many relationships between models (it doesn't alow having array of ids as relationships)
  4. Build Policy Based Guard

Author

Nuno Carvalhão (nextnm/nextNC) Site

License

Licensed under the MIT License - see the LICENSE file for details.

2.2.1

8 months ago

2.2.3

8 months ago

2.2.2

8 months ago

2.2.5

8 months ago

2.2.4

8 months ago

2.2.0

12 months ago

2.1.7

3 years ago

2.1.4

3 years ago

2.1.6

3 years ago

2.1.5

3 years ago

2.1.3

3 years ago

2.1.2

3 years ago

2.1.1

3 years ago

2.0.3

4 years ago

2.0.2

4 years ago

2.0.1

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago

0.0.3

4 years ago

0.0.4

4 years ago

0.0.2

4 years ago

0.0.1-beta-6

4 years ago

0.0.1-beta-5

4 years ago

0.0.1-beta-4

4 years ago

0.0.1-beta-3

4 years ago

0.0.1-beta-2

4 years ago

0.0.1-beta-1

4 years ago

0.0.1-rc-beta-1

4 years ago

0.0.1

4 years ago