Java源码示例:org.casbin.jcasbin.model.Model

示例1
/**
 * 从存储加载所有策略规则
 * 加载时会合并重复数据
 *
 * @param model the model.
 */
@Transactional(readOnly = true)
@Override
public void loadPolicy(Model model) {
    List<CasbinRule> casbinRules = jdbcTemplate.query(getLoadPolicySql(), BeanPropertyRowMapper.newInstance(CasbinRule.class));
    // 按ptype对策略进行分组,并合并重复数据
    Map<String, List<ArrayList<String>>> policies = casbinRules.parallelStream().distinct()
            .map(CasbinRule::toPolicy)
            .collect(Collectors.toMap(x -> x.get(0), y -> {
                ArrayList<ArrayList<String>> lists = new ArrayList<>();
                // 去除list第一项策略类型
                y.remove(0);
                lists.add(y);
                return lists;
            }, (oldValue, newValue) -> {
                oldValue.addAll(newValue);
                return oldValue;
            }));
    // 对分组的策略进行加载
    policies.keySet().forEach(
            k -> model.model.get(k.substring(0, 1)).get(k).policy.addAll(policies.get(k))
    );
}
 
示例2
/**
 * loadFilteredPolicy loads only policy rules that match the filter.
 * @param model the model.
 * @param filter the filter used to specify which type of policy should be loaded.
 * @throws CasbinAdapterException if the file path or the type of the filter is incorrect.
 */
public void loadFilteredPolicy(Model model, Object filter) throws CasbinAdapterException {
    if ("".equals(filepath)) {
        throw new CasbinAdapterException("Invalid file path, file path cannot be empty.");
    }
    if (filter == null) {
        adapter.loadPolicy(model);
        isFiltered = false;
        return;
    }
    if (!(filter instanceof Filter)) {
        throw new CasbinAdapterException("Invalid filter type.");
    }
    try {
        loadFilteredPolicyFile(model, (Filter) filter, Helper::loadPolicyLine);
        isFiltered = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
示例3
/**
 * savePolicy saves all policy rules to the storage.
 */
@Override
public void savePolicy(Model model) {
    if (byteArrayInputStream != null && readOnly) {
        throw new CasbinAdapterException("Policy file can not write, because use inputStream is readOnly");
    }
    if (filePath == null || "".equals(filePath) || !new File(filePath).exists()) {
        throw new CasbinPolicyFileNotFoundException("invalid file path: " + filePath);
    }

    List<String> policy = new ArrayList<>();
    policy.addAll(getModelPolicy(model, "p"));
    policy.addAll(getModelPolicy(model, "g"));

    savePolicyFile(String.join("\n", policy));
}
 
示例4
@Test
public void testRBACModelInMemory() {
    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("g", "g", "_, _");
    m.addDef("e", "e", "some(where (p.eft == allow))");
    m.addDef("m", "m", "g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act");

    Enforcer e = new Enforcer(m);

    e.addPermissionForUser("alice", "data1", "read");
    e.addPermissionForUser("bob", "data2", "write");
    e.addPermissionForUser("data2_admin", "data2", "read");
    e.addPermissionForUser("data2_admin", "data2", "write");
    e.addRoleForUser("alice", "data2_admin");

    testEnforce(e, "alice", "data1", "read", true);
    testEnforce(e, "alice", "data1", "write", false);
    testEnforce(e, "alice", "data2", "read", true);
    testEnforce(e, "alice", "data2", "write", true);
    testEnforce(e, "bob", "data1", "read", false);
    testEnforce(e, "bob", "data1", "write", false);
    testEnforce(e, "bob", "data2", "read", false);
    testEnforce(e, "bob", "data2", "write", true);
}
 
示例5
@Test
public void testNotUsedRBACModelInMemory() {
    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("g", "g", "_, _");
    m.addDef("e", "e", "some(where (p.eft == allow))");
    m.addDef("m", "m", "g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act");

    Enforcer e = new Enforcer(m);

    e.addPermissionForUser("alice", "data1", "read");
    e.addPermissionForUser("bob", "data2", "write");

    testEnforce(e, "alice", "data1", "read", true);
    testEnforce(e, "alice", "data1", "write", false);
    testEnforce(e, "alice", "data2", "read", false);
    testEnforce(e, "alice", "data2", "write", false);
    testEnforce(e, "bob", "data1", "read", false);
    testEnforce(e, "bob", "data1", "write", false);
    testEnforce(e, "bob", "data2", "read", false);
    testEnforce(e, "bob", "data2", "write", true);
}
 
示例6
@Test
public void testInitEmpty() {
    Enforcer e = new Enforcer();

    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("e", "e", "some(where (p.eft == allow))");
    m.addDef("m", "m", "r.sub == p.sub && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act)");

    Adapter a = new FileAdapter("examples/keymatch_policy.csv");

    e.setModel(m);
    e.setAdapter(a);
    e.loadPolicy();

    testEnforce(e, "alice", "/alice_data/resource1", "GET", true);
}
 
示例7
@Test
public void testInitEmptyByInputStream() {
    Enforcer e = new Enforcer();

    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("e", "e", "some(where (p.eft == allow))");
    m.addDef("m", "m", "r.sub == p.sub && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act)");

    try (FileInputStream fis = new FileInputStream("examples/keymatch_policy.csv")) {
        Adapter a = new FileAdapter(fis);

        e.setModel(m);
        e.setAdapter(a);
        e.loadPolicy();

        testEnforce(e, "alice", "/alice_data/resource1", "GET", true);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}
 
示例8
@Test
public void testRBACModelInMemory() {
    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("g", "g", "_, _");
    m.addDef("e", "e", "some(where (p.eft == allow))");
    m.addDef("m", "m", "g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act");

    Enforcer e = new SyncedEnforcer(m);

    e.addPermissionForUser("alice", "data1", "read");
    e.addPermissionForUser("bob", "data2", "write");
    e.addPermissionForUser("data2_admin", "data2", "read");
    e.addPermissionForUser("data2_admin", "data2", "write");
    e.addRoleForUser("alice", "data2_admin");

    testEnforce(e, "alice", "data1", "read", true);
    testEnforce(e, "alice", "data1", "write", false);
    testEnforce(e, "alice", "data2", "read", true);
    testEnforce(e, "alice", "data2", "write", true);
    testEnforce(e, "bob", "data1", "read", false);
    testEnforce(e, "bob", "data1", "write", false);
    testEnforce(e, "bob", "data2", "read", false);
    testEnforce(e, "bob", "data2", "write", true);
}
 
示例9
@Test
public void testNotUsedRBACModelInMemory() {
    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("g", "g", "_, _");
    m.addDef("e", "e", "some(where (p.eft == allow))");
    m.addDef("m", "m", "g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act");

    Enforcer e = new SyncedEnforcer(m);

    e.addPermissionForUser("alice", "data1", "read");
    e.addPermissionForUser("bob", "data2", "write");

    testEnforce(e, "alice", "data1", "read", true);
    testEnforce(e, "alice", "data1", "write", false);
    testEnforce(e, "alice", "data2", "read", false);
    testEnforce(e, "alice", "data2", "write", false);
    testEnforce(e, "bob", "data1", "read", false);
    testEnforce(e, "bob", "data1", "write", false);
    testEnforce(e, "bob", "data2", "read", false);
    testEnforce(e, "bob", "data2", "write", true);
}
 
示例10
@Test
public void testInitEmpty() {
    Enforcer e = new SyncedEnforcer();

    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("e", "e", "some(where (p.eft == allow))");
    m.addDef("m", "m", "r.sub == p.sub && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act)");

    Adapter a = new FileAdapter("examples/keymatch_policy.csv");

    e.setModel(m);
    e.setAdapter(a);
    e.loadPolicy();

    testEnforce(e, "alice", "/alice_data/resource1", "GET", true);
}
 
示例11
@Test
public void testInitEmptyByInputStream() {
    Enforcer e = new SyncedEnforcer();

    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("e", "e", "some(where (p.eft == allow))");
    m.addDef("m", "m", "r.sub == p.sub && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act)");

    try (FileInputStream fis = new FileInputStream("examples/keymatch_policy.csv")) {
        Adapter a = new FileAdapter(fis);

        e.setModel(m);
        e.setAdapter(a);
        e.loadPolicy();

        testEnforce(e, "alice", "/alice_data/resource1", "GET", true);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}
 
示例12
@SuppressFBWarnings(value={"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD","URLCONNECTION_SSRF_FD"})
public AuthorizationService () {
    Util.enableLog = false;
    
    if (MangooUtils.resourceExists(Default.MODEL_CONF.toString()) && MangooUtils.resourceExists(Default.POLICY_CSV.toString())) {
        Model model = new Model();
        try {
            model.loadModelFromText(IOUtils.toString(Resources.getResource(Default.MODEL_CONF.toString()).openStream(), Default.ENCODING.toString()));
            this.enforcer = new Enforcer(model, new AuthorizationAdapter());
            this.enforcer.enableLog(false);
        } catch (IOException e) {
            LOG.error("Failed to load model configuration for authorization handling", e);
        }
    } else {
        this.enforcer = new Enforcer();
        this.enforcer.enableLog(false);   
    }
}
 
示例13
/**
 * 将model转换为CasbinRule
 * 转换过程将会合并重复数据
 */
public static List<CasbinRule> transformToCasbinRule(Model model) {
    Set<CasbinRule> casbinRules = new HashSet<>();
    model.model.values().forEach(x -> x.values().forEach(y -> y.policy.forEach(z -> {
        if (z.isEmpty()) return;
        int size = z.size();
        CasbinRule casbinRule = new CasbinRule();
        casbinRule.setPtype(y.key);
        casbinRule.setV0(z.get(0));
        if (size >= 2) {
            casbinRule.setV1(z.get(1));
        }
        if (size >= 3) {
            casbinRule.setV2(z.get(2));
        }
        if (size >= 4) {
            casbinRule.setV3(z.get(3));
        }
        if (size >= 5) {
            casbinRule.setV4(z.get(4));
        }
        if (size >= 6) {
            casbinRule.setV5(z.get(5));
        }
        casbinRules.add(casbinRule);
    })));
    return new ArrayList<>(casbinRules);
}
 
示例14
/**
 * 将所有策略规则保存到存储
 * 保存时会合并重复数据
 *
 * @param model the model.
 */
@Transactional
@Override
public void savePolicy(Model model) {
    deleteTableContent();
    List<CasbinRule> casbinRules = CasbinRule.transformToCasbinRule(model);
    int[] rows = jdbcTemplate.batchUpdate(
            INSERT_POLICY_SQL,
            new BatchPreparedStatementSetter() {

                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ps.setString(1, casbinRules.get(i).getPtype());
                    ps.setString(2, casbinRules.get(i).getV0());
                    ps.setString(3, casbinRules.get(i).getV1());
                    ps.setString(4, casbinRules.get(i).getV2());
                    ps.setString(5, casbinRules.get(i).getV3());
                    ps.setString(6, casbinRules.get(i).getV4());
                    ps.setString(7, casbinRules.get(i).getV5());
                }

                @Override
                public int getBatchSize() {
                    return casbinRules.size();
                }
            }
    );
    int insertRows = 0;
    for (int row : rows) {
        insertRows += row;
    }
    if (insertRows != casbinRules.size()) {
        throw new CasbinAdapterException(String.format("Add policy error, add %d rows, expect %d rows", insertRows, casbinRules.size()));
    }

}
 
示例15
/**
 * loadFilteredPolicyFile loads only policy rules that match the filter from file.
 */
private void loadFilteredPolicyFile(Model model, Filter filter, Helper.loadPolicyLineHandler<String, Model> handler) throws CasbinAdapterException {
    try (FileInputStream fis = new FileInputStream(filepath)) {
        List<String> lines = IOUtils.readLines(fis, Charset.forName("UTF-8"));
        for (String line : lines) {
            line = line.trim();
            if (filterLine(line, filter)) continue;
            handler.accept(line, model);
        }
    } catch (IOException e) {
        throw new CasbinAdapterException("Load policy file error", e.getCause());
    }
}
 
示例16
/**
 * loadPolicy loads all policy rules from the storage.
 */
@Override
public void loadPolicy(Model model) {
    if (filePath != null && !"".equals(filePath)) {
        try (FileInputStream fis = new FileInputStream(filePath)) {
            loadPolicyData(model, Helper::loadPolicyLine, fis);
        } catch (IOException e) {
            throw new CasbinAdapterException("Load policy file error", e.getCause());
        }
    }
    if (byteArrayInputStream != null) {
        loadPolicyData(model, Helper::loadPolicyLine, byteArrayInputStream);
    }
}
 
示例17
private List<String> getModelPolicy(Model model, String ptype) {
    List<String> policy = new ArrayList<>();
    model.model.get(ptype).forEach((k, v) -> {
        List<String> p = v.policy.parallelStream().map(x -> k + ", " + Util.arrayToString(x)).collect(Collectors.toList());
        policy.addAll(p);
    });
    return policy;
}
 
示例18
private void loadPolicyData(Model model, Helper.loadPolicyLineHandler<String, Model> handler, InputStream inputStream) {
    try {
        List<String> lines = IOUtils.readLines(inputStream, Charset.forName("UTF-8"));
        lines.forEach(x -> handler.accept(x, model));
    } catch (IOException e) {
        e.printStackTrace();
        throw new CasbinAdapterException("Policy load error");
    }
}
 
示例19
public static void loadPolicyLine(String line, Model model) {
    if (line.equals("")) {
        return;
    }

    if (line.charAt(0) == '#') {
        return;
    }

    String[] tokens = splitCommaDelimited(line);

    String key = tokens[0];
    String sec = key.substring(0, 1);
    model.model.get(sec).get(key).policy.add(Arrays.asList(Arrays.copyOfRange(tokens, 1, tokens.length)));
}
 
示例20
/**
 * newModel creates a model.
 *
 * @param text the model text.
 * @return the model.
 */
public static Model newModel(String text) {
    Model m = new Model();

    m.loadModelFromText(text);

    return m;
}
 
示例21
/**
 * newModel creates a model.
 *
 * @param modelPath the path of the model file.
 * @param unused unused parameter, just for differentiating with
 *               newModel(String text).
 * @return the model.
 */
public static Model newModel(String modelPath, String unused) {
    Model m = new Model();

    if (!modelPath.equals("")) {
        m.loadModel(modelPath);
    }

    return m;
}
 
示例22
/**
 * Enforcer initializes an enforcer with a model and a database adapter.
 *
 * @param m the model.
 * @param adapter the adapter.
 */
public Enforcer(Model m, Adapter adapter) {
    this.adapter = adapter;
    this.watcher = null;

    model = m;
    model.printModel();
    fm = FunctionMap.loadFunctionMap();

    initialize();

    if (this.adapter != null) {
        loadPolicy();
    }
}
 
示例23
@Test
public void testKeyMatchModelInMemoryDeny() {
    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("e", "e", "!some(where (p.eft == deny))");
    m.addDef("m", "m", "r.sub == p.sub && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act)");

    Adapter a = new FileAdapter("examples/keymatch_policy.csv");

    Enforcer e = new Enforcer(m, a);

    testEnforce(e, "alice", "/alice_data/resource2", "POST", true);
}
 
示例24
@Test
public void testRBACModelInMemoryIndeterminate() {
    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("g", "g", "_, _");
    m.addDef("e", "e", "some(where (p.eft == allow))");
    m.addDef("m", "m", "g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act");

    Enforcer e = new Enforcer(m);

    e.addPermissionForUser("alice", "data1", "invalid");

    testEnforce(e, "alice", "data1", "read", false);
}
 
示例25
@Test
public void testRBACModelInMemory2() {
    String text =
  "[request_definition]\n"
        + "r = sub, obj, act\n"
        + "\n"
        + "[policy_definition]\n"
        + "p = sub, obj, act\n"
        + "\n"
        + "[role_definition]\n"
        + "g = _, _\n"
        + "\n"
        + "[policy_effect]\n"
        + "e = some(where (p.eft == allow))\n"
        + "\n"
        + "[matchers]\n"
        + "m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act\n";

    Model m = newModel(text);
    // The above is the same as:
    // Model m = newModel();
    // m.loadModelFromText(text);

    Enforcer e = new Enforcer(m);

    e.addPermissionForUser("alice", "data1", "read");
    e.addPermissionForUser("bob", "data2", "write");
    e.addPermissionForUser("data2_admin", "data2", "read");
    e.addPermissionForUser("data2_admin", "data2", "write");
    e.addRoleForUser("alice", "data2_admin");

    testEnforce(e, "alice", "data1", "read", true);
    testEnforce(e, "alice", "data1", "write", false);
    testEnforce(e, "alice", "data2", "read", true);
    testEnforce(e, "alice", "data2", "write", true);
    testEnforce(e, "bob", "data1", "read", false);
    testEnforce(e, "bob", "data1", "write", false);
    testEnforce(e, "bob", "data2", "read", false);
    testEnforce(e, "bob", "data2", "write", true);
}
 
示例26
@Test
public void testKeyMatchModelInMemoryDeny() {
    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("e", "e", "!some(where (p.eft == deny))");
    m.addDef("m", "m", "r.sub == p.sub && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act)");

    Adapter a = new FileAdapter("examples/keymatch_policy.csv");

    Enforcer e = new SyncedEnforcer(m, a);

    testEnforce(e, "alice", "/alice_data/resource2", "POST", true);
}
 
示例27
@Test
public void testRBACModelInMemoryIndeterminate() {
    Model m = newModel();
    m.addDef("r", "r", "sub, obj, act");
    m.addDef("p", "p", "sub, obj, act");
    m.addDef("g", "g", "_, _");
    m.addDef("e", "e", "some(where (p.eft == allow))");
    m.addDef("m", "m", "g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act");

    Enforcer e = new SyncedEnforcer(m);

    e.addPermissionForUser("alice", "data1", "invalid");

    testEnforce(e, "alice", "data1", "read", false);
}
 
示例28
@Test
public void testRBACModelInMemory2() {
    String text =
  "[request_definition]\n"
        + "r = sub, obj, act\n"
        + "\n"
        + "[policy_definition]\n"
        + "p = sub, obj, act\n"
        + "\n"
        + "[role_definition]\n"
        + "g = _, _\n"
        + "\n"
        + "[policy_effect]\n"
        + "e = some(where (p.eft == allow))\n"
        + "\n"
        + "[matchers]\n"
        + "m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act\n";

    Model m = newModel(text);
    // The above is the same as:
    // Model m = newModel();
    // m.loadModelFromText(text);

    Enforcer e = new SyncedEnforcer(m);

    e.addPermissionForUser("alice", "data1", "read");
    e.addPermissionForUser("bob", "data2", "write");
    e.addPermissionForUser("data2_admin", "data2", "read");
    e.addPermissionForUser("data2_admin", "data2", "write");
    e.addRoleForUser("alice", "data2_admin");

    testEnforce(e, "alice", "data1", "read", true);
    testEnforce(e, "alice", "data1", "write", false);
    testEnforce(e, "alice", "data2", "read", true);
    testEnforce(e, "alice", "data2", "write", true);
    testEnforce(e, "bob", "data1", "read", false);
    testEnforce(e, "bob", "data1", "write", false);
    testEnforce(e, "bob", "data2", "read", false);
    testEnforce(e, "bob", "data2", "write", true);
}
 
示例29
private void loadPolicyFile(Model model, Helper.loadPolicyLineHandler<String, Model> handler) {
    try {
        IOUtils.readLines(Resources.getResource(Default.POLICY_CSV.toString()).openStream(), Default.ENCODING.toString()).forEach(line -> handler.accept(line, model));
    } catch (IOException e) {
        LOG.error("Failed to load policy configuration for authorization handling", e);
    }        
}
 
示例30
/**
 * loadPolicy loads all policy rules from the storage.
 */
@Override
public void loadPolicy(Model model) {
    adapter.loadPolicy(model);
    isFiltered = false;
}