Skip to content

Commit

Permalink
Merge pull request #11 from basakest/UpdatableDatabaseAdapter
Browse files Browse the repository at this point in the history
feat: support Casbin UpdatableAdapter interface
  • Loading branch information
leeqvip authored Mar 23, 2021
2 parents 96e2eb7 + 60848b4 commit acf902c
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/Adapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Casbin\Persist\Adapters\Filter;
use Casbin\Exceptions\InvalidFilterTypeException;
use Casbin\Persist\BatchAdapter;
use Casbin\Persist\UpdatableAdapter;
use Closure;
use Throwable;

Expand All @@ -18,7 +19,7 @@
*
* @author [email protected]
*/
class Adapter implements AdapterContract, FilteredAdapter, BatchAdapter
class Adapter implements AdapterContract, FilteredAdapter, BatchAdapter, UpdatableAdapter
{
use AdapterHelper;

Expand Down Expand Up @@ -274,4 +275,36 @@ public function loadFilteredPolicy(Model $model, $filter): void
}
$this->filtered = true;
}

/**
* Updates a policy rule from storage.
* This is part of the Auto-Save feature.
*
* @param string $sec
* @param string $ptype
* @param string[] $oldRule
* @param string[] $newPolicy
*/
public function updatePolicy(string $sec, string $ptype, array $oldRule, array $newPolicy): void
{
$where['ptype'] = $ptype;
$condition[] = 'ptype = :ptype';

foreach($oldRule as $key => $value) {
$placeholder = "w" . strval($key);
$where['w' . strval($key)] = $value;
$condition[] = 'v' . strval($key) . ' = :' . $placeholder;
}

$update = [];
foreach($newPolicy as $key => $value) {
$placeholder = "s" . strval($key);
$updateValue["$placeholder"] = $value;
$update[] = 'v' . strval($key) . ' = :' . $placeholder;
}

$sql = "UPDATE {$this->casbinRuleTableName} SET " . implode(', ', $update) . " WHERE " . implode(' AND ', $condition);

$this->connection->execute($sql, array_merge($updateValue, $where));
}
}
28 changes: 28 additions & 0 deletions tests/AdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,34 @@ public function testRemoveFilteredPolicy()
$this->assertFalse($e->enforce('alice', 'data2', 'write'));
}

public function testUpdatePolicy()
{
$e = $this->getEnforcer();
$this->assertEquals([
['alice', 'data1', 'read'],
['bob', 'data2', 'write'],
['data2_admin', 'data2', 'read'],
['data2_admin', 'data2', 'write'],
], $e->getPolicy());

$e->updatePolicy(
['alice', 'data1', 'read'],
['alice', 'data1', 'write']
);

$e->updatePolicy(
['bob', 'data2', 'write'],
['bob', 'data2', 'read']
);

$this->assertEquals([
['alice', 'data1', 'write'],
['bob', 'data2', 'read'],
['data2_admin', 'data2', 'read'],
['data2_admin', 'data2', 'write'],
], $e->getPolicy());
}

protected function env($key, $default = null)
{
$value = getenv($key);
Expand Down

0 comments on commit acf902c

Please sign in to comment.