Giter Site home page Giter Site logo

php-casbin / php-casbin Goto Github PK

View Code? Open in Web Editor NEW
1.2K 52.0 124.0 366 KB

An authorization library that supports access control models like ACL, RBAC, ABAC in PHP .

Home Page: https://casbin.org

License: Apache License 2.0

PHP 100.00%
rbac permission php access-control authorization acl abac middlewares roles framework

php-casbin's Introduction

PHP-Casbin

Scrutinizer Code Quality Default Coverage Status Latest Stable Version Total Downloads License Gitter

Documentation | Tutorials | Extensions

Breaking News: Laravel-authz is now available, an authorization library for the Laravel framework.

PHP-Casbin is a powerful and efficient open-source access control library for PHP projects. It provides support for enforcing authorization based on various access control models.

All the languages supported by Casbin:

golang java nodejs php
Casbin jCasbin node-Casbin PHP-Casbin
production-ready production-ready production-ready production-ready
python dotnet c++ rust
PyCasbin Casbin.NET Casbin-CPP Casbin-RS
production-ready production-ready beta-test production-ready

Installation

Require this package in the composer.json of your project. This will download the package:

composer require casbin/casbin

Get started

  1. New a Casbin enforcer with a model file and a policy file:
require_once './vendor/autoload.php';

use Casbin\Enforcer;

$e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
  1. Add an enforcement hook into your code right before the access happens:
$sub = "alice"; // the user that wants to access a resource.
$obj = "data1"; // the resource that is going to be accessed.
$act = "read"; // the operation that the user performs on the resource.

if ($e->enforce($sub, $obj, $act) === true) {
    // permit alice to read data1
} else {
    // deny the request, show an error
}

Table of contents

Supported models

  1. ACL (Access Control List)
  2. ACL with superuser
  3. ACL without users: especially useful for systems that don't have authentication or user log-ins.
  4. ACL without resources: some scenarios may target for a type of resources instead of an individual resource by using permissions like write-article, read-log. It doesn't control the access to a specific article or log.
  5. RBAC (Role-Based Access Control)
  6. RBAC with resource roles: both users and resources can have roles (or groups) at the same time.
  7. RBAC with domains/tenants: users can have different role sets for different domains/tenants.
  8. ABAC (Attribute-Based Access Control): syntax sugar like resource.Owner can be used to get the attribute for a resource.
  9. RESTful: supports paths like /res/*, /res/:id and HTTP methods like GET, POST, PUT, DELETE.
  10. Deny-override: both allow and deny authorizations are supported, deny overrides the allow.
  11. Priority: the policy rules can be prioritized like firewall rules.

How it works?

In php-casbin, an access control model is abstracted into a CONF file based on the PERM metamodel (Policy, Effect, Request, Matchers). So switching or upgrading the authorization mechanism for a project is just as simple as modifying a configuration. You can customize your own access control model by combining the available models. For example, you can get RBAC roles and ABAC attributes together inside one model and share one set of policy rules.

The most basic and simplest model in php-casbin is ACL. ACL's model CONF is:

# Request definition
[request_definition]
r = sub, obj, act

# Policy definition
[policy_definition]
p = sub, obj, act

# Policy effect
[policy_effect]
e = some(where (p.eft == allow))

# Matchers
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act

An example policy for ACL model is like:

p, alice, data1, read
p, bob, data2, write

It means:

  • alice can read data1
  • bob can write data2

Features

What php-casbin does:

  1. enforce the policy in the classic {subject, object, action} form or a customized form as you defined, both allow and deny authorizations are supported.
  2. handle the storage of the access control model and its policy.
  3. manage the role-user mappings and role-role mappings (aka role hierarchy in RBAC).
  4. support built-in superuser like root or administrator. A superuser can do anything without explict permissions.
  5. multiple built-in operators to support the rule matching. For example, keyMatch can map a resource key /foo/bar to the pattern /foo*.

What php-casbin does NOT do:

  1. authentication (aka verify username and password when a user logs in)
  2. manage the list of users or roles. I believe it's more convenient for the project itself to manage these entities. Users usually have their passwords, and php-casbin is not designed as a password container. However, php-casbin stores the user-role mapping for the RBAC scenario.

Documentation

https://casbin.org/docs/en/overview

Online editor

You can also use the online editor (http://casbin.org/editor/) to write your php-casbin model and policy in your web browser. It provides functionality such as syntax highlighting and code completion, just like an IDE for a programming language.

Tutorials

https://casbin.org/docs/tutorials

Policy management

php-casbin provides two sets of APIs to manage permissions:

  • Management API: the primitive API that provides full support for php-casbin policy management.
  • RBAC API: a more friendly API for RBAC. This API is a subset of Management API. The RBAC users could use this API to simplify the code.

model editor

policy editor

Policy persistence

https://casbin.org/docs/en/adapters

Role manager

https://casbin.org/docs/en/role-managers

Examples

Model Model file Policy file
ACL basic_model.conf basic_policy.csv
ACL with superuser basic_model_with_root.conf basic_policy.csv
ACL without users basic_model_without_users.conf basic_policy_without_users.csv
ACL without resources basic_model_without_resources.conf basic_policy_without_resources.csv
RBAC rbac_model.conf rbac_policy.csv
RBAC with resource roles rbac_model_with_resource_roles.conf rbac_policy_with_resource_roles.csv
RBAC with domains/tenants rbac_model_with_domains.conf rbac_policy_with_domains.csv
ABAC abac_model.conf N/A
RESTful keymatch_model.conf keymatch_policy.csv
Deny-override rbac_model_with_deny.conf rbac_policy_with_deny.csv
Priority priority_model.conf priority_policy.csv

Middlewares

Authz middlewares for web frameworks: https://casbin.org/docs/en/middlewares

Our adopters

https://casbin.org/docs/en/adopters

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

This project is licensed under the Apache 2.0 license.

Contact

If you have any issues or feature requests, please contact us. PR is welcomed.

php-casbin's People

Contributors

acgrid avatar basakest avatar gopherj avatar hsluoyz avatar javi-p-nt avatar kang8 avatar kyle-mccarthy avatar leeqvip avatar lorenzomar avatar mavimo avatar ra1nyd4nc3r avatar smallsung avatar sukui avatar techqiang avatar uax avatar zxilly avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-casbin's Issues

Installation issue

I am trying to download the packages by running the following command:
composer require casbin/casbin
but i got following while running it:

./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package casbin/casbin No version set (parsed as 1.0.0) is satisfiable by casbin/casbin[No version set (parsed as 1.0.0)] but these conflict with your requirements or minimum-stability.


Installation failed, reverting ./composer.json to its original content.

Can anyone let me know what is the problem?

How to add user while using RBAC policy?

Hi,
I've gone through the documentation page of casbin.[How to create rbac_model.conf and
rbac_policy.csv]
Now suppose i've one page called index.php in my website, so what i want to do is only student with certain user-id[email-id] can only access that page[or can do any action(read or write) on that page].
So i can enforce the rbac policy in the index.php file with following code:

require_once './vendor/autoload.php';
use Casbin\Enforcer;
$e = new Enforcer("rbac_model.conf", "rbac_policy.csv");

My rbac_model.conf file will be like this:

[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act

and rbac_policy file will look like this [suppose i know the email-id of student '[email protected]']

p, [email protected], index.php, write

Is the above things are fine?

Now what i want to do is i don't know what is every users email-id while enforcing one single .csv file.
So what i want to do is get the user's email-id from database in php file and to send that email-id to .csv file.
Is there any way to send that extracted email-id from php file to that .csv file through Enforcer function or some other way.
Please let me know.

hasPermissionForUser

image

Enforcer::hasPermissionForUser('1', 'project', 'add') 返回的是 false 操作不对吗

Use C++ to build php-casbin

@techoner can we use our casbin-cpp project to build the casbin PHP extension. I think it will greatly increase our performance. The cpp-casbin builds into dll file for windows and php also use dll file in windows for extension, so I will with very few modification we can achieve this migration. We can use PHP-CPP for this task.

在laravel 7.10版本中

Call to undefined method stdClass::buildRoleLinks()

public function test()
    {
        $enforcer = new Enforcer(base_path('model.conf'), $this->getAdapter());

        $sub = "alice"; // the user that wants to access a resource.
        $obj = "data1"; // the resource that is going to be accessed.
        $act = "read"; // the operation that the user performs on the resource.
        $enforcer->addRoleForUser('alice', 'admin');
    }

    public function getAdapter()
    {
        $config = [
            'type' => 'mysql',
            'hostname' => env('DB_HOST'),
            'database' => env('DB_DATABASE'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
        ];
        return Adapter::newAdapter($config);
    }

还有一个问题,看文档的话,好像没有告知如何将 policy 持久化到 mysql中,如何建表呢

dose it support sub domain wildcard (*) ?

If I have 5 domains.
I want define to :

  • domain/1 : This domain has child domain 2 and 3.
  • domain/1/2
  • domain/1/3
  • domain/4 : This domain has child domain 5
  • domain/4/5

I want domain/1 admin has full access permision , also has full acess permission on domain/1/* , domain/4 admin has full access on domain/4/*.

so policy maybe

p, admin, domain/:domainId, data, read
p, admin, domain/:domainId, data, write
p, admin, domain/:domainId/:domainId, data, read
p, admin, domain/:domainId/:domainId, data, write

g, alice, admin, domain/1
g, alice, admin, domain/1/*
g, bob, admin, domain/1/2
g, mary, admin, domain/1/3

alice has full access permission on domain/1/2 and domain/1/3 , bob only has access on domain/1/2

Is it possibile ?

rbac_with_domain_pattern_model can not work with domain *

Hi
I am trying examples/rbac_with_domain_pattern_model.conf
I load rbac_with_domain_pattern_policy.csv

I use latest version(2.3.0)

My code

<?php require_once './vendor/autoload.php';

use Casbin\Enforcer;

$e = new Enforcer("config/casbin_model.conf", "config/casbin_policy.csv");

$sub = "alice"; // the user that wants to access a resource.
$obj = "data1"; // the resource that is going to be accessed.
$dom = "domain1";
$act = "read"; // the operation that the user performs on the resource.

var_dump($e->enforce($sub, $dom, $obj, $act));

it dump false
When I change $sub = "bob" , $dom t="domain2" , $obj="data2" , it dump true.
Why alice no perssion ? does this version support wildcard(*) ?

Path error in the example code

Hi, in the example, the following code:

require_once './vendor/autoload.php';
use Casbin\Enforcer;

actually should be:

use Casbin/Enforcer;

Is this backslash: \ wrong here?

An $expression variable is initialized with wrong type which results in fatal error

$expression = new ExpressionLanguage();

A variable $expression is initialized as ExpressionLanguage, and then used as function argument where Expression is required. In most cases it is redefined by value returned from $expressionLanguage->parse(...) method, but in one case it is used unchanged:
$result = $expressionLanguage->evaluate($expression, $parameters);

It results in a fatal error with message:

Object of class Symfony\Component\ExpressionLanguage\ExpressionLanguage could not be converted to string

Storing comments with policies

As the authorization gets more complex, it would be nice to add comments/description to i.e. roles. Would it be possible to have $m->addPolicy('g', 'g', $rule, 'this role has a comment'); ? Thanks!

Unable to get a property on a non-object

I am trying to implement the casbin but I have a 500 error.
Just throw me a simple message, and there is no way to know what causes

         $adapter =  new Adapter($config["db"]);
        $e = new Enforcer("config/autoload/model.conf", $adapter);


        $sub = "alice"; // the user that wants to access a resource.
        $obj = "data1"; // the resource that is going to be accessed.
        $act = "read"; // the operation that the user performs on the resource.

        print_r($e->enforce($sub, $obj, $act)); // <-----generate error 
      
      

Message Error

{
  "error": {
    "debugMessage": "Unable to get a property on a non-object.",
    "message": "Internal server error",
    "extensions": {
      "category": "internal"
    }
  }
}

what does `g(r.sub, p.sub, r.dom)` mean?

I look through all documents, no details about g(r.sub, p.sub, r.dom).

[request_definition]
r = sub, dom, obj, act

[policy_definition]
p = sub, dom, obj, act

[role_definition]
g = _, _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && r.obj == p.obj && r.act == p.act

Getting all domains that user is in

With the model

[request_definition]
r = sub, dom, obj, act

[policy_definition]
p = sub, dom, obj, act

[role_definition]
g = _, _, _
g2 = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub, r.dom) && g2(r.dom, p.dom) && keyMatch2(r.obj, p.obj) && r.act == p.act

I'd like to get a function getDomains('user1', '/a/object/*', 'read') that

  • finds the roles attached to user1
  • returns domains, where the role/user has read access to an object

Thanks in advance

Int type results in multiple entries

Lets assume this code:

if (!$m->hasPolicy('g', 'g2', $rule)) {
    $m->addPolicy('g', 'g2', $rule);  
    $e->savePolicy();
}

If $rule = [ '0', '1' ];, everything works as expected, but if $rule = [ 0, 1 ];, the $m->hasPolicy always evaluates to false. I'm not sure, why php doesn't throw an exception, because

public function hasPolicy(string $sec, string $ptype, array $rule): bool
requires string and should fail on an int due to declare(strict_types=1); on
declare(strict_types=1);

Can anyone reproduce this?

getImplicitUsersForPermission maybe have a bug

I understand the function of this method through comments

 /**
     * Gets implicit users for a permission.
     * For example:
     * p, admin, data1, read
     * p, bob, data1, read
     * g, alice, admin
     * getImplicitUsersForPermission("data1", "read") will get: ["alice", "bob"].
     * Note: only users will be returned, roles (2nd arg in "g") will be excluded.
     *
     * @param string ...$permission
     *
     * @return array
     * @throws CasbinException
     */
   public function getImplicitUsersForPermission(string ...$permission): array
    {
        $subjects = $this->getAllSubjects();
        $roles = $this->getAllRoles();     // this function just return role value. not have  role  name.  I think it should return [ 'alice', 'admin']
        $users = array_diff($subjects, $roles);  //  I think you want    ['admin','bob']  ^ ['alice', 'admin']   = ['bob','alice']   Actually  just return  ['bob']
// array_diff  Returns an array containing all the entries from array that are not present in any of the other arrays. 

        // I think it should be like this
        //$roles = array_reduce($this->getGroupingPolicy(), 'array_merge', array());
        //$users = array_diff($subjects, $roles) + array_diff($roles, $subjects) ;

        $res = [];
        foreach ($users as $user) {
            $req = $permission;
            array_unshift($req, $user);
            $allowed = $this->enforce(...$req);

            if ($allowed) {
                $res[] = $user;
            }
        }

        return $res;
    }

ABAC with php-casbin

I read through the casbin main project information on abac but don't really understand how to work with abac. Lets say I have this data:

INSERT INTO `article` (`id`, `author`, `name`, `state`, `data`) VALUES
(1,	'[email protected]',	'My first article', 'published', `article text goes here`),
(2,	'[email protected]',	'The case for ABAC', 'unpublished', `Abac is cool`);

and that I want to

  • deny users from reading unpublished articles,
  • but allow users with role 'reviewer' to read them.

How would I note that? Like this?

p, role::reviewer, article/*.state == published, read
g, user:peter, role::reviewer

How would I pass the article.state to the enforce function?

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Missing package.json file.

A package.json file at the root of your project is required to release on npm.

Please follow the npm guideline to create a valid package.json file.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Is there an example of FilteredAdapter or implement document ?

I am trying yii-permission , and post an issue.

php-casbin/yii-permission#6

Becasue every request will query all data from casbin_rule, If i have many domain and user , the result will be very large.

I think FilteredAdapter may fix the problem , but I can not find any example for php version.
Anyone who has implemented it for mysql( or any database ) ? please provide it , thanks.

Broken Links

Links are broken under Policy management section of readme file

New 2.3.0 release ?

Hi,

In the issue #44 you added the support of the scaling ABAC model with the eval() function (which is awesome btw) but it is not included in the latest release 2.2.0 since it got merged after. So I switched from 2.2.0 to dev-master in my project to be able to use that model but it'd be safer to have a release including it.

No rush, but what's your strategy to create a new release / when do you plan to create 2.3.0 ?

Thank you very much,
Clement

Upgrading a casbin model

Hi,

is there a recommended way to upgrade models? Let's say we want to change from RBAC to RBAC with domains, also with an updated matcher. Obviously we have to update the conf file and assign domains to existing permissions.

Thanks, in advance

Policy not matching

Hi guys,

version: casbin/casbin v3.3.0

here the conf and the policy I am trying to use:

[request_definition]
r = sub, dom, act

[policy_definition]
p = sub, dom, act, eft

[role_definition]
g = _, _, _

[policy_effect]
e = some(where (p.eft == allow)) && !some(where (p.eft == deny))

[matchers]
m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && r.act == p.act
p, admin_domain1, domain1, read, allow
p, admin_domain1, domain1, write, allow
p, admin_domain2, domain2, read, allow
p, admin_domain2, domain2, write, allow
g, alice, admin_domain1, domain1
g, bob, admin_domain2, domain2

Now, when I want to test:

        $this->assertTrue($enforcer->enforce('alice', 'domain1', 'read')); // <--- pass
        $this->assertTrue($enforcer->enforce('alice', 'domain1', 'write')); // <--- pass

        $this->assertFalse($enforcer->enforce('alice', 'domain2', 'read')); // <--- fail
        $this->assertFalse($enforcer->enforce('alice', 'domain2', 'write')); // <--- fail

        $this->assertFalse($enforcer->enforce('bob', 'domain1', 'read')); // <--- fail
        $this->assertFalse($enforcer->enforce('bob', 'domain1', 'write')); // <--- fail

        $this->assertTrue($enforcer->enforce('bob', 'domain2', 'read')); // <--- pass
        $this->assertTrue($enforcer->enforce('bob', 'domain2', 'write')); // <--- pass

What is wrong with my workflow? Since alice is not related at all with domain2, the assert should return false, but here, it returns true.

I tried also with the following matcher:
m = r.sub == p.sub && r.dom == p.dom && r.act == p.act
but same result

Thank you for your help.

RBAC with domains: functions return wrong results

Using the model

[request_definition]
r = sub, dom, obj, act

[policy_definition]
p = sub, dom, obj, act

[role_definition]
g = _, _, _
g2 = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub, r.dom) && g2(r.dom, p.dom) && keyMatch2(r.obj, p.obj) && r.act == p.act

I defined roles, domain relationships and users:

           // lets create administrative and usage roles
            $role_dom_obj_act[] = [ 'admin', '0', '*', 'r' ];
            $role_dom_obj_act[] = [ 'admin', '0', '*', 'c' ];
            $role_dom_obj_act[] = [ 'admin', '0', '*', 'u' ];
            $role_dom_obj_act[] = [ 'admin', '0', '*', 'd' ];
            $role_dom_obj_act[] = [ 'usage', '0', '/ui/worklog/*', 'r' ];
            $role_dom_obj_act[] = [ 'usage', '0', '/ui/account/my_account', 'r' ];
            $role_dom_obj_act[] = [ 'usage', '0', '/ui/stor', 'r' ];
            $role_dom_obj_act[] = [ 'usage', '0', '/ui/worklog', 'r' ];
            
            foreach ($role_dom_obj_act as $rule) {
                if (!$m->hasPolicy('p', 'p', $rule)) {
                    $m->addPolicy('p', 'p', $rule);  
                    $e->savePolicy();
                }
            }
    
            // lets assign the admin role to user 1 on domain 0
            $authid_role_dom[] = [ '1', 'admin', '0' ];
            $authid_role_dom[] = [ '2', 'usage', '0' ];    

            foreach ($authid_role_dom as $rule) {
                if (!$m->hasPolicy('g', 'g', $rule)) {
                    $m->addPolicy('g', 'g', $rule);  
                    $e->savePolicy();
                }
            }

            // lets have domain 0 = main domain, domain 1 = subdomain
            $dom_dom[] = [ '0', '1' ];
            foreach ($dom_dom as $rule) {
                if (!$m->hasPolicy('g', 'g2', $rule)) {
                    $m->addPolicy('g', 'g2', $rule);  
                    $e->savePolicy();
                }
            }

i tried to work with some of the functions, but for example,

$e->getRolesForUser('2'); returns an empty array where [ 'usage' ] would be expected, or $e->getFilteredPolicy(2, '/ui/stor'); returns an array with 25 same items. Basically most of the functions don't behave as expected. Any idea why?

"grouping policy elements do not meet role definition" cannot create roles with domains php-casbin

My model definition is this

[request_definition]
r = sub, dom, obj, act

[policy_definition]
p = sub, dom, obj, act

[role_definition]
g = _, _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && r.obj == p.obj && r.act == p.act

The standard domain tenant rbac model definition but trying to create or even load the casbin fails with this error
"grouping policy elements do not meet role definition" but if the role params are two it loads but does not register my domains

problem with configuration

Hi guys,

I'm struggling with brand new project using Casbin(it's my first time :) ), I've set up the editor online with this configuration for models:

 [request_definition]
 r = sub, dom, obj, act
 
 [policy_definition]
 p = sub, dom, obj, act
 
 [role_definition]
 g = _, _, _
 
 [policy_effect]
 e = some(where (p.eft == allow))
 
 [matchers]
 m = (g(r.sub, p.sub, r.dom) && r.obj == p.obj &&  r.act == p.act && p.sub != r.sub) || (r.obj == p.obj &&  r.act == p.act && p.sub == r.sub && r.dom == p.dom) 
 

and this is my policy file :

p,role_admin,p1,A,read
p,role_admin,p1,A,write

p,role_L,p1,A,read

p,role_C,p1,A,reads
p,role_C,p1,A,write

p,role_T,p1,A,read
p,role_T,p1,A,write

p, carlo,p3,A,read

g,ale,role_admin,*
g,mario,role_admin,*
g,rosy,role_C,p1
g,jessica,role_C,p1
g,camilla,role_T,p1
g,vincenzo,role_L,p1

the tests that I've made are these :

vincenzo, p1, A, read //true
vincenzo, p1, A, write //false

ale, p8, A, read //true
ale, p14, A, write //true

mario, pALL, A, read //true
mario, pALL, A, write //true

mario, p1, A, read //true
mario, p1, A, write //true


carlo, p2, A, read //false
carlo, p3, A, read //true

under custom config :

> (function() {
>   return {
>     /**
>      * Here is custom functions for Casbin.
>      * Currently, there are built-in globMatch, keyMatch, keyMatch2, keyMatch3, keyMatch4, regexMatch, ipMatch.
>      */
>     functions: {},
>     /**
>      * The value comes from config.functions, Casbin will not use this configuration if the value is undefined.
>      * example:
>      * matchingForGFunction: 'globMatch'
>      * matchingDomainForGFunction: 'keyMatch'
>      */
>     matchingForGFunction: 'keyMatch',
>     matchingDomainForGFunction: 'keyMatch',
>     
>   };
> })();

what we want is the possibility to set authorization for multiple domains in one row (actually we use the '*' character to specify multiple domains but the best option for us is to build a hierarchy of domains. Is it possible?)
and for what we have seen on online editor it works well, anyway if we put this configuration in brand new php project with casbin and prepare a test page with this code:

<php?
require_once './vendor/autoload.php';

use Casbin\Enforcer;

$e = new Enforcer(__DIR__ . "\\casbin_model.conf", __DIR__ . "\\policy.csv");

//test.csv contains the same testas the online editor part.
$res = file_get_contents('./test.csv', true);

$rows = explode("\r\n", $res);

foreach ($rows as $row) {
    if ($row == "")
        echo "//ignore";
    else {
        $params = explode(',', $row);
        $res = $e->enforce($params[0], $params[1], $params[2], $params[3]);
        echo $res;
    }
}

with this composer.json

{
  "name": "vendor_name/casbin",
  "require": {
    "casbin/casbin": "v2.4.0"
  }
}

I got all false as result.

what have I done wrong?

I think that the problem is that I've not passed the specific configuration for keyMatch function but sincerely i don't know how to configure that.

can someone help us please?

Adding a g2 policy

Hi, I'm implementing RBAC with domains/tenants and resource roles like this

[request_definition]
r = sub, dom, obj, act

[policy_definition]
p = sub, dom, obj, act

[role_definition]
g = _, _, _
g2 = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub, r.dom) && g2(r.dom, p.dom) && keyMatch2(r.obj, p.obj) && r.act == p.act

To test things out, I did a simple

$model = __ROOT__ . '/glued/Core/Includes/Casbin/default.model';
$adapter = __ROOT__ . '/private/cache/casbin.csv';
$e = new Enforcer($model, $adapter);
$m = $e->getModel();

// add subject permission
$rule = [ 'sub', 'domain', 'obj', 'read' ];
if (!$m->hasPolicy('p', 'p', $rule)) {
    $m->addPolicy('p', 'p', $rule);  
    $e->savePolicy();
}

// assign user to role & domain
$rule = [ 'user', 'role', 'domain' ];
if (!$m->hasPolicy('g', 'g', $rule)) {
    $m->addPolicy('g', 'g', $rule);  
    $e->savePolicy();
}

// assign domain relationships
$rule = [ 'domain', 'subdomain' ];
if (!$m->hasPolicy('g2', 'g2', $rule)) {
    $m->addPolicy('g2', 'g2', $rule);  
    $e->savePolicy();
}

An warning is raised on $m->addPolicy('g2', 'g2', $rule); (Creating default object from empty value). I don't see what I'm missing. Any tips please?

AddNamedPolicies() not add authorization rules to the current named policy

I have rules in array, E.g.:
$rules = [ ["editor", "/admin/dashboard/*", "GET"], ["editor", "/admin/users/edit*", "GET"] ];

Even though the function from ManagementApi $e->addPolicies($rules) returns True, does not add any rules.

For completion only:
If I use E.g. $e->addPolicy("editor", "/admin/dashboard/*", "GET"), the function returns True and the rule is added properly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.