Skip to content

Commit

Permalink
feat: use Laravel's built-in Manager class and integrate authorizatio…
Browse files Browse the repository at this point in the history
…n Gates

- Use Laravel's built-in abstract Manager class instead of ModelLoaderFactory (php-casbin#71)
- Integrate Laravel's built-in authorization Gates (php-casbin#70)
  • Loading branch information
Dobmod committed Jun 30, 2024
1 parent 259a389 commit cb8bc81
Show file tree
Hide file tree
Showing 8 changed files with 190 additions and 59 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,16 @@ Route::group(['middleware' => ['http_request']], function () {
});
```

### Using Gates

You can use Laravel Gates to check if a user has a permission, provided that you have set an existing user instance as the currently authenticated user using `Auth::login`. See [Gates](https://laravel.com/docs/11.x/authorization#gates) for more details.

```php
if(Gate::allows('enforcer', ['articles', 'read'])) {
// The user can read articles
};
```

### Multiple enforcers

If you need multiple permission controls in your project, you can configure multiple enforcers.
Expand Down
5 changes: 3 additions & 2 deletions src/EnforcerManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
use Casbin\Model\Model;
use Casbin\Log\Log;
use Lauthz\Contracts\Factory;
use Lauthz\Contracts\ModelLoader;
use Lauthz\Models\Rule;
use Illuminate\Support\Arr;
use InvalidArgumentException;
use Lauthz\Loaders\LoaderManager;

/**
* @mixin \Casbin\Enforcer
Expand Down Expand Up @@ -87,7 +87,8 @@ protected function resolve($name)
}

$model = new Model();
$loader = $this->app->make(ModelLoader::class, $config);
$loader = $this->app->make(LoaderManager::class);
$loader->initFromConfig($config);
$loader->loadModel($model);

$adapter = Arr::get($config, 'adapter');
Expand Down
29 changes: 25 additions & 4 deletions src/LauthzServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

namespace Lauthz;

use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Lauthz\Contracts\ModelLoader;
use Lauthz\Loaders\ModelLoaderFactory;
use Lauthz\Facades\Enforcer;
use Lauthz\Loaders\LoaderManager;
use Lauthz\Models\Rule;
use Lauthz\Observers\RuleObserver;

Expand Down Expand Up @@ -53,8 +54,28 @@ public function register()
return new EnforcerManager($app);
});

$this->app->bind(ModelLoader::class, function($app, $config) {
return ModelLoaderFactory::createFromConfig($config);
$this->app->singleton(LoaderManager::class, function ($app) {
return new LoaderManager($app);
});

$this->registerGates();
}

/**
* Register a gate that allows users to use Laravel's built-in Gate to call Enforcer.
*
* @return void
*/
protected function registerGates()
{
Gate::define('enforcer', function ($user, ...$args) {
$identifier = $user->getAuthIdentifier();
if (method_exists($user, 'getAuthzIdentifier')) {
$identifier = $user->getAuthzIdentifier();
}
$identifier = strval($identifier);

return Enforcer::enforce($identifier, ...$args);
});
}
}
110 changes: 110 additions & 0 deletions src/Loaders/LoaderManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php

namespace Lauthz\Loaders;

use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Manager;
use InvalidArgumentException;

/**
* The model loader manager.
*
* A model loader is responsible for a loading model from an arbitrary source.
* Developers can customize loading behavior by implementing
* and register it in AppServiceProvider through `app(LoaderManager::class)->extend()`.
*
* Built-in loader implementations include:
* - FileLoader: For loading model from file.
* - TextLoader: Suitable for model defined as a multi-line string.
* - UrlLoader: Handles model loading from URL.
*
* To utilize a built-in or custom loader, set 'model.config_type' in the configuration to match one of the above types.
*/
class LoaderManager extends Manager
{

/**
* The array of the lauthz driver configuration.
*
* @var array
*/
protected $config;

/**
* Initialize configuration for the loader manager instance.
*
* @param array $config the lauthz driver configuration.
*/
public function initFromConfig(array $config)
{
$this->config = $config;
}

/**
* Get the default driver from the configuration.
*
* @return string The default driver name.
*/
public function getDefaultDriver()
{
return Arr::get($this->config, 'model.config_type', '');
}

/**
* Create a new TextLoader instance.
*
* @return TextLoader
*/
public function createTextDriver()
{
return new TextLoader($this->config);
}

/**
* Create a new UrlLoader instance.
*
* @return UrlLoader
*/
public function createUrlDriver()
{
return new UrlLoader($this->config);
}

/**
* Create a new FileLoader instance.
*
* @return FileLoader
*/
public function createFileDriver()
{
return new FileLoader($this->config);
}

/**
* Create a new driver instance.
*
* @param string $driver
* @return mixed
*
* @throws \InvalidArgumentException
*/
protected function createDriver($driver)
{
if (empty($driver)) {
throw new InvalidArgumentException("Unsupported empty model loader type.");
}

if (isset($this->customCreators[$driver])) {
return $this->callCustomCreator($driver);
}

$method = 'create' . Str::studly($driver) . 'Driver';

if (method_exists($this, $method)) {
return $this->$method();
}

throw new InvalidArgumentException("Unsupported model loader type: {$driver}.");
}
}
48 changes: 0 additions & 48 deletions src/Loaders/ModelLoaderFactory.php

This file was deleted.

2 changes: 1 addition & 1 deletion tests/DatabaseAdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ public function testLoadFilteredPolicy()
$this->assertEquals([
['bob', 'data2', 'write']
], Enforcer::getPolicy());

// Filter
$filter = new Filter(['v2'], ['read']);
Enforcer::loadFilteredPolicy($filter);
Expand Down
29 changes: 29 additions & 0 deletions tests/GatesAuthorizationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Lauthz\Tests;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\Gate;

class GatesAuthorizationTest extends TestCase
{
use DatabaseMigrations;

public function testNotLogin()
{
$this->assertFalse(Gate::allows('enforcer', ['data1', 'read']));
}

public function testAfterLogin()
{
$this->login('alice');
$this->assertTrue(Gate::allows('enforcer', ['data1', 'read']));
$this->assertTrue(Gate::allows('enforcer', ['data2', 'read']));
$this->assertTrue(Gate::allows('enforcer', ['data2', 'write']));


$this->login('bob');
$this->assertFalse(Gate::allows('enforcer', ['data1', 'read']));
$this->assertTrue(Gate::allows('enforcer', ['data2', 'write']));
}
}
16 changes: 12 additions & 4 deletions tests/ModelLoaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Lauthz\Tests;

use Lauthz\Facades\Enforcer;
use Lauthz\Loaders\LoaderManager;
use InvalidArgumentException;
use RuntimeException;

Expand Down Expand Up @@ -67,7 +68,7 @@ public function testEmptyLoaderType(): void
$this->assertFalse(Enforcer::enforce('alice', 'data', 'read'));
}

public function testBadUlrConnection(): void
public function testBadUrlConnection(): void
{
$this->initUrlConfig();
$this->app['config']->set('lauthz.basic.model.config_url', 'http://filenoexists');
Expand All @@ -94,12 +95,19 @@ protected function initTextConfig(): void
);
}

protected function initCustomConfig(): void {
$this->app['config']->set('lauthz.second.model.config_loader_class', '\Lauthz\Loaders\TextLoader');
protected function initCustomConfig(): void
{
$this->app['config']->set('lauthz.second.model.config_type', 'custom');
$this->app['config']->set(
'lauthz.second.model.config_text',
$this->getModelText()
);

$config = $this->app['config']->get('lauthz.second');
$loader = $this->app->make(LoaderManager::class);
$loader->extend('custom', function () use ($config) {
return new \Lauthz\Loaders\TextLoader($config);
});
}

protected function getModelText(): string
Expand All @@ -118,4 +126,4 @@ protected function getModelText(): string
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
EOT;
}
}
}

0 comments on commit cb8bc81

Please sign in to comment.