An open API service indexing awesome lists of open source software.

https://github.com/danieleds/simpleroles

A simple and lightweight PHP authorization library
https://github.com/danieleds/simpleroles

Last synced: over 1 year ago
JSON representation

A simple and lightweight PHP authorization library

Awesome Lists containing this project

README

          

Getting started
----------
First, you have to create a new class where you will define all your rules. Let's start with this:

```php
getRoles();

if(in_array('admin', $user_roles)) {
$this->can('read_article');
$this->can('update_article');
$this->can('delete_article');
}

if(in_array('moderator', $user_roles)) {
$this->can('read_article');
$this->can('update_article');
}

if(in_array('guest', $user_roles)) {
$this->cannot('all');
$this->can('read_article');
}
}
```

The code is self-explanatory. `all` is a special keyword which will match every rule.
Now, we just have to add code to our main application.
For example:

```php
authorize('update_article');
// ... We're authorized. Update the article.
} else if(isset($_POST['delete'])) {
$a->authorize('delete_article');
// ... We're authorized. Delete the article.
} else {
$a->authorize('read_article');
// ... We're authorized. Display the article.
}
```

`$session_current_user` is an instance of some User model, representing the current logged in user. In the Ability class, we called `$user->getRoles()` to get an array of enabled roles for the current user.

Now, if the user is not authorized to complete the action, an exception will be raised. You can override this behavior by adding a special function called *unauthorized* to your Ability class, for example:

```php
is_authorized('your action')`.