Skip to content

多套配置共存及针对Laravel ORM的优化 #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ vendor
.idea
.vscode
.phpunit*
composer.lock
composer.lock
.DS_Store
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>
8 changes: 7 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"casbin/casbin": "^3.20",
"topthink/think-orm": "^2.0",
"php-di/php-di": "^6.3",
"doctrine/annotations": "^1.13",
"workerman/redis": "^1.0"
},
"autoload": {
Expand All @@ -41,7 +42,12 @@
"phpunit/phpunit": "~7.0|~8.0|~9.0",
"php-coveralls/php-coveralls": "^2.1",
"workerman/webman": "^1.0",
"vlucas/phpdotenv": "^5.5",
"psr/container": "^1.1.1",
"illuminate/database": "^8.83",
"illuminate/cache": "^8.83"
"illuminate/pagination": "^8.83",
"illuminate/events": "^8.83",
"symfony/var-dumper": "^6.2",
"webman/think-orm": "^1.0"
}
}
8 changes: 4 additions & 4 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 RuleModel([], $driver);
}

/**
Expand Down Expand Up @@ -371,4 +371,4 @@ public function loadFilteredPolicy(Model $model, $filter): void
}
$this->setFiltered(true);
}
}
}
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();
}
}
Loading