PHP code example of casbin / casbin-client

1. Go to this page and download the library: Download casbin/casbin-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

casbin / casbin-client example snippets




use Proto\CasbinClient;
use Proto\NewEnforcerRequest;
use Proto\NewAdapterRequest;
use Proto\EnforceRequest;

$client = new CasbinClient('localhost:50051', [
    'credentials' => Grpc\ChannelCredentials::createInsecure(),
]);

$newAdapterRequest = new NewAdapterRequest();
$newAdapterRequest->setDriverName('file');
$newAdapterRequest->setConnectString('path/to/rbac_policy.csv');

list($newAdapterReply, $status) = $client->NewAdapter($newAdapterRequest)->wait();

if (0 !== $status->code) {
    throw new \Exception($status->details, $status->code);
}
	
$adapterHandle = $newAdapterReply->getHandler();

$newEnforcerRequest = new NewEnforcerRequest();
$newEnforcerRequest->setModelText(<<<EOT
[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
EOT
        );
$newEnforcerRequest->setAdapterHandle($adapterHandle);

list($newEnforcerReply, $status) = $client->NewEnforcer($newEnforcerRequest)->wait();

if (0 !== $status->code) {
    throw new \Exception($status->details, $status->code);
}

$enforceRequest = new EnforceRequest();
$enforceRequest->setEnforcerHandler($newEnforcerReply->getHandler());
$enforceRequest->setParams(['alice', 'data1', 'read']);

list($enforceReply, $status) = $client->Enforce($enforceRequest)->wait();

if (0 !== $status->code) {
    throw new \Exception($status->details, $status->code);
}

if ($enforceReply->getRes()) {
    // permit alice to read data1
} else {
    // deny the request, show an error
}