Implementing RBAC Rights Management in Laravel 5 using the Entrust Expansion Pack (ii): Using the

Source: Internet
Author: User
In the previous tutorial we discussed how to install configuration entrust, which we'll discuss in detail.

1. Create roles/permissions and assign

Let's start by creating 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 create the two roles assigned to the user:

$user = User::where (' username ', ' = ', ' Michele ')->first ();//Call Hasrole to provide Attachrole method $user->attachrole ($admin) ; The parameter can be a role object, an array or a id//, or you can use the eloquent native method $user->roles ()->attach ($admin->id); Just pass the ID

Now we also need to add the appropriate 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 = ' edit users '; $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 & Permissions

After doing this, we can check the roles and permissions below:

$user->hasrole (' owner '); False$user->hasrole (' admin '); True$user->can (' Edit-user '); False$user->can (' Create-post '); True

Hasrole () and can both receive an array of roles and permissions for checking:

$user->hasrole ([' owner ', ' admin ']); True$user->can ([' Edit-user ', ' create-post ']); True

By default, if a user has any of these roles or permissions, it returns True, and if you want to check whether the user has all roles and permissions, you can pass true as the second parameter to the appropriate 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

Users can have multiple roles.

In addition, you can check whether the currently logged on user has the specified roles and permissions through the entrust façade:

Entrust::hasrole (' Role-name '); Entrust::can (' Permission-name ');

You can even check user permissions by using wildcard characters:

Match any admin permission$user->can ("admin.*"); true//match any permission about Users$user->can ("*_users"); True

3. Ability method

You can also implement more advanced checks by using the ability method, which requires three parameters (roles, permissions, Options), and the same roles and permissions can be either a string or an array:

$user->ability (' admin ', ' owner '), Array (' Create-post ', ' edit-user '));//or $user->ability (' Admin,owner ') , ' Create-post,edit-user ');

This checks to see if the user has any roles and permissions that are provided, and in this case returns true because the user's role is admin and has create-post permissions.

The third parameter is an optional array:

$options = Array (    ' validate_all ' = = True | False (Default:false),    ' return_type ' = = Boolean | array | both ( Default:boolean));

Where Validate_all is a Boolean value that sets whether to check all values, Return_type is used to specify the return boolean value, check the array of values, or both.

Here is an example of a sample output:

$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 façade also provides the ability method for the currently logged-on user:

Entrust::ability (' Admin,owner ', ' create-post,edit-user ');//equivalent to Auth::user ()->ability (' Admin,owner ', ' Create-post,edit-user ');

4. Blade Template

The instructions for the above three methods can also be used in the blade template:

@role (' admin ')    

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

@endrole @permission (' Manage-admins ')

This was 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 was 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 through roles or permissions in the middleware:

Route::group ([' prefix ' = ' admin ', ' middleware ' = [' role:admin ']], function () {    route::get ('/', ' Admincontroller@welcome ');    Route::get ('/manage ', [        ' middleware ' = [' permission:manage-admins '],         ' uses ' and ' = ' Admincontroller@manageadmins '    ]);

Support for Or/and logic:

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

You can also use ability Middleware:

' Middleware ' = [' ability:admin|owner,create-post|edit-user,true ']

5, the fast implementation of the route filter

Filtering routes through permissions and roles you can also invoke the following code in app/http/routes.php:

Only users who have the ' create-post ' permission corresponding to the role can access admin/post*entrust::routeneedspermission (' admin/post* ', ' create-post ');/ Only the owner can access Admin/advanced*entrust::routeneedsrole (' admin/advanced* ', ' owner ');//The second argument can be an array, In this way the user must satisfy all conditions to access the corresponding route entrust::routeneedspermission (' admin/post* ', Array (' Create-post ', ' edit-comment ')); Entrust::routeneedsrole (' admin/advanced* ', Array (' owner ', ' writer '));

The above method can accept the third parameter, if the third argument is NULL then the default call 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, which defaults to true, which means that all the roles and permissions provided will be checked, and if you set it to False, the method will return failure only if all roles/permissions are not met:

If the user has ' create-post ', ' edit-comment ' one or two permissions have access to the entrust::routeneedspermission (' admin/post* ', an array (' Create-post ', ' edit-comment '), NULL, FALSE);//If the user is an owner, author, or both, you can access the Entrust::routeneedsrole (' admin/advanced* ', Array (' owner ', ' writer '), 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 invoking the can and Hasrole methods on the entrust façade:

Route::filter (' manage_posts ', function () {    //Check the current user    if (! Entrust::can (' Create-post ')) {        return redirect::to (' admin ');}    }); /only the user corresponding role has ' manage_posts ' permission to access any admin/post route route::when (' admin/post* ', ' manage_posts ');

Use filters to check for 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 route::when (' admin/advanced* ', ' owner_role ');

As you can see, the Entrust::hasrole and Entrust::can methods check whether the user is logged in, and then determine whether they are useful to specify roles or permissions, and return False if the user is not logged in.

If you want to see an instance of background rights management based on entrust in Laravel 5.2, refer to Ryan's GitHub project: Https://github.com/yuansir/laravel5-rbac-example

  • Related Article

    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.