feat: Integrate Laravel's built-in authorization Gates

- Integrate Laravel's built-in authorization Gates (#70)
- Added guidance for Gates in README.md
This commit is contained in:
Dobando 2024-07-05 16:49:27 +08:00
parent 259a389595
commit fe9fd1a7d3
3 changed files with 60 additions and 0 deletions

View File

@ -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.

View File

@ -2,8 +2,10 @@
namespace Lauthz;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Lauthz\Contracts\ModelLoader;
use Lauthz\Facades\Enforcer;
use Lauthz\Loaders\ModelLoaderFactory;
use Lauthz\Models\Rule;
use Lauthz\Observers\RuleObserver;
@ -56,5 +58,25 @@ class LauthzServiceProvider extends ServiceProvider
$this->app->bind(ModelLoader::class, function($app, $config) {
return ModelLoaderFactory::createFromConfig($config);
});
$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);
});
}
}

View File

@ -0,0 +1,28 @@
<?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']));
}
}