https://github.com/andrewdyer/gate
Check if a user is authorized to perform a given action
https://github.com/andrewdyer/gate
authorization gate permissions php
Last synced: 2 months ago
JSON representation
Check if a user is authorized to perform a given action
- Host: GitHub
- URL: https://github.com/andrewdyer/gate
- Owner: andrewdyer
- Created: 2020-02-22T00:07:12.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2024-12-23T00:13:31.000Z (over 1 year ago)
- Last Synced: 2025-05-06T01:09:46.240Z (about 1 year ago)
- Topics: authorization, gate, permissions, php
- Language: PHP
- Size: 32.2 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Gate
[](https://packagist.org/packages/andrewdyer/gate)
[](https://packagist.org/packages/andrewdyer/gate)
[](https://packagist.org/packages/andrewdyer/gate)
[](https://packagist.org/packages/andrewdyer/gate)
[](https://packagist.org/packages/andrewdyer/gate)
[](https://packagist.org/packages/andrewdyer/gate)
[](https://packagist.org/packages/andrewdyer/gate)
Check if a user is authorized to perform a given action.
## License
Licensed under MIT. Totally free for private or commercial projects.
## Installation
```text
composer require andrewdyer/gate
```
## Getting Started
To get started with the Gate library, you need to create an instance of the `Gate` class and pass an `Authenticatable` user to it.
```php
use Anddye\Gate\Gate;
use Anddye\Gate\Authenticatable;
class User implements Authenticatable {
// User implementation
}
$user = new User();
$gate = new Gate($user);
```
## Usage
### Defining Abilities
You can define abilities using the `define` method. The first argument is the name of the ability, and the second argument is a callback that determines if the user has the ability.
```php
$gate->define('edit-post', function ($user, $post) {
return $user->id === $post->user_id;
});
```
### Checking Abilities
You can check abilities using the `allows` and `denies` methods.
```php
if ($gate->allows('edit-post', $post)) {
// The user can edit the post
}
if ($gate->denies('edit-post', $post)) {
// The user cannot edit the post
}
```
### Authorizing Actions
You can authorize actions using the `authorize` method. This method will throw an `UnauthorizedException` if the user does not have the required abilities.
```php
try {
$gate->authorize(['edit-post'], $post);
// The user is authorized to edit the post
} catch (UnauthorizedException $e) {
// The user is not authorized to edit the post
}
```
### Registering Before Callbacks
You can register a callback to run before all checks using the `before` method.
```php
$gate->before(function ($user, $ability) {
if ($user->isAdmin()) {
return true;
}
});
```