Use the Entrust extension package to implement RBAC permission management in Laravel5 (II): use

Source: Internet
Author: User
Use the Entrust extension package to implement RBAC permission management in Laravel5 (II): in this article, we discussed how to install and configure Entrust in the previous tutorial. in this article, we will discuss in detail how to use it.

1. create and assign roles/permissions

First, create the Role and Permission:

$owner = new Role();$owner->name = 'owner';$owner->display_name = 'Project Owner';$owner->description = 'User is the owner of a given project';$owner->save();$admin = new Role();$admin->name = 'admin';$admin->display_name = 'User Administrator';$admin->description = 'User is allowed to manage and edit other users';$admin->save();

Next, we will allocate the two roles created to the user:

$ User = User: where ('username', '=', 'nginx')-> first (); // call the attachRole method $ user-> attachRole ($ admin) provided by hasRole; // The parameter can be a Role object, array or id // or you can also use the native method of Eloquent $ user-> roles ()-> attach ($ admin-> id); // you only need to pass the id.

Now we need to add the corresponding permissions to these roles:

$ CreatePost = new Permission (); $ createPost-> name = 'create-post'; $ createPost-> display_name = 'create posts '; $ createPost-> description = 'create new blog posts'; $ createPost-> save (); $ editUser = new Permission (); $ editUser-> name = 'edit-user'; $ editUser-> display_name = 'editusers'; $ editUser-> description = 'edit existing users '; $ editUser-> save (); $ admin-> attachPermission ($ createPost); // equivalent to $ admin-> perms () -> sync (array ($ createPost-> id); $ owner-> attachPermissions (array ($ createPost, $ editUser )); // equivalent to $ owner-> perms ()-> sync (array ($ createPost-> id, $ editUser-> id ));
2. check roles and permissions

After completing the preceding operations, we can check the corresponding roles and permissions:

$user->hasRole('owner'); // false$user->hasRole('admin'); // true$user->can('edit-user'); // false$user->can('create-post'); // true

Both hasRole () and can receive roles and permissions in array form for inspection:

$user->hasRole(['owner', 'admin']); // true$user->can(['edit-user', 'create-post']); // true

By default, true is returned if the user has any of the above roles or permissions. if you want to check whether the user has all the roles and permissions, you can pass true as the second parameter to the corresponding method:

$user->hasRole(['owner', 'admin']); // true$user->hasRole(['owner', 'admin'], true); // false$user->can(['edit-user', 'create-post']); // true$user->can(['edit-user', 'create-post'], true); // false

You can have multiple roles.

In addition, you can use the Entrust facade to check whether the current logon user has the specified role and permissions:

Entrust::hasRole('role-name');Entrust::can('permission-name');

You can also use wildcards to check user permissions:

// match any admin permission$user->can("admin.*"); // true// match any permission about users$user->can("*_users"); // true
3. ability method

You can also use the ability method to perform more advanced checks. This requires three parameters (role, permission, and option). Likewise, roles and permissions can be strings or arrays:

$ User-> ability (array ('admin', 'owner'), array ('create-post', 'edit-user ')); // or $ user-> ability ('admin, owner', 'create-post, edit-user ');

This checks whether the user has any provided roles and permissions. In this example, true is returned because the user's role is admin and has the create-post permission.

The third parameter is an optional array:

$options = array(    'validate_all' => true | false (Default: false),    'return_type' => boolean | array | both (Default: boolean));

Validate_all is a Boolean value used to set whether to check all values. return_type is used to specify whether to return a Boolean value, check a value array, or both.

The following is an output example:

$options = array(    'validate_all' => true,    'return_type' => 'both');list($validate, $allValidations) = $user->ability(    array('admin', 'owner'),    array('create-post', 'edit-user'),    $options);var_dump($validate);// bool(false)var_dump($allValidations);// array(4) {//     ['role'] => bool(true)//     ['role_2'] => bool(false)//     ['create-post'] => bool(true)//     ['edit-user'] => bool(false)// }

Similarly, the Entrust facade provides the ability method for the current login user:

Entrust: ability ('admin, owner ', 'create-post, edit-user'); // equivalent to Auth: user ()-> ability ('admin, owner ', 'create-post, edit-user ');
4. Blade Template

In the Blade template, you can also use the commands corresponding to the preceding three methods:

@role('admin')    

This is visible to users with the admin role. Gets translated to \Entrust::role('admin')

@endrole@permission('manage-admins')

This is visible to users with the given permissions. Gets translated to \Entrust::can('manage-admins'). The @can directive is already taken by core laravel authorization package, hence the @permission directive instead.

@endpermission@ability('admin,owner', 'create-post,edit-user')

This is visible to users with the given abilities. Gets translated to \Entrust::ability('admin,owner', 'create-post,edit-user')

@endability

Middleware

You can filter routes and routing groups by roles or permissions in middleware:

Route::group(['prefix' => 'admin', 'middleware' => ['role:admin']], function() {    Route::get('/', 'AdminController@welcome');    Route::get('/manage', [        'middleware' => ['permission:manage-admins'],         'uses' => 'AdminController@manageAdmins'    ]);});

Support OR/AND logic:

'middleware' => ['role:admin|root']'middleware' => ['permission:owner', 'permission:writer']

The ability middleware can also be used:

'middleware' => ['ability:admin|owner,create-post|edit-user,true']
5. fast implementation of routing filters

You can also use the following code in app/Http/routes. php to filter routes by permissions and roles:

// Only users with the 'create-post' permission can access admin/post * Entrust: routeNeedsPermission ('admin/post * ', 'create-post '); // only the owner can access admin/advanced * Entrust: routeNeedsRole ('admin/advanced * ', 'owner'); // The second parameter can be an array, in this way, the user must meet all the conditions to access the corresponding route Entrust: routeNeedsPermission ('admin/post * ', array ('create-post', 'edit-comment'); Entrust:: routeNeedsRole ('admin/advanced * ', array ('owner', 'writer '));

The preceding method can accept the third parameter. if the third parameter is null, access to the default App: abort (403) is forbidden. Otherwise, the third parameter is returned, so we can do this:

Entrust::routeNeedsRole('admin/advanced*', 'owner', Redirect::to('/home'));

You can even accept the fourth parameter. the default value is true, which means that all roles and permissions provided are checked. if you set this parameter to false, this method will return a failure only when all roles/permissions are not met:

// If you have either 'create-post' or 'edit-comment' permissions, you can access Entrust: routeNeedsPermission ('admin/post *', array ('create-post', 'edit-comment '), null, false); // if the user is the owner, author, or both, you can access Entrust :: routeNeedsRole ('admin/advanced * ', array ('owner', 'write'), null, false); Entrust: routeNeedsRoleOrPermission ('admin/advanced *', array ('owner', 'writer'), array ('create-post', 'edit-comment'), null, false );
6. route filter

Entrust roles/permissions can be applied to the filter by calling the can and hasRole methods on the Entrust facade:

Route: filter ('manage _ posts', function () {// check the current user if (! Entrust: can ('create-post') {return Redirect: to ('admin ');}}); // only the user's role has the 'manage _ posts' permission can access any admin/post Route: when ('admin/post * ', 'manage _ posts ');

Use filters to check roles:

Route: filter ('owner _ role', function () {// check the current user if (! Entrust: hasRole ('owner') {App: abort (403) ;}}); // only the Owner can access the admin/advanced * Route :: when ('admin/advanced * ', 'owner _ role ');

As you can see, the Entrust: hasRole and Entrust: can methods check whether users are logged on and then determine whether they are useful for specifying roles or permissions, if the user does not log on, false is returned directly.

If you want to view instances that implement background permission management based on Entrust in Laravel 5.2, refer to Ryan's Github project: https://github.com/yuansir/laravel5-rbac-example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.