Simple Laravel Resource Access Control
419
4
1
Package Data
Maintainer Username: wesleyalmeida
Maintainer Contact: wes@tera-tech.net (Wes Almeida)
Package Create Date: 2014-12-30
Package Last Update: 2015-07-06
Language: PHP
License: Apache-2.0
Last Refreshed: 2024-03-26 15:00:13
Package Statistics
Total Downloads: 419
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 4
Total Watchers: 1
Total Forks: 1
Total Open Issues: 0

#Sentry

Simple Laravel Resource Access Control

Usage

Sentry is a simple Laravel resource access control plugin that works without specifying resources. The sentry_user_roles database table stores the relationship between the user and the user's roles. Roles can be any arbitrary string that an organization chooses to use. Because this system does not care about resources, developers can validate a user's roles at any time simply by running a check of Sentry::hasRole("my_role"). The developer's script can continue or hault based on the boolean result of that check.

Sentry requires knowledge of the user's roles before it is effective. The best place to load Sentry with this information is immediately after the user has been authorized in your application; typically after logging in.

Example

public function doLogin() {

    $credentials = [
        'username' => 'foo',
        'password' => 'bar',
    ]

    if(Auth::attempt($credentials)) {

        // Retrieve SentryUserRoles from storage
        // Below is the Query way, but you can use
        // any other database driver.
        $table      = DB::table('sentry_user_roles');
        $query      = $table->where('user_id', "=", $user_id);
        $user_roles = $query->lists('role');
        
        // Add user roles to Sentry
        Sentry::setUserRoles($user_roles);
        
        // Success Authentication
        return Redirect::intended('/');
        
    } else {
        
        // Fail Authentication
        return Redirect::route('login');
    }
}

Once the developer has completed loading Sentry with the user roles it is not necessary to perform this step again.

Validation is simple. The developer can perform this anywhere, but the most common use-case is probably in a Controller's Action.

Example

class HomeController extends BaseController {

    public function myAdminAction() {
    
        // Sentry::requireRole accepts a string, or an array
        // String usage is below
        $isAllowed = Sentry::requireRole('admin');

        if($isAllowed) {
            dd("Success, I'm allowed to do this!");
        }
        dd("Bummer, I am not allowed to do this...");
    }
    
    public function myPowerUserAction() {
    
        // Sentry::requireRole accepts a string, or an array
        // Array usage is below
        $isAllowed = Sentry::requireRole(['sales', 'sales_admin', 'sales_intern']);

        if($isAllowed) {
            dd("Success, I'm allowed to do this!");
        }
        dd("Bummer, I am not allowed to do this...");
    }
}

Instead of passing a string or an array to Sentry::requireRole(), a developer can allow Roles by using the Sentry::allowFooRole magic method. A third way of allowing roles is to use Sentry::allow("foo_role"). If the developer chooses this method, then he or she can call Sentry::requireRole() without any parameters.

Example

Sentry::allowUser();
Sentry::allowGuest();
$isAllowed = Sentry::requireRole();

is the same as

$isAllowed = Sentry::requireRole(['user', 'guest']);

which is the same as

Sentry::allow('user');
Sentry::allow('guest');
$isAllowed = Sentry::requireRole();

Additionally, the configuration file for this package includes the parameter super_admin. The role assigned to this key will always be allowed whenever Sentry::requireRole() is invoked. In other words, Sentry::requireRole() will return TRUE for users who's roles include the value that matches the value in super_admin.

Example

// config/packages/wesleyalmeida/sentry/config.php
    'super_admin' => 'admin',


// login action
    // User Roles
    $user_roles = ['user', 'sales', 'admin']
    // Add user roles to Sentry
    Sentry::setUserRoles($user_roles);

// someAction()
    $isAllowed = Sentry::requireRole(); // returns true
    

Final Note

  1. The user roles are not case sensitive. All user roles are normalized to lowercase as soon as the developer provides them to Sentry. Underscores are not converted to camelCase. Therefore, salesAdmin is the same as salesadmin, but neither are the same as sales_admin.

  2. Sentry uses Laravel's Session to store the user roles. If you want to store the user roles in the Auth::user() object, you can do so by adding the following method to the User object that your UserProvider class demands. In the event that the user roles expire within the Session, Sentry will throw a SentryKeyNotFoundException. Catch this exception and reset the user roles with:

    Sentry::setUserRoles($user_roles);

Sample

// Eloquent User
public function roles() {
    $this->hasMany('SentryUserRoles', 'user_id', 'id); // SentryUserRoles must also be an Eloquent model
}

// Using QueryBuilder
public function roles() {
    $table = DB::table('sentry_user_roles');
    
    $query = $table->where('user_id', "=", $user_id);

    return $query->lists('role');
}

Installation

Composer

"require": {
    "wesleyalmeida/sentry": "dev-master"
},
"repositories": [
    { "type": "vcs", "url": "git@github.com:wesleyalmeida/sentry.git" }
],

Configuration File

php artisan config:publish wesleyalmeida/sentry"

Database Table

php artisan migrate --package="wesleyalmeida/sentry"