New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@katomaran/nest-role-group

Package Overview
Dependencies
Maintainers
2
Versions
38
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@katomaran/nest-role-group

@katomaran/nest-role-group is a NestJS package that simplifies the implementation of role-based access control (RBAC) within your application. It enables role management, permission checks, and integrates seamlessly with Redis for caching roles and permis

  • 0.3.8
  • unpublished
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
2
Weekly downloads
 
Created
Source

@katomaran/nest-role-group

Overview

@katomaran/nest-role-group is a NestJS package that simplifies the implementation of role-based access control (RBAC) within your application. It enables role management, permission checks, and integrates seamlessly with Redis for caching roles and permissions.

Features

Role and Role Group Creation: Define and manage roles and role groups. Permission Validation: Check if a user or role group has the required permissions for specific API routes. Guard Integration: Integrates a PermissionGuard that secures routes based on roles. Redis Caching: Caches roles and permissions in Redis for faster access and reduced database load. Redis Expiry: Sets an expiration time for cached roles and permissions to ensure data is refreshed regularly.

Installation

To install @katomaran/nest-role-group, use the following commands:

Using npm

npm install @katomaran/nest-role-group

Using Yarn

yarn add @katomaran/nest-role-group

Module Setup

In order to use the role and permission features, import the RoleModule in your AppModule and configure it with your MongoDB and Redis settings.

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { RoleModule } from '@katomaran/nest-role-group';

@Module({
  imports: [
    MongooseModule.forRoot('your_mongo_db_connection_string'), // MongoDB connection
    RoleModule, // Import the Role module for role management
  ],
})
export class AppModule {}

Main Guard Registration

main_guard_registration: description: > Import and configure PermissionGuard, and set up role groups and roles at application startup in main.ts.

    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    import { PermissionGuard } from '@katomaran/nest-role-group';
    import { RoleUtilityService } from '@katomaran/nest-role-group'; # Adjust the path as needed
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      
      # Retrieve RoleUtilityService instance
      const roleUtilityService = app.get(RoleUtilityService);

      try:
        # Initialize role groups from roleGroup.json
        await roleUtilityService.createRoleGroupsFromFile('file path to the role groups');
        console.log('Role groups created successfully');

        # Initialize roles from permission.json
        await roleUtilityService.createRolesFromFile('file path to the roles');
        console.log('Roles created successfully');
      } catch (error) {
        console.error('Error creating role groups or roles:', error);
      }

      # Register PermissionGuard globally
      app.useGlobalGuards(new PermissionGuard());

      # Start application
      await app.listen(3000);
      console.log('Application is running on http://localhost:3000');
      bootstrap();
  

Redis Configuration

This package integrates with Redis to cache role and permission data. Ensure your Redis instance is correctly configured.

Environment Variables Set the following environment variables in your .env file to configure Redis:

REDIS_URL: Your Redis connection URL. This connects the application to Redis for caching.

Example:

REDIS_URL='redis://username:password@domain:port'
ROLE_CACHE: Defines the caching strategy, whether roles and permissions are fetched from both the database and cache (DB_AND_CACHE), or directly from cache (CACHE_ONLY).

Example:

ROLE_CACHE='DB_AND_CACHE'
REDIS_EXPIRY: Specifies the expiration time in seconds for cached role and permission data. After this time, the data will be automatically removed from the cache, ensuring it is refreshed from the database when needed.

Example:

REDIS_EXPIRY=86400 # 1 day in seconds Redis Key Structure Role Cache: role: - Stores role information and its associated permissions. Role Group Cache: roleGroup: - Stores role group information and the roles associated with the group. Permission Cache: permissions::: - Caches permissions associated with a route and HTTP method. Redis Expiry By default, cached role and permission data will expire based on the REDIS_EXPIRY value. This ensures that the cache is refreshed at regular intervals to prevent stale data from being used.

For example, if you set REDIS_EXPIRY=86400 (1 day), all cached data will be automatically cleared after one day.

Expiry Example: If you're caching a role with the key role:12345, the expiration time will be set as follows:

import { RedisService } from '@nestjs/redis';

@Injectable()
export class RoleService {
  constructor(private readonly redisService: RedisService) {}

  async cacheRole(roleId: string, roleData: any) {
    const redisClient = this.redisService.getClient();
    const expiryTime = process.env.REDIS_EXPIRY || 86400; // Default to 1 day

    await redisClient.setex(`role:${roleId}`, expiryTime, JSON.stringify(roleData));
  }
}

Guard Setup The PermissionGuard is used to secure routes based on roles and permissions. It checks whether a user or role group has the necessary permissions to access a specific route.

Register Permission Guard To use the PermissionGuard globally, register it in your main.ts file:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { PermissionGuard } from '@katomaran/nest-role-group';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // Register the PermissionGuard globally
  app.useGlobalGuards(new PermissionGuard());

  await app.listen(3000);
  console.log('Application is running on http://localhost:3000');
}
bootstrap();

Usage of Permission Decorators You can use decorators like @Public() to mark specific routes as accessible by any user, bypassing permission checks for that route.

typescript Copy code import { Controller, Get } from '@nestjs/common'; import { Public } from '@katomaran/nest-role-group';

@Controller('users') export class UserController { @Get() @Public() // Skip permission checks for this route async getUsers() { // Logic to get users } }

Permission Guard Behavior The PermissionGuard works by checking if the current user has the correct permissions based on the route and HTTP method. If no permission is found, the guard denies access and responds with an HTTP 403 (Forbidden).

Example For example, if you have a role group "Admin" that has access to GET /users, the guard ensures that only users in the "Admin" role group can access that route:

{
  "name": "Admin",
  "permissions": {
    "route": "/users",
    "methods": ["GET"]
  }
}

Role Group Permission Check If a user belongs to a "User" role group, the following permissions will be checked for any route they attempt to access:

{
  "name": "User",
  "permissions": {
    "route": "/users/:id",
    "methods": ["PUT"]
  }
}

Example Controller with Permissions

import { Controller, Get, Put } from '@nestjs/common';
import { UseGuards } from '@nestjs/common';
import { PermissionGuard } from '@katomaran/nest-role-group';

@Controller('users')
@UseGuards(PermissionGuard)
export class UserController {
  @Get()
  async getAllUsers() {
    return 'Getting all users';
  }

  @Put(':id')
  async updateUser() {
    return 'User updated';
  }
}

In this example, the PermissionGuard will check if the user has permission to access either GET /users or PUT /users/:id based on their assigned role and permissions.

Role and Role Group Setup Roles and role groups can be created and managed using JSON files. These files define the permissions for each role and group.

Example roles.json

[
  {
    "name": "Admin",
    "permissions": [
      {
        "route": "/users",
        "methods": ["GET", "POST", "PUT", "DELETE"]
      }
    ]
  },
  {
    "name": "User",
    "permissions": [
      {
        "route": "/users/:id",
        "methods": ["GET", "PUT"]
      }
    ]
  }
]

Example role_groups.json

[
  {
    "name": "Admin Group",
    "roles": ["Admin"]
  },
  {
    "name": "User Group",
    "roles": ["User"]
  }
]

Creating Roles and Role Groups from File You can create roles and role groups from JSON files using the RoleUtilityService. Here's how you can integrate it into your NestJS application.

import { Injectable } from '@nestjs/common';
import { RoleUtilityService } from '@katomaran/nest-role-group';

@Injectable()
export class RoleService {
  constructor(private readonly roleUtilityService: RoleUtilityService) {}

  async createRoles() {
    try {
      await this.roleUtilityService.createRolesFromFile('path/to/roles.json');
      console.log('Roles created successfully');
    } catch (error) {
      console.error('Error creating roles:', error);
    }
  }

  async createRoleGroups() {
    try {
      await this.roleUtilityService.createRoleGroupsFromFile('path/to/role_groups.json');
      console.log('Role groups created successfully');
    } catch (error) {
      console.error('Error creating role groups:', error);
    }
  }
}

Conclusion

@katomaran/nest-role-group provides an efficient and scalable solution for role-based access control in NestJS applications. It simplifies managing roles and permissions while leveraging Redis for caching, reducing the load on your database and improving performance.

Ensure that your Redis and MongoDB configurations are set up properly, and use the PermissionGuard to secure routes and manage access based on user roles. Redis expiration settings ensure that cached data is refreshed regularly, preventing stale data from being used.

FAQs

Package last updated on 25 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc