Skip to content

Commit

Permalink
增加了多套配置
Browse files Browse the repository at this point in the history
* feat:  增加了多套配置,可以使用client指定使用那套。 php-casbin#8
* refactor: 去掉了在框架初始化的时候就注入监听,改为按需初始化 php-casbin#6
* fix: 去掉了Laravel的缓存,保持和TP一样 php-casbin#7
* refactor:  调整了一些LaravelAdapter里用法。

已知问题:
* 测试待补充
* 调整未测试(主要因为着急,本身项目里已造了轮子,所以没拿回去测试)
  • Loading branch information
lyt8384 committed Feb 22, 2023
1 parent dac242a commit 109354d
Show file tree
Hide file tree
Showing 8 changed files with 140 additions and 143 deletions.
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,23 @@ if (Permission::enforce("eve", "articles", "edit")) {
}
```

多套配置
```php
$permission = Permission::client("other_conf")
// adds permissions to a user
$permission->addPermissionForUser('eve', 'articles', 'read');
// adds a role for a user.
$permission->addRoleForUser('eve', 'writer');
// adds permissions to a rule
$permission->addPolicy('writer', 'articles','edit');

if ($permission->enforce("eve", "articles", "edit")) {
echo '恭喜你!通过权限认证';
} else {
echo '对不起,您没有该资源访问权限';
}
```

更多 `API` 参考 [Casbin API](https://casbin.org/docs/en/management-api)

## 感谢
Expand Down Expand Up @@ -140,4 +157,4 @@ if (is_null(static::$_manager)) {
}
```
耦合太高,不建议这么搞,更多了解:https://www.workerman.net/doc/webman/di.html
</details>
</details>
6 changes: 3 additions & 3 deletions src/Adapter/DatabaseAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ class DatabaseAdapter implements Adapter, UpdatableAdapter, BatchAdapter, Filter
/**
* the DatabaseAdapter constructor.
*
* @param RuleModel $model
* @param string|null $driver
*/
public function __construct(RuleModel $model)
public function __construct(?string $driver = null)
{
$this->model = $model;
$this->model = new DatabaseAdapter($driver);
}

/**
Expand Down
140 changes: 73 additions & 67 deletions src/Adapter/LaravelDatabaseAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
use Casbin\Persist\Adapters\Filter;
use Casbin\Exceptions\InvalidFilterTypeException;
use Casbin\WebmanPermission\Model\LaravelRuleModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Throwable;

Expand All @@ -45,11 +47,12 @@ class LaravelDatabaseAdapter implements Adapter, UpdatableAdapter, BatchAdapter,

/**
* LaravelDatabaseAdapter constructor.
* @param LaravelRuleModel $model
*
* @param string|null $driver
*/
public function __construct(LaravelRuleModel $model)
public function __construct(?string $driver = null)
{
$this->model = $model;
$this->model = new LaravelRuleModel([],$driver);
}

/**
Expand Down Expand Up @@ -84,9 +87,9 @@ public function savePolicyLine(string $ptype, array $rule)
{
$col['ptype'] = $ptype;
foreach ($rule as $key => $value) {
$col['v' . strval($key) . ''] = $value;
$col['v' . $key] = $value;
}
$this->model->create($col);
$this->model->updateOrCreate($col);
}

/**
Expand All @@ -96,7 +99,7 @@ public function savePolicyLine(string $ptype, array $rule)
*/
public function loadPolicy(Model $model): void
{
$rows = $this->model->getAllFromCache();
$rows = $this->model->select(['ptype', 'v0', 'v1', 'v2', 'v3', 'v4', 'v5'])->get()->toArray();;
foreach ($rows as $row) {
$this->loadPolicyArray($this->filterRule($row), $model);
}
Expand Down Expand Up @@ -145,21 +148,13 @@ public function addPolicy(string $sec, string $ptype, array $rule): void
*/
public function addPolicies(string $sec, string $ptype, array $rules): void
{
$cols = [];
$i = 0;

foreach ($rules as $rule) {
$temp['ptype'] = $ptype;
$temp['created_at'] = date("Y-m-d h:m:i");
$temp['updated_at'] = $temp['created_at'];
$temp = ['ptype' => $ptype];
foreach ($rule as $key => $value) {
$temp['v' . strval($key)] = $value;
$temp['v' . $key] = $value;
}
$cols[$i++] = $temp ?? [];
$temp = [];
$this->model->updateOrCreate($temp);
}
$this->model->insert($cols);
LaravelRuleModel::fireModelEvent('saved');
}

/**
Expand All @@ -173,10 +168,12 @@ public function removePolicy(string $sec, string $ptype, array $rule): void
{
$instance = $this->model->where('ptype', $ptype);
foreach ($rule as $key => $value) {
$instance->where('v' . strval($key), $value);
$instance->where('v' . $key, $value);
}
$data = $instance->get();
foreach ($data as $item) {
$item->delete();
}
$instance->delete();
LaravelRuleModel::fireModelEvent('deleted');
}

/**
Expand All @@ -189,25 +186,13 @@ public function removePolicy(string $sec, string $ptype, array $rule): void
*/
public function _removeFilteredPolicy(string $sec, string $ptype, int $fieldIndex, ?string ...$fieldValues): array
{
$count = 0;
$removedRules = [];
$data = $this->getCollection($ptype, $fieldIndex, $fieldValues);

$instance = $this->model->where('ptype', $ptype);
foreach (range(0, 5) as $value) {
if ($fieldIndex <= $value && $value < $fieldIndex + count($fieldValues)) {
if ('' != $fieldValues[$value - $fieldIndex]) {
$instance->where('v' . strval($value), $fieldValues[$value - $fieldIndex]);
}
}
}

foreach ($instance->select() as $model) {
$item = $model->hidden(['id', 'ptype'])->toArray();
$item = $this->filterRule($item);
foreach ($data as $model) {
$item = $model->hidden(['id', 'ptype'])->toArray();
$item = $this->filterRule($item);
$removedRules[] = $item;
if ($model->cache('tauthz')->delete()) {
++$count;
}
}

return $removedRules;
Expand Down Expand Up @@ -241,22 +226,10 @@ public function removePolicies(string $sec, string $ptype, array $rules): void
*/
public function removeFilteredPolicy(string $sec, string $ptype, int $fieldIndex, string ...$fieldValues): void
{
$instance = $this->model->where('ptype', $ptype);
foreach (range(0, 5) as $value) {
if ($fieldIndex <= $value && $value < $fieldIndex + count($fieldValues)) {
if ('' != $fieldValues[$value - $fieldIndex]) {
$instance->where('v' . strval($value), $fieldValues[$value - $fieldIndex]);
}
}
}

$oldP = $instance->get()->makeHidden(['created_at','updated_at', 'id', 'ptype'])->toArray();
foreach ($oldP as &$item) {
$item = $this->filterRule($item);
$removedRules[] = $item;
$data = $this->getCollection($ptype, $fieldIndex, $fieldValues);
foreach ($data as $item) {
$item->delete();
}
$instance->delete();
LaravelRuleModel::fireModelEvent('deleted');
}

/**
Expand All @@ -272,7 +245,7 @@ public function updatePolicy(string $sec, string $ptype, array $oldRule, array $
{
$instance = $this->model->where('ptype', $ptype);
foreach ($oldRule as $key => $value) {
$instance->where('v' . strval($key), $value);
$instance->where('v' . $key, $value);
}
$instance = $instance->first();

Expand All @@ -281,8 +254,8 @@ public function updatePolicy(string $sec, string $ptype, array $oldRule, array $
$update['v' . $key] = $value;
}

$instance->update($update);
LaravelRuleModel::fireModelEvent('saved');
$instance->fill($update);
$instance->save();
}

/**
Expand Down Expand Up @@ -316,7 +289,7 @@ public function updatePolicies(string $sec, string $ptype, array $oldRules, arra
public function updateFilteredPolicies(string $sec, string $ptype, array $newPolicies, int $fieldIndex, string ...$fieldValues): array
{
$oldRules = [];
\Illuminate\Support\Facades\DB::transaction(function () use ($sec, $ptype, $fieldIndex, $fieldValues, $newPolicies, &$oldRules) {
DB::transaction(function () use ($sec, $ptype, $fieldIndex, $fieldValues, $newPolicies, &$oldRules) {
$oldRules = $this->_removeFilteredPolicy($sec, $ptype, $fieldIndex, ...$fieldValues);
$this->addPolicies($sec, $ptype, $newPolicies);
});
Expand Down Expand Up @@ -346,34 +319,67 @@ public function setFiltered(bool $filtered): void
/**
* Loads only policy rules that match the filter.
*
* @param Model $model
* @param mixed $filter
* @param Model $model
* @param mixed $filter
*
* @throws InvalidFilterTypeException
*/
public function loadFilteredPolicy(Model $model, $filter): void
{
$instance = $this->model;
if (is_string($filter)) {
$instance = $instance->whereRaw($filter);
} elseif ($filter instanceof Filter) {
$instance->whereRaw($filter);
}
elseif ($filter instanceof Filter) {
$where = [];
foreach ($filter->p as $k => $v) {
$where[$v] = $filter->g[$k];
$instance = $instance->where($v, $filter->g[$k]);
}
} elseif ($filter instanceof \Closure) {
$instance->where($where);
}
elseif ($filter instanceof Closure) {
$instance = $instance->where($filter);
} else {
}
else {
throw new InvalidFilterTypeException('invalid filter type');
}
$rows = $instance->get()->makeHidden(['created_at','updated_at', 'id'])->toArray();
$rows = $instance->get()->makeHidden(['created_at', 'updated_at', 'id'])->toArray();
if ($rows) {
foreach ($rows as $row) {
$row = array_filter($row, function($value) { return !is_null($value) && $value !== ''; });
$line = implode(', ', array_filter($row, function ($val) {
return '' != $val && !is_null($val);
}));
$row = array_filter($row, function ($value) {
return !is_null($value) && $value !== '';
});
$line = implode(
', ',
array_filter($row, function ($val) {
return '' != $val && !is_null($val);
})
);
$this->loadPolicyLine(trim($line), $model);
}
}
$this->setFiltered(true);
}

/**
* @param string $ptype
* @param int $fieldIndex
* @param array $fieldValues
*
* @return Builder[]|Collection
*/
protected function getCollection(string $ptype, int $fieldIndex, array $fieldValues) {
$where = [
'ptype' => $ptype,
];
foreach (range(0, 5) as $value) {
if ($fieldIndex <= $value && $value < $fieldIndex + count($fieldValues)) {
if ('' != $fieldValues[$value - $fieldIndex]) {
$where['v' . $value] = $fieldValues[$value - $fieldIndex];
}
}
}

return $this->model->where($where)->get();
}
}
43 changes: 9 additions & 34 deletions src/Model/LaravelRuleModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@

namespace Casbin\WebmanPermission\Model;

use Illuminate\Cache\Repository;
use Illuminate\Database\Eloquent\Model;

/**
* RuleModel Model
*
* @inheritDoc
*/
class LaravelRuleModel extends Model
{
Expand All @@ -25,34 +26,25 @@ class LaravelRuleModel extends Model
*/
public $timestamps = false;

/**
* a cache store.
*
* @var Repository
*/
protected Repository $store;

/**
* Fillable.
*
* @var array
*/
protected $fillable = ['ptype', 'v0', 'v1', 'v2', 'v3', 'v4', 'v5'];

/**
* the guard for lauthz.
*
* @var string
*/
protected string $guard;

/** @var string $driver */
protected string $driver;

/**
* 架构函数
* @access public
* @param array $data 数据
*/
public function __construct(array $data = [])
public function __construct(array $data = [], ?string $driver = null)
{
$this->driver = $driver;
$connection = $this->config('database.connection') ?: config('database.default');
$this->setConnection($connection);
$this->setTable($this->config('database.rules_table'));
Expand All @@ -69,24 +61,7 @@ public function __construct(array $data = [])
*/
protected function config(string $key = null, $default = null)
{
$driver = config('plugin.casbin.webman-permission.permission.default');
$driver = $this->driver ?? config('plugin.casbin.webman-permission.permission.default');
return config('plugin.casbin.webman-permission.permission.' . $driver . '.' . $key, $default);
}

/**
* Gets rules from caches.
*
* @return mixed
*/
public function getAllFromCache()
{
$get = function () {
return $this->select('ptype', 'v0', 'v1', 'v2', 'v3', 'v4', 'v5')->get()->toArray();
};
if (!$this->config('cache.enabled', false)) {
return $get();
}

return $this->store->remember($this->config('cache.key'), $this->config('cache.ttl'), $get);
}
}
}
Loading

0 comments on commit 109354d

Please sign in to comment.