├── examples
├── rbac_policy.csv
├── rbac_with_domains_policy.csv
├── rbac_model.conf
└── rbac_with_domains_model.conf
├── .gitignore
├── maven-settings.xml
├── src
├── main
│ └── java
│ │ └── org
│ │ └── casbin
│ │ └── adapter
│ │ ├── JDBCDataSource.java
│ │ ├── JDBCAdapter.java
│ │ └── JDBCBaseAdapter.java
└── test
│ └── java
│ └── org
│ └── casbin
│ └── adapter
│ ├── AdapterCreator.java
│ ├── JDBCAdapterTestSets.java
│ └── JDBCAdapterTest.java
├── .github
└── workflows
│ └── maven-ci.yml
├── README.md
├── pom.xml
└── LICENSE
/examples/rbac_policy.csv:
--------------------------------------------------------------------------------
1 | p, alice, data1, read
2 | p, bob, data2, write
3 | p, data2_admin, data2, read
4 | p, data2_admin, data2, write
5 | g, alice, data2_admin
--------------------------------------------------------------------------------
/examples/rbac_with_domains_policy.csv:
--------------------------------------------------------------------------------
1 | p, admin, domain1, data1, read
2 | p, admin, domain1, data1, write
3 | p, admin, domain2, data2, read
4 | p, admin, domain2, data2, write
5 | g, alice, admin, domain1
6 | g, bob, admin, domain2
--------------------------------------------------------------------------------
/examples/rbac_model.conf:
--------------------------------------------------------------------------------
1 | [request_definition]
2 | r = sub, obj, act
3 |
4 | [policy_definition]
5 | p = sub, obj, act
6 |
7 | [role_definition]
8 | g = _, _
9 |
10 | [policy_effect]
11 | e = some(where (p.eft == allow))
12 |
13 | [matchers]
14 | m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
--------------------------------------------------------------------------------
/examples/rbac_with_domains_model.conf:
--------------------------------------------------------------------------------
1 | [request_definition]
2 | r = sub, dom, obj, act
3 |
4 | [policy_definition]
5 | p = sub, dom, obj, act
6 |
7 | [role_definition]
8 | g = _, _, _
9 |
10 | [policy_effect]
11 | e = some(where (p.eft == allow))
12 |
13 | [matchers]
14 | m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && r.obj == p.obj && r.act == p.act
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.nar
17 | *.ear
18 | *.zip
19 | *.tar.gz
20 | *.rar
21 |
22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
23 | hs_err_pid*
24 |
25 | target
26 |
27 | .idea/
28 | *.iml
--------------------------------------------------------------------------------
/maven-settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ossrh
5 | ${OSSRH_JIRA_USERNAME}
6 | ${OSSRH_JIRA_PASSWORD}
7 |
8 |
9 |
10 |
11 | ossrh
12 |
13 | true
14 |
15 |
16 | gpg
17 | ${GPG_KEY_NAME}
18 | ${GPG_PASSPHRASE}
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/src/main/java/org/casbin/adapter/JDBCDataSource.java:
--------------------------------------------------------------------------------
1 | // Copyright 2020 The casbin Authors. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package org.casbin.adapter;
16 |
17 | import javax.sql.DataSource;
18 | import java.io.PrintWriter;
19 | import java.sql.Connection;
20 | import java.sql.DriverManager;
21 | import java.sql.SQLException;
22 | import java.sql.SQLFeatureNotSupportedException;
23 | import java.util.logging.Logger;
24 |
25 | public class JDBCDataSource implements DataSource {
26 | private String driver;
27 | private String url;
28 | private String username;
29 | private String password;
30 |
31 |
32 | JDBCDataSource(String driver, String url, String username, String password) throws ClassNotFoundException {
33 | Class.forName(driver);
34 | this.driver = driver;
35 | this.url = url;
36 | this.username = username;
37 | this.password = password;
38 | }
39 |
40 | @Override
41 | public Connection getConnection() throws SQLException {
42 | return DriverManager.getConnection(this.url, username, password);
43 | }
44 |
45 | @Override
46 | public Connection getConnection(String username, String password) throws SQLException {
47 | return null;
48 | }
49 |
50 | @Override
51 | public T unwrap(Class iface) throws SQLException {
52 | return null;
53 | }
54 |
55 | @Override
56 | public boolean isWrapperFor(Class> iface) throws SQLException {
57 | return false;
58 | }
59 |
60 | @Override
61 | public PrintWriter getLogWriter() throws SQLException {
62 | return null;
63 | }
64 |
65 | @Override
66 | public void setLogWriter(PrintWriter out) throws SQLException{
67 |
68 | }
69 |
70 | @Override
71 | public void setLoginTimeout(int seconds) throws SQLException {
72 |
73 | }
74 |
75 | @Override
76 | public int getLoginTimeout() throws SQLException {
77 | return 0;
78 | }
79 |
80 | @Override
81 | public Logger getParentLogger() throws SQLFeatureNotSupportedException {
82 | return null;
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/.github/workflows/maven-ci.yml:
--------------------------------------------------------------------------------
1 | name: build
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | build:
7 | runs-on: ubuntu-latest
8 | services:
9 | mysql:
10 | image: mysql
11 | env:
12 | MYSQL_ROOT_PASSWORD: casbin_test
13 | MYSQL_DATABASE: casbin
14 | MYSQL_USER: casbin_test
15 | MYSQL_PASSWORD: TEST_casbin
16 | ports:
17 | - 3306:3306
18 | options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
19 | postgres:
20 | image: postgres
21 | env:
22 | POSTGRES_DB: casbin
23 | POSTGRES_USER: casbin_test
24 | POSTGRES_PASSWORD: TEST_casbin
25 | ports:
26 | - 5432:5432
27 | options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
28 | sqlserver:
29 | image: mcr.microsoft.com/mssql/server:2019-latest
30 | env:
31 | SA_PASSWORD: 9G3iqmzQDw9zCXII
32 | ACCEPT_EULA: Y
33 | ports:
34 | - 1433:1433
35 |
36 | steps:
37 | - name: Checkout
38 | uses: actions/checkout@v2
39 | with:
40 | fetch-depth: '0'
41 |
42 | - name: Install mssql-tools
43 | run: |
44 | curl https://packages.microsoft.com/keys/microsoft.asc | sudo tee /etc/apt/trusted.gpg.d/microsoft.asc
45 | curl https://packages.microsoft.com/config/ubuntu/22.04/prod.list | sudo tee /etc/apt/sources.list.d/msprod.list
46 | sudo apt-get update
47 | sudo ACCEPT_EULA=Y apt-get install -y mssql-tools18 unixodbc-dev
48 | echo 'export PATH="$PATH:/opt/mssql-tools18/bin"' >> ~/.bash_profile
49 |
50 | - name: Create database for sqlserver
51 | run: /opt/mssql-tools18/bin/sqlcmd -S 127.0.0.1,1433 -U sa -P '9G3iqmzQDw9zCXII' -Q "CREATE DATABASE casbin" -C
52 |
53 | - name: Set up JDK 1.8
54 | uses: actions/setup-java@v1
55 | with:
56 | java-version: 1.8
57 | server-id: ossrh
58 | server-username: OSSRH_JIRA_USERNAME
59 | server-password: OSSRH_JIRA_PASSWORD
60 | gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }}
61 | gpg-passphrase: GPG_PASSPHRASE
62 |
63 | - name: Build with Maven
64 | run: mvn clean test cobertura:cobertura
65 |
66 | - name: Codecov
67 | uses: codecov/codecov-action@v1
68 | with:
69 | token: ${{ secrets.CODECOV_TOKEN }}
70 |
71 | - name: Set up Node.js
72 | uses: actions/setup-node@v2
73 | with:
74 | node-version: 20
75 |
76 | - name: Semantic Release
77 | run: |
78 | npm install -g @conveyal/maven-semantic-release semantic-release
79 | semantic-release --prepare @conveyal/maven-semantic-release --publish @semantic-release/github,@conveyal/maven-semantic-release --verify-conditions @semantic-release/github,@conveyal/maven-semantic-release --verify-release @conveyal/maven-semantic-release
80 | env:
81 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
82 | GPG_KEY_NAME: ${{ secrets.GPG_KEY_NAME }}
83 | GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }}
84 | OSSRH_JIRA_USERNAME: ${{ secrets.OSSRH_JIRA_USERNAME }}
85 | OSSRH_JIRA_PASSWORD: ${{ secrets.OSSRH_JIRA_PASSWORD }}
86 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | JDBC Adapter
2 | ====
3 |
4 | [](https://github.com/jcasbin/jdbc-adapter/actions/workflows/maven-ci.yml)
5 | [](https://codecov.io/gh/jcasbin/jdbc-adapter)
6 | [](https://www.javadoc.io/doc/org.casbin/jdbc-adapter)
7 | [](https://mvnrepository.com/artifact/org.casbin/jdbc-adapter/latest)
8 | [](https://discord.gg/S5UjpzGZjN)
9 |
10 | JDBC Adapter is the [JDBC](https://en.wikipedia.org/wiki/Java_Database_Connectivity) adapter for [jCasbin](https://github.com/casbin/jcasbin). With this library, jCasbin can load policy from JDBC supported database or save policy to it.
11 |
12 | Based on [Supported JDBC Drivers and Databases](https://docs.oracle.com/cd/E19226-01/820-7688/gawms/index.html), The currently supported databases are:
13 |
14 | - MySQL
15 | - Java DB
16 | - Oracle
17 | - PostgreSQL
18 | - DB2
19 | - Sybase
20 | - Microsoft SQL Server
21 |
22 | ## Installation
23 |
24 | For Maven:
25 |
26 | ```xml
27 |
28 | org.casbin
29 | jdbc-adapter
30 | LATEST
31 |
32 | ```
33 |
34 | **Notice:**
35 |
36 | Since version 2.0.2, jdbc-adapter adds an ``id`` field to the database table structure by default.
37 |
38 | If you want to upgrade to 2.0.2 - 2.2.0, you have to add the ``id`` field manually. It is recommended to add the ``id`` field. If you don't want to add the ``id`` field, please use 2.2.1+.
39 |
40 | ## Simple Example
41 |
42 | ```java
43 | package com.company.test;
44 |
45 | import org.casbin.adapter.JDBCAdapter;
46 | import org.casbin.jcasbin.main.Enforcer;
47 | import com.mysql.cj.jdbc.MysqlDataSource;
48 |
49 | public class Test {
50 | public static void main() {
51 | String driver = "com.mysql.cj.jdbc.Driver";
52 | String url = "jdbc:mysql://localhost:3306/db_name";
53 | String username = "root";
54 | String password = "123456";
55 |
56 | // The adapter will use the table named "casbin_rule".
57 | // Use driver, url, username and password to initialize a JDBC adapter.
58 | JDBCAdapter a = new JDBCAdapter(driver, url, username, password);
59 |
60 | // Recommend use DataSource to initialize a JDBC adapter.
61 | // Implementer of DataSource interface, such as hikari, c3p0, durid, etc.
62 | MysqlDataSource dataSource = new MysqlDataSource();
63 | dataSource.setURL(url);
64 | dataSource.setUser(username);
65 | dataSource.setPassword(password);
66 |
67 | a = JDBCAdapter(dataSource);
68 |
69 | Enforcer e = new Enforcer("examples/rbac_model.conf", a);
70 |
71 | // Check the permission.
72 | e.enforce("alice", "data1", "read");
73 |
74 | // Modify the policy.
75 | // e.addPolicy(...);
76 | // e.removePolicy(...);
77 |
78 | // Save the policy back to DB.
79 | e.savePolicy();
80 | // Close the connection.
81 | a.close();
82 | }
83 | }
84 | ```
85 |
86 | ## Getting Help
87 |
88 | - [jCasbin](https://github.com/casbin/jcasbin)
89 |
90 | ## License
91 |
92 | This project is under Apache 2.0 License. See the [LICENSE](LICENSE) file for the full license text.
93 |
--------------------------------------------------------------------------------
/src/test/java/org/casbin/adapter/AdapterCreator.java:
--------------------------------------------------------------------------------
1 | // Copyright 2020 The casbin Authors. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package org.casbin.adapter;
16 |
17 | import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
18 | import com.mysql.cj.jdbc.MysqlDataSource;
19 | import oracle.jdbc.pool.OracleDataSource;
20 | import org.postgresql.ds.PGSimpleDataSource;
21 |
22 | public interface AdapterCreator {
23 | JDBCAdapter create() throws Exception;
24 |
25 | JDBCAdapter createViaDataSource() throws Exception;
26 | }
27 |
28 | class MySQLAdapterCreator implements AdapterCreator {
29 | private String url = "jdbc:mysql://127.0.0.1:3306/casbin?serverTimezone=GMT%2B8&useSSL=false&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true";
30 | private String username = "casbin_test";
31 | private String password = "TEST_casbin";
32 | private String driver = "com.mysql.cj.jdbc.Driver";
33 |
34 | @Override
35 | public JDBCAdapter create() throws Exception {
36 | return new JDBCAdapter(driver, url, username, password);
37 | }
38 |
39 | @Override
40 | public JDBCAdapter createViaDataSource() throws Exception {
41 | MysqlDataSource dataSource = new MysqlDataSource();
42 | dataSource.setURL(url);
43 | dataSource.setUser(username);
44 | dataSource.setPassword(password);
45 |
46 | return new JDBCAdapter(dataSource);
47 | }
48 |
49 | public JDBCAdapter create(boolean removePolicyFailed, String tableName, boolean autoCreateTable) throws Exception {
50 | return new JDBCAdapter(driver, url, username, password, removePolicyFailed, tableName, autoCreateTable);
51 | }
52 |
53 | public JDBCAdapter createViaDataSource(boolean removePolicyFailed, String tableName, boolean autoCreateTable) throws Exception {
54 | MysqlDataSource dataSource = new MysqlDataSource();
55 | dataSource.setURL(url);
56 | dataSource.setUser(username);
57 | dataSource.setPassword(password);
58 |
59 | return new JDBCAdapter(dataSource, removePolicyFailed, tableName, autoCreateTable);
60 | }
61 | }
62 |
63 | class OracleAdapterCreator implements AdapterCreator {
64 | private String url = "jdbc:oracle:thin:@//localhost:1521/orcl";
65 | private String username = "system";
66 | private String password = "oracle";
67 | private String driver = "oracle.jdbc.driver.OracleDriver";
68 |
69 | @Override
70 | public JDBCAdapter create() throws Exception {
71 | return new JDBCAdapter(driver, url, username, password);
72 | }
73 |
74 | @Override
75 | public JDBCAdapter createViaDataSource() throws Exception {
76 | OracleDataSource dataSource = new OracleDataSource();
77 | dataSource.setURL(url);
78 | dataSource.setUser(username);
79 | dataSource.setPassword(password);
80 |
81 | return new JDBCAdapter(dataSource);
82 | }
83 | }
84 |
85 | class PgAdapterCreator implements AdapterCreator {
86 | private String url = "jdbc:postgresql://localhost:5432/casbin";
87 | private String username = "casbin_test";
88 | private String password = "TEST_casbin";
89 | private String driver = "org.postgresql.Driver";
90 |
91 | @Override
92 | public JDBCAdapter create() throws Exception {
93 | return new JDBCAdapter(driver, url, username, password);
94 | }
95 |
96 | @Override
97 | public JDBCAdapter createViaDataSource() throws Exception {
98 | PGSimpleDataSource dataSource = new PGSimpleDataSource();
99 | dataSource.setURL(url);
100 | dataSource.setUser(username);
101 | dataSource.setPassword(password);
102 |
103 | return new JDBCAdapter(dataSource);
104 | }
105 | }
106 |
107 | class SQLServerAdapterCreator implements AdapterCreator {
108 | private String url = "jdbc:sqlserver://localhost:1433;databaseName=casbin;";
109 | private String username = "sa";
110 | private String password = "9G3iqmzQDw9zCXII";
111 | private String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
112 |
113 | @Override
114 | public JDBCAdapter create() throws Exception {
115 | return new JDBCAdapter(driver, url, username, password);
116 | }
117 |
118 | @Override
119 | public JDBCAdapter createViaDataSource() throws Exception {
120 | SQLServerDataSource dataSource = new SQLServerDataSource();
121 | dataSource.setURL(url);
122 | dataSource.setUser(username);
123 | dataSource.setPassword(password);
124 |
125 | return new JDBCAdapter(dataSource);
126 | }
127 | }
128 |
129 |
--------------------------------------------------------------------------------
/src/test/java/org/casbin/adapter/JDBCAdapterTestSets.java:
--------------------------------------------------------------------------------
1 | // Copyright 2020 The casbin Authors. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package org.casbin.adapter;
16 |
17 | import org.casbin.jcasbin.main.Enforcer;
18 | import org.casbin.jcasbin.util.Util;
19 |
20 | import java.util.List;
21 |
22 | import static java.util.Arrays.asList;
23 | import static org.junit.Assert.assertEquals;
24 | import static org.junit.Assert.fail;
25 |
26 | // JDBCAdapterTestSets provide a set of test sets.
27 | class JDBCAdapterTestSets {
28 | private static void testEnforce(Enforcer e, String sub, Object obj, String act, boolean res) {
29 | assertEquals(res, e.enforce(sub, obj, act));
30 | }
31 |
32 | public static void testGetPolicy(Enforcer e, List> res) {
33 | List> myRes = e.getPolicy();
34 | Util.logPrint("Policy: " + myRes);
35 |
36 | if (!Util.array2DEquals(res, myRes)) {
37 | fail("Policy: " + myRes + ", supposed to be " + res);
38 | }
39 | }
40 |
41 | public static void testHasPolicy(Enforcer e, List policy, boolean res) {
42 | boolean myRes = e.hasPolicy(policy);
43 | Util.logPrint("Has policy " + Util.arrayToString(policy) + ": " + myRes);
44 |
45 | if (res != myRes) {
46 | fail("Has policy " + Util.arrayToString(policy) + ": " + myRes + ", supposed to be " + res);
47 | }
48 | }
49 |
50 | static void testAdapter(JDBCAdapter a) {
51 | // Because the DB is empty at first,
52 | // so we need to load the policy from the file adapter (.CSV) first.
53 | Enforcer e = new Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv");
54 |
55 | // This is a trick to save the current policy to the DB.
56 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter.
57 | // The current policy means the policy in the jCasbin enforcer (aka in memory).
58 | a.savePolicy(e.getModel());
59 |
60 | // Clear the current policy.
61 | e.clearPolicy();
62 | testGetPolicy(e, asList());
63 |
64 | // Load the policy from DB.
65 | a.loadPolicy(e.getModel());
66 | testGetPolicy(e, asList(
67 | asList("alice", "data1", "read"),
68 | asList("bob", "data2", "write"),
69 | asList("data2_admin", "data2", "read"),
70 | asList("data2_admin", "data2", "write")));
71 |
72 | // Note: you don't need to look at the above code
73 | // if you already have a working DB with policy inside.
74 | e = new Enforcer("examples/rbac_model.conf", a);
75 | testGetPolicy(e, asList(
76 | asList("alice", "data1", "read"),
77 | asList("bob", "data2", "write"),
78 | asList("data2_admin", "data2", "read"),
79 | asList("data2_admin", "data2", "write")));
80 | }
81 |
82 | static void testAddAndRemovePolicy(JDBCAdapter a) {
83 | Enforcer e = new Enforcer("examples/rbac_model.conf", a);
84 | testEnforce(e, "cathy", "data1", "read", false);
85 |
86 | // AutoSave is enabled by default.
87 | // It can be disabled by:
88 | // e.enableAutoSave(false);
89 |
90 | // Because AutoSave is enabled, the policy change not only affects the policy in Casbin enforcer,
91 | // but also affects the policy in the storage.
92 | e.addPolicy("cathy", "data1", "read");
93 | testEnforce(e, "cathy", "data1", "read", true);
94 |
95 | e.addPolicies(new String[][]{{"cathy2", "data1", "read"},{"cathy3", "data1", "read"}});
96 | testEnforce(e, "cathy2", "data1", "read", true);
97 | testEnforce(e, "cathy3", "data1", "read", true);
98 |
99 | // Reload the policy from the storage to see the effect.
100 | e.clearPolicy();
101 | a.loadPolicy(e.getModel());
102 | // The policy has a new rule: {"cathy", "data1", "read"}.
103 | testEnforce(e, "cathy", "data1", "read", true);
104 |
105 | // Remove the added rule.
106 | e.removePolicy("cathy", "data1", "read");
107 | testEnforce(e, "cathy", "data1", "read", false);
108 |
109 | e.removePolicies(new String[][]{{"cathy2", "data1", "read"},{"cathy3", "data1", "read"}});
110 | testEnforce(e, "cathy2", "data1", "read", false);
111 | testEnforce(e, "cathy3", "data1", "read", false);
112 |
113 | // Reload the policy from the storage to see the effect.
114 | e.clearPolicy();
115 | a.loadPolicy(e.getModel());
116 | testEnforce(e, "cathy", "data1", "read", false);
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/src/main/java/org/casbin/adapter/JDBCAdapter.java:
--------------------------------------------------------------------------------
1 | // Copyright 2021 The casbin Authors. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package org.casbin.adapter;
16 |
17 | import dev.failsafe.Failsafe;
18 | import org.casbin.jcasbin.exception.CasbinAdapterException;
19 | import org.casbin.jcasbin.model.Model;
20 | import org.casbin.jcasbin.persist.FilteredAdapter;
21 | import org.casbin.jcasbin.persist.Helper;
22 | import org.casbin.jcasbin.persist.file_adapter.FilteredAdapter.Filter;
23 |
24 | import javax.sql.DataSource;
25 | import java.sql.*;
26 |
27 | /**
28 | * JDBCFilteredAdapter is the JDBC adapter for jCasbin.
29 | * JDBCFilteredAdapter can load policy from JDBC supported database or save policy to it and it supports filtered policies .
30 | *
31 | * @author shy
32 | * @since 2021/01/26
33 | */
34 | public class JDBCAdapter extends JDBCBaseAdapter implements FilteredAdapter {
35 |
36 | private boolean isFiltered = false;
37 |
38 | /**
39 | * JDBCAdapter is the constructor for JDBCAdapter.
40 | *
41 | * @param driver the JDBC driver, like "com.mysql.cj.jdbc.Driver".
42 | * @param url the JDBC URL, like "jdbc:mysql://localhost:3306/casbin".
43 | * @param username the username of the database.
44 | * @param password the password of the database.
45 | */
46 | public JDBCAdapter(String driver, String url, String username, String password) throws Exception {
47 | super(driver, url, username, password);
48 | }
49 |
50 | /**
51 | * The constructor for JDBCAdapter, will not try to create database.
52 | *
53 | * @param dataSource the JDBC DataSource.
54 | */
55 | public JDBCAdapter(DataSource dataSource) throws Exception {
56 | super(dataSource);
57 | }
58 |
59 | /**
60 | * JDBCAdapter is the constructor for JDBCAdapter.
61 | *
62 | * @param driver the JDBC driver, like "com.mysql.cj.jdbc.Driver".
63 | * @param url the JDBC URL, like "jdbc:mysql://localhost:3306/casbin".
64 | * @param username the username of the database.
65 | * @param password the password of the database.
66 | * @param removePolicyFailed whether to throw an exception when delete strategy fails.
67 | * @param tableName the table name of casbin rule.
68 | * @param autoCreateTable whether to create the table automatically.
69 | */
70 | public JDBCAdapter(String driver, String url, String username, String password, boolean removePolicyFailed, String tableName, boolean autoCreateTable) throws Exception {
71 | super(driver, url, username, password, removePolicyFailed, tableName, autoCreateTable);
72 | }
73 |
74 | /**
75 | * JDBCAdapter is the constructor for JDBCAdapter.
76 | *
77 | * @param dataSource the JDBC DataSource.
78 | * @param removePolicyFailed whether to throw an exception when delete strategy fails.
79 | * @param tableName the table name of casbin rule.
80 | * @param autoCreateTable whether to create the table automatically.
81 | */
82 | public JDBCAdapter(DataSource dataSource, boolean removePolicyFailed, String tableName, boolean autoCreateTable) throws Exception {
83 | super(dataSource, removePolicyFailed, tableName, autoCreateTable);
84 | }
85 |
86 | /**
87 | * loadFilteredPolicy loads only policy rules that match the filter.
88 | *
89 | * @param model the model.
90 | * @param filter the filter used to specify which type of policy should be loaded.
91 | * @throws CasbinAdapterException if the file path or the type of the filter is incorrect.
92 | */
93 | @Override
94 | public void loadFilteredPolicy(Model model, Object filter) throws CasbinAdapterException {
95 | if (filter == null) {
96 | loadPolicy(model);
97 | isFiltered = false;
98 | return;
99 | }
100 | if (!(filter instanceof Filter)) {
101 | isFiltered = false;
102 | throw new CasbinAdapterException("Invalid filter type.");
103 | }
104 | try {
105 | loadFilteredPolicyFile(model, (Filter) filter, Helper::loadPolicyLine);
106 | isFiltered = true;
107 | } catch (Exception e) {
108 | e.printStackTrace();
109 | }
110 | }
111 |
112 | /**
113 | * IsFiltered returns true if the loaded policy has been filtered.
114 | *
115 | * @return true if have any filter roles.
116 | */
117 | @Override
118 | public boolean isFiltered() {
119 | return isFiltered;
120 | }
121 |
122 | /**
123 | * loadFilteredPolicyFile loads only policy rules that match the filter from file.
124 | */
125 | private void loadFilteredPolicyFile(Model model, Filter filter, Helper.loadPolicyLineHandler handler) throws CasbinAdapterException {
126 | Failsafe.with(retryPolicy).run(ctx -> {
127 | if (ctx.isRetry()) {
128 | retry(ctx);
129 | }
130 | try (Statement stmt = conn.createStatement();
131 | ResultSet rSet = stmt.executeQuery(renderActualSql("SELECT * FROM casbin_rule"))) {
132 | ResultSetMetaData rData = rSet.getMetaData();
133 | while (rSet.next()) {
134 | CasbinRule line = new CasbinRule();
135 | for (int i = 1; i <= rData.getColumnCount(); i++) {
136 | if (i == 2) {
137 | line.ptype = rSet.getObject(i) == null ? "" : (String) rSet.getObject(i);
138 | } else if (i == 3) {
139 | line.v0 = rSet.getObject(i) == null ? "" : (String) rSet.getObject(i);
140 | } else if (i == 4) {
141 | line.v1 = rSet.getObject(i) == null ? "" : (String) rSet.getObject(i);
142 | } else if (i == 5) {
143 | line.v2 = rSet.getObject(i) == null ? "" : (String) rSet.getObject(i);
144 | } else if (i == 6) {
145 | line.v3 = rSet.getObject(i) == null ? "" : (String) rSet.getObject(i);
146 | } else if (i == 7) {
147 | line.v4 = rSet.getObject(i) == null ? "" : (String) rSet.getObject(i);
148 | } else if (i == 8) {
149 | line.v5 = rSet.getObject(i) == null ? "" : (String) rSet.getObject(i);
150 | }
151 | }
152 | if (filterLine(line, filter)) {
153 | continue;
154 | }
155 | loadPolicyLine(line, model);
156 | }
157 | }
158 | });
159 | }
160 |
161 | /**
162 | * match the line.
163 | */
164 | private boolean filterLine(CasbinRule line, Filter filter) {
165 | if (filter == null) {
166 | return false;
167 | }
168 | String[] filterSlice = null;
169 | switch (line.ptype.trim()) {
170 | case "p":
171 | filterSlice = filter.p;
172 | break;
173 | case "g":
174 | filterSlice = filter.g;
175 | break;
176 | }
177 | if (filterSlice == null) {
178 | filterSlice = new String[]{};
179 | }
180 | return filterWords(line.toStringArray(), filterSlice);
181 | }
182 |
183 | /**
184 | * match the words in the specific line.
185 | */
186 | private boolean filterWords(String[] line, String[] filter) {
187 | boolean skipLine = false;
188 | int i = 0;
189 | for (String s : filter) {
190 | i++;
191 | if (s.length() > 0 && !s.trim().equals(line[i].trim())) {
192 | skipLine = true;
193 | break;
194 | }
195 | }
196 | return skipLine;
197 | }
198 | }
199 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | org.casbin
8 | jdbc-adapter
9 | 2.6.0
10 |
11 | JDBC Adapter for JCasbin
12 | Load policy from JDBC supported database or save policy to it
13 | https://github.com/jcasbin/jdbc-adapter
14 | 2018
15 |
16 |
17 | Github
18 | https://github.com/jcasbin/jdbc-adapter/issues
19 |
20 |
21 |
22 | org.sonatype.oss
23 | oss-parent
24 | 7
25 |
26 |
27 |
28 | The Apache Software License, Version 2.0
29 | https://www.apache.org/licenses/LICENSE-2.0.txt
30 | repo
31 |
32 |
33 |
34 | https://github.com/jcasbin/jdbc-adapter
35 | git@github.com:jcasbin/jdbc-adapter.git
36 | https://github.com/hsluoyz
37 |
38 |
39 |
40 | Yang Luo
41 | hsluoyz@qq.com
42 | https://github.com/hsluoyz
43 |
44 |
45 |
46 |
47 | UTF-8
48 |
49 |
50 |
51 |
52 | ossrh
53 | https://central.sonatype.com
54 |
55 |
56 |
57 |
58 |
59 |
60 | org.apache.maven.plugins
61 | maven-gpg-plugin
62 | 1.5
63 |
64 |
65 | sign-artifacts
66 | verify
67 |
68 | sign
69 |
70 |
71 |
72 |
73 |
74 |
75 | --pinentry-mode
76 | loopback
77 |
78 |
79 |
80 |
81 | org.eluder.coveralls
82 | coveralls-maven-plugin
83 | 4.3.0
84 |
85 |
86 | org.jacoco
87 | jacoco-maven-plugin
88 | 0.7.6.201602180812
89 |
90 |
91 | prepare-agent
92 |
93 | prepare-agent
94 |
95 |
96 |
97 |
98 |
99 |
100 | org.apache.maven.plugins
101 | maven-javadoc-plugin
102 | 2.10.4
103 |
104 | 11
105 | false
106 |
107 | -Xdoclint:none
108 |
109 |
110 | notnull
111 | a
112 | Not null
113 |
114 |
115 | default
116 | a
117 | Default:
118 |
119 |
120 |
121 |
122 |
123 |
124 | attach-javadocs
125 |
126 | jar
127 |
128 |
129 |
130 |
131 |
132 |
133 | org.apache.maven.plugins
134 | maven-source-plugin
135 |
136 |
137 | attach-sources
138 |
139 | jar-no-fork
140 |
141 |
142 |
143 |
144 |
145 |
146 | org.sonatype.central
147 | central-publishing-maven-plugin
148 | 0.5.0
149 | true
150 |
151 | ossrh
152 | true
153 |
154 | true
155 |
156 |
157 |
158 | org.apache.maven.plugins
159 | maven-compiler-plugin
160 |
161 | 1.8
162 | 1.8
163 |
164 |
165 |
166 | org.codehaus.mojo
167 | cobertura-maven-plugin
168 | 2.7
169 |
170 |
171 | html
172 | xml
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 | org.apache.commons
183 | commons-collections4
184 | 4.4
185 |
186 |
187 |
188 | junit
189 | junit
190 | 4.13.2
191 | test
192 |
193 |
194 | org.casbin
195 | jcasbin
196 | 1.85.1
197 |
198 |
199 | com.mysql
200 | mysql-connector-j
201 | 8.3.0
202 | test
203 |
204 |
205 |
206 | com.oracle.database.jdbc
207 | ojdbc6
208 | 11.2.0.4
209 |
210 |
211 |
212 | org.postgresql
213 | postgresql
214 | 42.7.2
215 |
216 |
217 |
218 | com.microsoft.sqlserver
219 | mssql-jdbc
220 | 8.2.2.jre8
221 |
222 |
223 | dev.failsafe
224 | failsafe
225 | 3.2.3
226 |
227 |
228 |
229 |
230 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/src/test/java/org/casbin/adapter/JDBCAdapterTest.java:
--------------------------------------------------------------------------------
1 | // Copyright 2018 The casbin Authors. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package org.casbin.adapter;
16 |
17 | import org.casbin.jcasbin.exception.CasbinAdapterException;
18 | import org.casbin.jcasbin.main.Enforcer;
19 | import org.casbin.jcasbin.persist.file_adapter.FilteredAdapter;
20 | import org.junit.Assert;
21 | import org.junit.Test;
22 |
23 | import java.sql.SQLException;
24 | import java.util.ArrayList;
25 | import java.util.Arrays;
26 | import java.util.List;
27 |
28 | import static java.util.Arrays.asList;
29 | import static org.casbin.adapter.JDBCAdapterTestSets.*;
30 | import static org.junit.Assert.fail;
31 |
32 | public class JDBCAdapterTest {
33 | private void testAdapter(List adapters) {
34 | for (JDBCAdapter a : adapters) {
35 | JDBCAdapterTestSets.testAdapter(a);
36 | JDBCAdapterTestSets.testAddAndRemovePolicy(a);
37 | }
38 | }
39 |
40 | @Test
41 | public void testMySQLAdapter() {
42 | List adapters = new ArrayList<>();
43 |
44 | try {
45 | adapters.add(new MySQLAdapterCreator().create());
46 | adapters.add(new MySQLAdapterCreator().createViaDataSource());
47 | } catch (Exception e) {
48 | e.printStackTrace();
49 | fail(e.getMessage());
50 | return;
51 | }
52 |
53 | testAdapter(adapters);
54 |
55 | adapters.forEach(adapter -> {
56 | try {
57 | adapter.close();
58 | } catch (SQLException sqlException) {
59 | sqlException.printStackTrace();
60 | }
61 | });
62 | }
63 |
64 | @Test
65 | public void testPgAdapter() {
66 | List adapters = new ArrayList<>();
67 |
68 | try {
69 | adapters.add(new PgAdapterCreator().create());
70 | adapters.add(new PgAdapterCreator().createViaDataSource());
71 | } catch (Exception e) {
72 | e.printStackTrace();
73 | fail(e.getMessage());
74 | return;
75 | }
76 |
77 | testAdapter(adapters);
78 |
79 | adapters.forEach(adapter -> {
80 | try {
81 | adapter.close();
82 | } catch (SQLException sqlException) {
83 | sqlException.printStackTrace();
84 | }
85 | });
86 | }
87 |
88 | @Test
89 | public void testSQLServerAdapter() {
90 | List adapters = new ArrayList<>();
91 |
92 | try {
93 | adapters.add(new SQLServerAdapterCreator().create());
94 | adapters.add(new SQLServerAdapterCreator().createViaDataSource());
95 | } catch (Exception e) {
96 | e.printStackTrace();
97 | fail(e.getMessage());
98 | return;
99 | }
100 |
101 | testAdapter(adapters);
102 |
103 | adapters.forEach(adapter -> {
104 | try {
105 | adapter.close();
106 | } catch (SQLException sqlException) {
107 | sqlException.printStackTrace();
108 | }
109 | });
110 | }
111 |
112 | @Test
113 | public void testLoadFilteredPolicyEmptyFilter() throws Exception {
114 | JDBCAdapter adapter = new MySQLAdapterCreator().create();
115 |
116 | // Because the DB is empty at first,
117 | // so we need to load the policy from the file adapter (.CSV) first.
118 | Enforcer e = new Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv");
119 |
120 | // This is a trick to save the current policy to the DB.
121 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter.
122 | // The current policy means the policy in the jCasbin enforcer (aka in memory).
123 | adapter.savePolicy(e.getModel());
124 |
125 | // Clear the current policy.
126 | e.clearPolicy();
127 | testGetPolicy(e, asList());
128 |
129 | // Load the policy from DB.
130 | adapter.loadFilteredPolicy(e.getModel(), null);
131 | testGetPolicy(e, asList(
132 | asList("alice", "data1", "read"),
133 | asList("bob", "data2", "write"),
134 | asList("data2_admin", "data2", "read"),
135 | asList("data2_admin", "data2", "write")));
136 |
137 | // Note: you don't need to look at the above code
138 | // if you already have a working DB with policy inside.
139 | e = new Enforcer("examples/rbac_model.conf", adapter);
140 | testGetPolicy(e, asList(
141 | asList("alice", "data1", "read"),
142 | asList("bob", "data2", "write"),
143 | asList("data2_admin", "data2", "read"),
144 | asList("data2_admin", "data2", "write")));
145 |
146 | adapter.close();
147 | }
148 |
149 | @Test
150 | public void testLoadFilteredPolicyInvalidFilter() throws Exception {
151 | JDBCAdapter adapter = new MySQLAdapterCreator().create();
152 | // Because the DB is empty at first,
153 | // so we need to load the policy from the file adapter (.CSV) first.
154 | Enforcer e = new Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv");
155 |
156 | // This is a trick to save the current policy to the DB.
157 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter.
158 | // The current policy means the policy in the jCasbin enforcer (aka in memory).
159 | adapter.savePolicy(e.getModel());
160 |
161 | // Clear the current policy.
162 | e.clearPolicy();
163 | testGetPolicy(e, asList());
164 |
165 | // Load the policy from DB.
166 | Assert.assertThrows(CasbinAdapterException.class, () -> adapter.loadFilteredPolicy(e.getModel(), new Object()));
167 |
168 | adapter.close();
169 | }
170 |
171 | @Test
172 | public void testLoadFilteredPolicy() throws Exception {
173 | JDBCAdapter adapter = new MySQLAdapterCreator().create();
174 |
175 | FilteredAdapter.Filter f = new FilteredAdapter.Filter();
176 | f.g = new String[]{
177 | "", "", "domain1"
178 | };
179 | f.p = new String[]{
180 | "", "domain1"
181 | };
182 |
183 | // Because the DB is empty at first,
184 | // so we need to load the policy from the file adapter (.CSV) first.
185 | Enforcer e = new Enforcer("examples/rbac_with_domains_model.conf", "examples/rbac_with_domains_policy.csv");
186 | // This is a trick to save the current policy to the DB.
187 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter.
188 | // The current policy means the policy in the jCasbin enforcer (aka in memory).
189 | adapter.savePolicy(e.getModel());
190 |
191 | testHasPolicy(e, asList("admin", "domain1", "data1", "read"), true);
192 | testHasPolicy(e, asList("admin", "domain2", "data2", "read"), true);
193 |
194 | // Clear the current policy.
195 | e.clearPolicy();
196 | testGetPolicy(e, asList());
197 |
198 | // Load the policy from DB.
199 | adapter.loadFilteredPolicy(e.getModel(), f);
200 |
201 | testHasPolicy(e, asList("admin", "domain1", "data1", "read"), true);
202 | testHasPolicy(e, asList("admin", "domain2", "data2", "read"), false);
203 |
204 | adapter.close();
205 | }
206 |
207 | @Test
208 | public void testConstructorParams() throws Exception {
209 | JDBCAdapter adapter = new MySQLAdapterCreator().create(true, "table_name_test", true);
210 | JDBCAdapter adapterViaDataSource = new MySQLAdapterCreator().createViaDataSource(true, "table_name_test", true);
211 | Assert.assertThrows(CasbinAdapterException.class, () -> adapter.removePolicy("p", "p", Arrays.asList("cathy", "data1", "read")));
212 | Assert.assertThrows(CasbinAdapterException.class, () -> adapterViaDataSource.removePolicy("p", "p", Arrays.asList("cathy", "data1", "read")));
213 | adapter.close();
214 | adapterViaDataSource.close();
215 | }
216 |
217 | @Test
218 | public void testRemovePolicy() throws Exception {
219 | JDBCAdapter adapter = new MySQLAdapterCreator().create();
220 |
221 | // Because the DB is empty at first,
222 | // so we need to load the policy from the file adapter (.CSV) first.
223 | Enforcer e = new Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv");
224 |
225 | // This is a trick to save the current policy to the DB.
226 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter.
227 | // The current policy means the policy in the jCasbin enforcer (aka in memory).
228 | adapter.savePolicy(e.getModel());
229 |
230 | e.clearPolicy();
231 | testGetPolicy(e, asList());
232 |
233 | e = new Enforcer("examples/rbac_model.conf", adapter);
234 | testGetPolicy(e, asList(
235 | asList("alice", "data1", "read"),
236 | asList("bob", "data2", "write"),
237 | asList("data2_admin", "data2", "read"),
238 | asList("data2_admin", "data2", "write")));
239 |
240 | adapter.removePolicy("p", "p", Arrays.asList("alice", "data1", "read"));
241 | e = new Enforcer("examples/rbac_model.conf", adapter);
242 | testGetPolicy(e, asList(
243 | asList("bob", "data2", "write"),
244 | asList("data2_admin", "data2", "read"),
245 | asList("data2_admin", "data2", "write")));
246 |
247 | adapter.removePolicy("p", "p", Arrays.asList("bob", "data2"));
248 | e = new Enforcer("examples/rbac_model.conf", adapter);
249 | testGetPolicy(e, asList(
250 | asList("bob", "data2", "write"),
251 | asList("data2_admin", "data2", "read"),
252 | asList("data2_admin", "data2", "write")));
253 |
254 | adapter.removePolicy("p", "p", Arrays.asList("bob", "data2", "write"));
255 | e = new Enforcer("examples/rbac_model.conf", adapter);
256 | testGetPolicy(e, asList(
257 | asList("data2_admin", "data2", "read"),
258 | asList("data2_admin", "data2", "write")));
259 | }
260 |
261 | @Test
262 | public void testUpdatePolicy() throws Exception {
263 | JDBCAdapter adapter = new MySQLAdapterCreator().create();
264 |
265 | // Because the DB is empty at first,
266 | // so we need to load the policy from the file adapter (.CSV) first.
267 | Enforcer e = new Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv");
268 |
269 | // This is a trick to save the current policy to the DB.
270 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter.
271 | // The current policy means the policy in the jCasbin enforcer (aka in memory).
272 | adapter.savePolicy(e.getModel());
273 |
274 | e.clearPolicy();
275 | testGetPolicy(e, asList());
276 |
277 | e = new Enforcer("examples/rbac_model.conf", adapter);
278 | testGetPolicy(e, asList(
279 | asList("alice", "data1", "read"),
280 | asList("bob", "data2", "write"),
281 | asList("data2_admin", "data2", "read"),
282 | asList("data2_admin", "data2", "write")));
283 |
284 | adapter.updatePolicy("p", "p", asList("bob", "data2", "write"), asList("alice", "data2", "read"));
285 | e = new Enforcer("examples/rbac_model.conf", adapter);
286 | testGetPolicy(e, asList(
287 | asList("alice", "data1", "read"),
288 | asList("data2_admin", "data2", "read"),
289 | asList("data2_admin", "data2", "write"),
290 | asList("alice", "data2", "read")));
291 |
292 | }
293 | }
294 |
--------------------------------------------------------------------------------
/src/main/java/org/casbin/adapter/JDBCBaseAdapter.java:
--------------------------------------------------------------------------------
1 | // Copyright 2018 The casbin Authors. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package org.casbin.adapter;
16 |
17 | import dev.failsafe.ExecutionContext;
18 | import dev.failsafe.Failsafe;
19 | import dev.failsafe.RetryPolicy;
20 | import org.apache.commons.collections4.CollectionUtils;
21 | import org.casbin.jcasbin.exception.CasbinAdapterException;
22 | import org.casbin.jcasbin.model.Assertion;
23 | import org.casbin.jcasbin.model.Model;
24 | import org.casbin.jcasbin.persist.Adapter;
25 | import org.casbin.jcasbin.persist.BatchAdapter;
26 | import org.casbin.jcasbin.persist.Helper;
27 | import org.casbin.jcasbin.persist.UpdatableAdapter;
28 |
29 | import javax.sql.DataSource;
30 | import java.sql.*;
31 | import java.time.Duration;
32 | import java.util.*;
33 |
34 | class CasbinRule {
35 | int id; //Fields reserved for compatibility with other adapters, and the primary key is automatically incremented.
36 | String ptype;
37 | String v0;
38 | String v1;
39 | String v2;
40 | String v3;
41 | String v4;
42 | String v5;
43 |
44 | public String[] toStringArray() {
45 | return new String[]{ptype, v0, v1, v2, v3, v4, v5};
46 | }
47 | }
48 |
49 | /**
50 | * JDBCAdapter is the JDBC adapter for jCasbin.
51 | * It can load policy from JDBC supported database or save policy to it.
52 | */
53 | abstract class JDBCBaseAdapter implements Adapter, BatchAdapter, UpdatableAdapter {
54 | protected static final String DEFAULT_TABLE_NAME = "casbin_rule";
55 | protected static final boolean DEFAULT_REMOVE_POLICY_FAILED = false;
56 | protected static final boolean DEFAULT_AUTO_CREATE_TABLE = true;
57 | protected static final int _DEFAULT_CONNECTION_TRIES = 3;
58 | protected DataSource dataSource;
59 | protected String tableName;
60 | protected boolean removePolicyFailed;
61 | private final int batchSize = 1000;
62 | protected Connection conn;
63 | protected RetryPolicy