Skip to content

Commit

Permalink
feat: make cache configurable (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dobmod authored Aug 17, 2024
1 parent 2daf43e commit a5bc495
Show file tree
Hide file tree
Showing 9 changed files with 199 additions and 50 deletions.
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,14 +209,31 @@ Enforcer::hasPermissionForUser('eve', 'articles', 'read'); // true or false

### 使用中间件


该扩展包带有一个 `\tauthz\middleware\Basic::class` 中间件:

```php
Route::get('news/:id','News/Show')
->middleware(\tauthz\middleware\Basic::class, ['news', 'read']);
```

### 缓存配置

该扩展包通过配置 `config/tauthz.php` 中的 `cache` 选项来开启或关闭缓存,以及配置缓存标识和过期时间。

通过继承 `tauthz\cache\CacheHandler` 可以实现自定义缓存策略。例如:

```php
class MyCacheHandler extends CacheHandler
{
public function cachePolicies(Rule $model)
{
return $model->cacheAlways('my_cache_key', 3600);
}
}
```

并在 `cache` 配置选项中的`handler`声明此类。

## 感谢

[Casbin](https://github.com/php-casbin/php-casbin),你可以查看全部文档在其 [官网](https://casbin.org/) 上。
Expand Down
14 changes: 14 additions & 0 deletions config/tauthz.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,20 @@
// 策略表完整名称.
'rules_table' => null,
],

/*
* 缓存设置.
*/
'cache' => [
// 是否使用缓存
'enabled' => true,
// 缓存key
'key' => 'tauthz',
// 缓存有效期 0表示永久缓存
'expire' => 0,
// 缓存策略
'handler' => \tauthz\cache\CacheHandler::class
]
],
],
];
24 changes: 18 additions & 6 deletions src/adapter/DatabaseAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace tauthz\adapter;

use tauthz\model\Rule;
use tauthz\cache\CacheHandlerContract;
use Casbin\Model\Model;
use Casbin\Persist\Adapter;
use Casbin\Persist\AdapterHelper;
Expand All @@ -11,6 +12,7 @@
use Casbin\Persist\FilteredAdapter;
use Casbin\Persist\Adapters\Filter;
use Casbin\Exceptions\InvalidFilterTypeException;
use tauthz\traits\Configurable;
use think\facade\Db;

/**
Expand All @@ -20,7 +22,7 @@
*/
class DatabaseAdapter implements Adapter, UpdatableAdapter, BatchAdapter, FilteredAdapter
{
use AdapterHelper;
use AdapterHelper, Configurable;

/**
* @var bool
Expand All @@ -34,6 +36,13 @@ class DatabaseAdapter implements Adapter, UpdatableAdapter, BatchAdapter, Filter
*/
protected $model;

/**
* Cache Handler.
*
* @var CacheHandlerContract
*/
protected $cacheHandler;

/**
* the DatabaseAdapter constructor.
*
Expand All @@ -42,6 +51,9 @@ class DatabaseAdapter implements Adapter, UpdatableAdapter, BatchAdapter, Filter
public function __construct(Rule $model)
{
$this->model = $model;

$cacheHandlerClass = $this->config('cache.handler', \tauthz\cache\CacheHandler::class);
$this->cacheHandler = new $cacheHandlerClass();
}

/**
Expand Down Expand Up @@ -78,7 +90,7 @@ public function savePolicyLine($ptype, array $rule)
foreach ($rule as $key => $value) {
$col['v'.strval($key).''] = $value;
}
$this->model->cache('tauthz')->insert($col);
$this->cacheHandler->cachePolicies($this->model)->insert($col);
}

/**
Expand All @@ -88,7 +100,7 @@ public function savePolicyLine($ptype, array $rule)
*/
public function loadPolicy(Model $model): void
{
$rows = $this->model->cache('tauthz')->field(['ptype', 'v0', 'v1', 'v2', 'v3', 'v4', 'v5'])->select()->toArray();
$rows = $this->cacheHandler->cachePolicies($this->model)->field(['ptype', 'v0', 'v1', 'v2', 'v3', 'v4', 'v5'])->select()->toArray();
foreach ($rows as $row) {
$this->loadPolicyArray($this->filterRule($row), $model);
}
Expand Down Expand Up @@ -148,7 +160,7 @@ public function addPolicies(string $sec, string $ptype, array $rules): void
$cols[$i++] = $temp;
$temp = [];
}
$this->model->cache('tauthz')->insertAll($cols);
$this->cacheHandler->cachePolicies($this->model)->insertAll($cols);
}

/**
Expand All @@ -169,7 +181,7 @@ public function removePolicy(string $sec, string $ptype, array $rule): void
}

foreach ($instance->select() as $model) {
if ($model->cache('tauthz')->delete()) {
if ($this->cacheHandler->cachePolicies($model)->delete()) {
++$count;
}
}
Expand Down Expand Up @@ -218,7 +230,7 @@ public function _removeFilteredPolicy(string $sec, string $ptype, int $fieldInde
$item = $model->hidden(['id', 'ptype'])->toArray();
$item = $this->filterRule($item);
$removedRules[] = $item;
if ($model->cache('tauthz')->delete()) {
if ($this->cacheHandler->cachePolicies($model)->delete()) {
++$count;
}
}
Expand Down
29 changes: 29 additions & 0 deletions src/cache/CacheHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace tauthz\cache;

use tauthz\model\Rule;
use tauthz\traits\Configurable;
use think\db\Query;

class CacheHandler implements CacheHandlerContract
{
use Configurable;

/**
* Cache policies for the given model.
*
* @param Rule $model The model to cache policies for.
* @return Query The cached query or a new query if caching is disabled.
*/
public function cachePolicies(Rule $model): Query
{
if ($this->config('cache.enabled', false)) {
$key = $this->config('cache.key', 'tauthz');
$expire = $this->config('cache.expire', 0);
return $model->cache($key, $expire);
} else {
return $model->newQuery();
}
}
}
11 changes: 11 additions & 0 deletions src/cache/CacheHandlerContract.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace tauthz\cache;

use tauthz\model\Rule;
use think\db\Query;

interface CacheHandlerContract
{
public function cachePolicies(Rule $model): Query;
}
16 changes: 2 additions & 14 deletions src/model/Rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace tauthz\model;

use tauthz\traits\Configurable;
use think\Model;
use think\contract\Arrayable;

Expand All @@ -10,6 +11,7 @@
*/
class Rule extends Model implements Arrayable
{
use Configurable;
/**
* 设置字段信息
*
Expand Down Expand Up @@ -37,18 +39,4 @@ public function __construct($data = [])
$this->name = $this->config('database.rules_name');
parent::__construct($data);
}

/**
* Gets config value by key.
*
* @param string $key
* @param string $default
*
* @return mixed
*/
protected function config(string $key = null, $default = null)
{
$driver = config('tauthz.default');
return config('tauthz.enforcers.'.$driver.'.'.$key, $default);
}
}
20 changes: 20 additions & 0 deletions src/traits/Configurable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace tauthz\traits;

trait Configurable
{
/**
* Gets config value by key.
*
* @param string $key
* @param string $default
*
* @return mixed
*/
protected function config(string $key = null, $default = null)
{
$driver = config('tauthz.default');
return config('tauthz.enforcers.' . $driver . '.' . $key, $default);
}
}
34 changes: 34 additions & 0 deletions tests/CommandTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace tauthz\tests;

class CommandTest extends TestCase
{
public function testPublish()
{
$this->refreshApplication();
// delete published files
$this->deletePublishedFiles();
// run command
$this->app->console->call('tauthz:publish');

$this->assertFileExists($this->app->getRootPath() . '/database/migrations/20181113071924_create_rules_table.php');
$this->assertFileExists(config_path() . 'tauthz-rbac-model.conf');
$this->assertFileExists(config_path() . 'tauthz.php');
}

protected function deletePublishedFiles()
{
$destination = $this->app->getRootPath() . '/database/migrations';
if (file_exists($destination . '/20181113071924_create_rules_table.php')) {
unlink($destination . '/20181113071924_create_rules_table.php');
rmdir($destination);
}
if (file_exists(config_path() . 'tauthz-rbac-model.conf')) {
unlink(config_path() . 'tauthz-rbac-model.conf');
}
if (file_exists(config_path() . 'tauthz.php')) {
unlink(config_path() . 'tauthz.php');
}
}
}
Loading

0 comments on commit a5bc495

Please sign in to comment.