MongoDB adapter for jCasbin

Clone this repo:
  1. 1b158df feat: change all texts to English (#11) by ZHOU05030 · 1 year, 4 months ago master v1.2.0
  2. 9d7fc5a feat: improve the README (#9) by sukidayou · 1 year, 4 months ago v1.1.0
  3. 2ddda6b feat: improve pom.xml, CI scripts (#7) by sukidayou · 1 year, 4 months ago v1.0.0
  4. 65f0575 MongoAdapter now implement BatchAdapter (#4) by Gautier Dhordain · 1 year, 4 months ago
  5. acf0629 Merge pull request #1 from zzl221000/add-license-1 by JimZhang · 5 years ago

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.