Check Permissions

Learn how to use the permission check methods in the Role class for precise access control.

Check Permissions

The Role class in iamjs provides a set of powerful methods for verifying permissions. These methods enable precise access control and authorization decisions based on role capabilities.

import { Role } from '@iamjs/core';

const role = new Role({
    name: 'role',
    config: {
      user: {
        base: 'crudl',
        custom: {
          ban: false
        }
      },
      post: {
        base: '-rudl',
        custom: {
          publish: true
        }
      }
    }
});

Core Check Methods

can(resource: string, action: string): boolean

Verifies if the role can perform a specific action on a given resource.

role.can('user', 'update'); // Returns: true

cannot(resource: string, action: string): boolean

The inverse of can, determining if a role lacks permission for an action.

role.cannot('user', 'ban'); // Returns: true

Advanced Check Methods

canAny(resource: string, actions: string[]): boolean

Checks if the role has permission for at least one of the specified actions.

role.canAny('post', ['create', 'read']); // Returns: true

canAll(resource: string, actions: string[]): boolean

Verifies if the role has permissions for all specified actions.

role.canAll('post', ['update', 'delete']); // Returns: false

Usage and Best Practices

  1. Granular Control: Use these methods to implement fine-grained access control in your application.

  2. Conditional Rendering: Employ these checks for conditional rendering of UI elements based on user permissions.

  3. API Authorization: Integrate these methods in your API middleware to enforce resource-level access control.

  4. Audit Trails: Log permission checks for comprehensive security audits.

  5. Performance Optimization: These methods are designed for efficient, frequent checks without significant performance overhead.

Example: Implementing a Permission Guard

function guardedAction(role: Role, resource: string, action: string, callback: () => void) {
  if (role.can(resource, action)) {
    callback();
  } else {
    console.log('Permission denied');
  }
}

// Usage
guardedAction(userRole, 'document', 'edit', () => {
  // Perform protected action
});

By leveraging these permission check methods, you can create a robust, flexible, and easily maintainable authorization system in your application, ensuring that users only access resources and perform actions they're explicitly permitted to.