Node-Casbin

repository·master·Indexed 25 days ago

https://github.com/apache/casbin-node-casbin

An authorization library for Node.js that supports access control models including ACL, RBAC, and ABAC. It provides a CoreEnforcer for making authorization decisions, a Config class for managing model settings, and APIs for dynamic permission and role management. Supports policy persistence via adapters and provides both synchronous and asynchronous enforcement methods.

Tokens
6.9K
Snippets
5
Records
52
Agent score
84%

What's inside casbin

  1. Initialize a new enforcer

    master

    To start using Casbin, create a new enforcer instance by providing a model configuration file and a policy file. You can also initialize an enforcer using a database via adapters (see Policy Persistence documentation).

    // For Node.js:
    const { newEnforcer } = require('casbin');
    // For browser:
    // import { newEnforcer } from 'casbin';
    
    const enforcer = await newEnforcer('basic_model.conf', 'basic_policy.csv');
  2. Use SyncedEnforcer for synchronized authorization

    master
    The SyncedEnforcer class wraps the standard Enforcer to provide synchronized access to policy operations using an internal lock. This is useful in environments where concurrent policy modifications or enforcement requests might lead to race conditions. It also supports a Watcher to automatically reload policies when changes are detected in other nodes.
  3. Initialize an Enforcer

    master

    You can create a new Enforcer instance using the newEnforcer function. It supports several initialization patterns including loading from files, strings, or database adapters.

    Initialization Patterns

    1. From Files: Provide paths to a model configuration file and a policy CSV file.
    2. From a Database Adapter: Provide a path to a model file and an instance of an Adapter (e.g., MySQL, PostgreSQL).
    3. From a String: Provide a path to a model file and a CSV string containing the policy.
    4. From a Model Object: Provide a Model instance and an Adapter.
    // File-based initialization
    const e = new Enforcer('path/to/basic_model.conf', 'path/to/basic_policy.csv');
    
    // Database adapter initialization
    const a = new MySQLAdapter('mysql', 'mysql_username:mysql_password@tcp(127.0.0.1:3306)/');
    const e = new Enforcer('path/to/basic_model.conf', a);
  4. Enforce authorization requests

    master

    Use the enforce method to check if a subject (user) is allowed to perform an action on an object (resource). This is an asynchronous operation. For synchronous enforcement, use enforceSync.

    const sub = 'alice'; // the user that wants to access a resource.
    const obj = 'data1'; // the resource that is going to be accessed.
    const act = 'read'; // the operation the user performs on the resource.
    
    // Async:
    const res = await enforcer.enforce(sub, obj, act);
    // Sync:
    // const res = enforcer.enforceSync(sub, obj, act);
    
    if (res) {
      // permit alice to read data1
    } else {
      // deny the request, show an error
    }
  5. Manage permissions at run-time

    master

    Casbin provides APIs to manage permissions dynamically without restarting the application. You can use the Management API for full control or the RBAC API for a simplified interface focused on Role-Based Access Control. For example, you can retrieve all roles assigned to a specific user.

    const roles = await enforcer.getRolesForUser('alice');
  6. Define custom matching functions with FunctionMap

    master
    You can extend Casbin's matching capabilities by using the FunctionMap class to register custom matching functions. A MatchingFunction is a function that accepts any number of arguments and returns a boolean, number, string, or a Promise resolving to one of those types. Use addFunction(name, func) to register your custom function under a specific name that can then be used in your Casbin model file.
  7. Add authorization and grouping policies

    master

    Use these methods to add rules to your policy. If a rule already exists, the operation will return false and the rule will not be added.

    • addPolicy(...params): Adds a single p rule.
    • addPolicies(rules): Adds multiple p rules.
    • addGroupingPolicy(...params): Adds a single g rule.
    • addGroupingPolicies(rules): Adds multiple g rules.
    • addPoliciesEx(rules): An extended version that skips existing rules and continues adding the rest. Returns true if at least one rule was added successfully.
    • addNamed... versions: Allow you to specify a custom policy type like p2 or g2.
  8. Retrieve subjects, objects, and actions from policies

    master

    The ManagementEnforcer provides methods to extract unique lists of subjects, objects, or actions from your policy rules.

    • Subjects: Extracted from the 0-index of p policy rules (e.g., sub in sub, obj, act).
    • Objects: Extracted from the 1-index of p policy rules (e.g., obj in sub, obj, act).
    • Actions: Extracted from the 2-index of p policy rules (e.g., act in sub, obj, act).
    • Roles: Extracted from the 1-index of g policy rules (e.g., role in sub, role).

    You can use the generic getAllNamed... versions to specify a custom policy type (e.g., p2, g2).

  9. Check role inheritance with hasLink

    master

    Determine if one role inherits another using hasLink (asynchronous) or syncedHasLink (synchronous). You can optionally specify a domain.

    • hasLink(name1, name2, domain?): Returns a Promise<boolean> indicating if name1 inherits name2.
    • syncedHasLink(name1, name2, domain?): Synchronously returns a boolean indicating if name1 inherits name2.