Entrust is a concise and flexible way to add role-based permissions to Laravel5.

Source: Internet
Author: User
Tags composer install

Installation

The first thing to add in Composer.json:

"Zizaco/entrust": "5.2.x-dev"

Then run composer install or composer update

In the provider array of config.php, add:

Zizaco\entrust\entrustserviceprovider::class,

In the alias array of config.php, add:

' Entrust ' =>zizaco\entrust\entrustfacade::class,

If you want to use middleware (requires 5.1 or higher), you need to add it in the Routemiddleware array of app\http\kernel.php:

' Role ' =>\zizaco\entrust\middleware\entrustrole::class,
' Permission ' =>\zizaco\entrust\middleware\entrustpermission::class,
' Ability ' =>\zizaco\entrust\middleware\entrustability::class, configuring

Set the property value in config/auth.php. This is the value that will be used to specify the correct user table and model for entrust.

You can also publish the configuration of this package for further configuration indication and namespace.

As long as PHP artisan Vendor:publish, entrsust.php will be created in the App/config folder.

User Association to role

Now generate Enrust Migration:

PHP Artisan entrust:migration

This will generate a <timestamp>_entrust_setup_tables.ph migration. You can then run it with the migration command:

PHP Artisan Migrate

After the migration is complete, 4 new tables are created:

1. Roles-store Role records

2. Permissions-store Permission records

3. Role_user-Many-to-many associations between storage roles and users

4. Peimissionrole-Many-to-many associations between storage roles and permissions

Model Role

Use the following example to create a app/models/role.php as a role model:

<?php
namespace App;
Use Zizaco\entrust\entrustrole;
Class Role extends entrustrole{
}

The role model has 3 main attributes:

1. Name-a unique role name that is used to look up role information at the application information layer. For example: "admin", "owner", "Employee".

2. Display_name-Human readable role name. is not necessarily unique and optional. "User Administrator", "Project Owner", "Widget co.employee".

3. Description-A more detailed explanation of role roles. The same is optional.

Display_name and description are also optional. They can be empty in the database.

Permissions

Use the following example to create a app/models/permission.php as a permission model:

<?php
namespace App;
Use zizaco\entrust\entrustpermission;
Class Permission extends entrustpermission{
}

The permissions model has the same three main attributes as the role model:

1. Name-a unique permission name that is used to find permission information at the application level. For example "Create-post", "Edit-user", "Post-payment", "Mailing-list-subscribe".

2. Display_name-Human readable permission name. is not necessarily unique and optional. For example: "Create post", "Post Payments".

3. Description-More detailed description of the permissions.

User

Then use the Entrustusertrait feature in the user model, example:

<?php
Use zizaco\entrust\traits\entrustusertrait;
Class User extends eloquent{
Use entrustusertrait;
Add this trait to your user model ...
}

This will make the relationship with the role effective and add roles (), Hasrole ($name), Can ($permission), and ability ($roles, $permissions, $options) to your user model.

Don't forget to execute

Composer Dump-autoload Soft Delete

The default migration applies the OnDelete (' cascade ') clause setting to remove the association when the parent record is deleted. If for some reason you cannot use cascading deletions in the database, the Entrustrole and Entrustpermission classes and the Hasrole attribute containing the time listener can manually delete records in the related PivotTable report. To avoid accidentally deleting data, the time listener does not delete the actual data in case the model uses soft deletion. Because of the limitations of the Laravel event listener, there is no way to differentiate between delete () and Forcedelete () calls. For this reason, before you delete this model, you must manually delete any relevant data (unless your PivotTable report uses cascading deletions), for example:

$role =role::findorfail (1); Get a given role
General Delete
$role->delete ();
This will work anyway.
Force Delete
$role->users ()->sync ([]); Delete associated data
$role->perms ()->sync ([]); Delete associated data
$role->forcedelete (); Force Delete now works, no matter if the pivot table is enough cascade delete

Usage

Concept

Start by creating the following roles s and Permissions S:

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

Next, we assign two roles that have been created to a user. Because of the Hasrole feature, it is easy to:

$user =user::where (' username ', ' = ', ' Michele ')->first ();
Role Add Alias
$user->attachrole ($admin); Parameters can be a role item, an array, or
Or eloquent ' s original technology.
$user->roles ()->attach ($admin->id); ID only

Now we just need to add permissions to these roles:

$createPost =newpermission ();
$createPost->name= ' create-post ';
$createPost->display_name= ' Create Posts '; Optional
Allow a user to ...
$createPost->description= ' Create new blog posts '; Optional
$createPost->save ();
$editUser =newpermission ();
$editUser->name= ' Edit-user ';
$editUser->display_name= ' Edit Users '; Optional
Allow a user to ...
$editUser->description= ' Edit existing users '; Optional
$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));

Verifying Roles and Permissions

Now we can verify the roles and permissions in a simple way:

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

Hasrole () and can () can accept an array of roles and permissions for validation:

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

By default, any role or permission belongs to the current user, and the method returns True. Setting the second parameter of the method to true requires that all permissions and roles pass to verify success

$user->hasrole ([' owner ', ' admin ']); True
$user->hasrole ([' owner ', ' admin '], true); False, the user does not have the admin role
$user->can ([' Edit-user ', ' create-post ']); True
$user->can ([' Edit-user ', ' Create-post '], true); False, the user does not have Edit-user permissions

You can arbitrarily assign any number of roles to each user, and vice versa.

Entrust Hasrole () and can () shortcuts for users who are currently logged in

Entrust::hasrole (' Role-name ');
Entrust::can (' Permission-name ');
Equivalent to
Auth::user ()->hasrole (' Role-name ');
Auth::user ()->can (' Permission-name);

You can also use placeholders (wildcard characters) to verify any permissions that match a condition:

Match any of the admin permissions
$user->can ("admin.*"); True
Match any permissions on the user
$user->can ("*_users"); True

User availability

For more advanced authentication, you can use the ability function. It has three parameters (Roles,permissions,options):

1. Roles a set of roles for validation

2. Permissions a set of peimissions for validation

The roles and peimissions variables can be a set of comma-delimited strings or arrays:

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

This can also check whether the user provides roles and permissions. In this example, only if the user is admin and has create-post selected before it returns True.

The third parameter is an optional array:

$options = Array (
' Validate_all ' = True | False (Default:false),
' Return_type ' = Boolean | Array | Both (Default:boolean)
);

1. Validate_all This is a Boolean value that sets whether to verify that ownership is true, or returns True when at least one role or permission matches.

2. return_type Specifies whether to return a match worth a Boolean or an array, or both in an array,

The following is an example of the 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)
// }

Entrust a shortcut to 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 ');

Blade templates

There are three templates in the blade template that can be used, and your parameters will be passed directly to the Entrust function.

@role (' admin ')
<p> here is visible to users with the admin role. will be translated into \entrust::role (' admin ') </p>
@endrole
@permission (' Manage-admins ')
<p> here is visible to the user of the given permission. will be translated into \entrust::can (' manage-admins ') [email protected] has been used by the Laravel core authentication package, so use @permission directly instead of .</p>
@endpermission
@ability (' Admin,owner ', ' Create-post,edit-user ')
<p> here is visible to users of a given capability. will be translated into \entrust::ability (' Admin,owner ', ' create-post,edit-user ') </p>
@endability

Middleware

You can use middleware to filter routing and routing groups through permissions or roles:

Route::group ([' prefix ' = ' admin ', ' middleware ' = [' role:admin ']], function () {
Route::get ('/', ' [email protected] ');
Route::get ('/manage ', [' middleware ' = [' permission:manage-admins '], ' uses ' = ' [email protected] ');
});

You can use pipe symbols or operators:

' Middleware ' = [' role:admin|root ']

Simulations and functionalities use instances of multiple middleware:

' Middleware ' = [' Permission:owner ', ' permission:writer ']

More complex scenarios can be used with the ability middleware, which contains three parameters: Roles, permissions, Validate_all

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

Phrase Routing filter

Using permissions or roles to filter a route you can use the following code in your app/http/routes.php:

Admin/post routes can be accessed only if the user role has ' manage_posts ' permissions
Entrust::routeneedspermission (' admin/post* ', ' create-post ');
Only if the owner role can access the admin/advanced
Entrust::routeneedsrole (' admin/advanced* ', ' owner ');
The Second optional parameter can be an array of permissions or roles
The user needs to meet all roles and permissions to access this array
Entrust::routeneedspermission (' admin/post* ', Array (' Create-post ', ' edit-comment '));
Entrust::routeneedsrole (' admin/advanced* ', Array (' owner ', ' writer '));

Both methods accept the 3rd parameter, and if the third argument is null returns a App::abort (403) forbidden, otherwise the third argument is returned, so you can use:

Entrust::routeneedsrole (' admin/advanced* ', ' owner ', redirect::to (' home '));

In addition, the two methods also accept the 4th parameter, which defaults to true, to validate all given roles and permissions. If you set false, the function returns failure only if all permissions and roles have failed validation. This is useful for background programs that need to allow access to multiple groups:

If a user has ' create-post ', ' edit-comment ', or both they would have access
Entrust::routeneedspermission (' admin/post* ', Array (' Create-post ', ' edit-comment '), NULL, FALSE);
If a user is a member of ' owner ', ' writer ', or both they would have access
Entrust::routeneedsrole (' admin/advanced* ', Array (' owner ', ' writer '), NULL, FALSE);
If a user is a member of ' owner ', ' writer ', or both, or the user has ' create-post ', ' edit-comment ' they would have access
If the 4th parameter is true then the user must are a member of Role and must have Permission
Entrust::routeneedsroleorpermission (
' Admin/advanced* ',
Array (' owner ', ' writer '),
Array (' Create-post ', ' edit-comment '),
Null
False
);

Route filtering

Entrust role/permission filtering can use facade:

Route::filter (' manage_posts ', function ()
{
Check the current user
if (! Entrust::can (' Create-post ')) {
Return redirect::to (' admin ');
}
});
Only users with roles that has the ' manage_posts ' permission would be a able to access any admin/post route
Route::when (' admin/post* ', ' manage_posts ');

To verify a role using filtering:

Route::filter (' Owner_role ', function ()
{
Check the current user
if (! Entrust::hasrole (' Owner ')) {
App::abort (403);
}
});
Only owners'll has access to routes within admin/advanced
Route::when (' admin/advanced* ', ' owner_role ');

Entrust is a concise and flexible way to add role-based permissions to Laravel5.

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.