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: truecannot(resource: string, action: string): boolean
The inverse of can, determining if a role lacks permission for an action.
role.cannot('user', 'ban'); // Returns: trueAdvanced 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: truecanAll(resource: string, actions: string[]): boolean
Verifies if the role has permissions for all specified actions.
role.canAll('post', ['update', 'delete']); // Returns: falseUsage and Best Practices
- 
Granular Control: Use these methods to implement fine-grained access control in your application.
 - 
Conditional Rendering: Employ these checks for conditional rendering of UI elements based on user permissions.
 - 
API Authorization: Integrate these methods in your API middleware to enforce resource-level access control.
 - 
Audit Trails: Log permission checks for comprehensive security audits.
 - 
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.