DEV Community

Cover image for Granular Permission Management with CASL Library
Tomek Piela for Brainhub

Posted on • Updated on • Originally published at brainhub.eu

Granular Permission Management with CASL Library

Managing permission for complex applications is too… complex

User permissions management is one of the biggest challenges for complex applications. With multiple users working on different aspects, it is important to ensure that each user has the appropriate level of access to the data they need to do their job. Access control becomes an even bigger issue when the roles keep on changing as the application grows, especially in large organizations with complex hierarchies and multiple user roles.

Here's how we set up granular project management in a Metrics Tool application.

What is a Metrics Tool?

It is an essential platform for IT project management that allows users to monitor and evaluate the performance of various IT projects. The tool provides insights and metrics on project progress and other critical parameters, enabling businesses to make data-driven decisions.

Granular permissions with CASL library

This is where the CASL library comes into play.

CASL is a library for managing user permissions and access control in JavaScript applications. It provides a flexible and powerful way to define user roles and permissions and to enforce those permissions across the application.

With the CASL library, administrators can define granular permissions for different user roles, ensuring that users only have access to the features and data they need to perform their tasks. For example, project managers may have access to all project metrics, while team members may only be able to view metrics related to their specific projects.

Granular Permission Management with CASL Library

CASL Library in action

By using the CASL library in the Metrics Tool project, organizations can ensure that their data is secure and that users have access to the right information, resulting in better decision-making and improved project outcomes.

import { AbilityBuilder, createMongoAbility } from '@casl/ability';
import { User } from '../models' // application specific interfaces

function defineAbilitiesFor(user: User) {
  const { can, cannot, build } = new AbilityBuilder(createMongoAbility);

  // can read blog posts
  can('read', 'BlogPost');
  // can manage their own blog posts
  can('manage', 'BlogPost', { author: user.id });
  // cannot delete published blog posts that where created more than a day ago
  cannot('delete', 'BlogPost', { 
    isPublished: true, 
    createdAt: { 
      $lt: Date.now() - 24 * 3600 * 1000 
    } 
  });

  return build();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)