Skip to content

sukidayou/jcasbin-mongo-adapter

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jcasbin-mongodb-adapter

codebeat badge build codecov javadoc Maven Central Discord

jcasbin-mongodb-adapter is the MongoDB adapter for jCasbin. With this library, jCasbin can load policy from a MongoDB database or save policy to it.

Installation

For Maven:

<dependency>
    <groupId>org.casbin</groupId>
    <artifactId>jcasbin-mongo-adapter</artifactId>
    <version>LATEST</version>
</dependency>

optional: If your project already has a mongodb driver, please ignore it.

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>${mongodb.version}</version>
</dependency>

Simple Example

package org.casbin.adapter;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.casbin.jcasbin.main.Enforcer;
import org.casbin.jcasbin.persist.Adapter;
import org.jim.jcasbin.MongoAdapter;

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        // Use MongoDB connection string and database name to initialize a MongoAdapter.
        String connectionString = "mongodb://localhost:27017/";
        MongoClient mongoClient = MongoClients.create(connectionString);
        MongoDatabase database = mongoClient.getDatabase("casbin");

        // Check and create a collection
        if (!database.listCollectionNames().into(new ArrayList<>()).contains("casbin_rule")) {
            database.createCollection("casbin_rule");
        }

        Adapter adapter = new MongoAdapter(mongoClient, "casbin");
        Enforcer enforcer = new Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv");

        // Check the permission.
        enforcer.enforce("alice", "data1", "read");

        // Modify the policy.
        // enforcer.addPolicy(...);
        // enforcer.removePolicy(...);

        // Save the policy back to DB.
        adapter.savePolicy(enforcer.getModel());

        // Close the MongoDB client.
        mongoClient.close();
    }
}

Getting Help

License

This project is under Apache 2.0 License. See the LICENSE file for the full license text.

About

MongoDB policy storage, implemented as an adapter for casbin

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java 100.0%