在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):Zizaco/entrust开源软件地址(OpenSource Url):https://github.com/Zizaco/entrust开源编程语言(OpenSource Language):PHP 97.8%开源软件介绍(OpenSource Introduction):ENTRUST (Laravel 5 Package)Entrust is a succinct and flexible way to add Role-based Permissions to Laravel 5. If you are looking for the Laravel 4 version, take a look Branch 1.0. It contains the latest entrust version for Laravel 4. Contents
Installation
"zizaco/entrust": "5.2.x-dev"
Zizaco\Entrust\EntrustServiceProvider::class,
'Entrust' => Zizaco\Entrust\EntrustFacade::class,
php artisan vendor:publish
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => Namespace\Of\Your\User\Model\User::class,
'table' => 'users',
],
],
'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
'ability' => \Zizaco\Entrust\Middleware\EntrustAbility::class, to ConfigurationSet the property values in the To further customize table names and model namespaces, edit the User relation to rolesNow generate the Entrust migration: php artisan entrust:migration It will generate the php artisan migrate After the migration, four new tables will be present:
ModelsRoleCreate a Role model inside <?php namespace App;
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
} The
Both PermissionCreate a Permission model inside <?php namespace App;
use Zizaco\Entrust\EntrustPermission;
class Permission extends EntrustPermission
{
} The
In general, it may be helpful to think of the last two attributes in the form of a sentence: "The permission UserNext, use the <?php
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Eloquent
{
use EntrustUserTrait; // add this trait to your user model
...
} This will enable the relation with Don't forget to dump composer autoload composer dump-autoload And you are ready to go. Soft DeletingThe default migration takes advantage of $role = Role::findOrFail(1); // Pull back a given role
// Regular Delete
$role->delete(); // This will work no matter what
// Force Delete
$role->users()->sync([]); // Delete relationship data
$role->perms()->sync([]); // Delete relationship data
$role->forceDelete(); // Now force delete will work regardless of whether the pivot table has cascading delete UsageConceptsLet's start by creating the following $owner = new Role();
$owner->name = 'owner';
$owner->display_name = 'Project Owner'; // optional
$owner->description = 'User is the owner of a given project'; // optional
$owner->save();
$admin = new Role();
$admin->name = 'admin';
$admin->display_name = 'User Administrator'; // optional
$admin->description = 'User is allowed to manage and edit other users'; // optional
$admin->save(); Next, with both roles created let's assign them to the users.
Thanks to the $user = User::where('username', '=', 'michele')->first();
// role attach alias
$user->attachRole($admin); // parameter can be an Role object, array, or id
// or eloquent's original technique
$user->roles()->attach($admin->id); // id only Now we just need to add permissions to those Roles: $createPost = new Permission();
$createPost->name = 'create-post';
$createPost->display_name = 'Create Posts'; // optional
// Allow a user to...
$createPost->description = 'create new blog posts'; // optional
$createPost->save();
$editUser = new Permission();
$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)); Checking for Roles & PermissionsNow we can check for roles and permissions simply by doing: $user->hasRole('owner'); // false
$user->hasRole('admin'); // true
$user->can('edit-user'); // false
$user->can('create-post'); // true Both $user->hasRole(['owner', 'admin']); // true
$user->can(['edit-user', 'create-post']); // true By default, if any of the roles or permissions are present for a user then the method will return true.
Passing $user->hasRole(['owner', 'admin']); // true
$user->hasRole(['owner', 'admin'], true); // false, user does not have admin role
$user->can(['edit-user', 'create-post']); // true
$user->can(['edit-user', 'create-post'], true); // false, user does not have edit-user permission You can have as many The Entrust::hasRole('role-name');
Entrust::can('permission-name');
// is identical to
Auth::user()->hasRole('role-name');
Auth::user()->can('permission-name'); You can also use placeholders (wildcards) to check any matching permission by doing: // match any admin permission
$user->can("admin.*"); // true
// match any permission about users
$user->can("*_users"); // true To filter users according a specific role, you may use withRole() scope, for example to retrieve all admins:
User abilityMore advanced checking can be done using the awesome
Either of the roles or permissions variable can be a comma separated string or array: $user->ability(array('admin', 'owner'), array('create-post', 'edit-user'));
// or
$user->ability('admin,owner', 'create-post,edit-user'); This will check whether the user has any of the provided roles and permissions.
In this case it will return true since the user is an The third parameter is an options array: $options = array(
'validate_all' => true | false (Default: false),
'return_type' => boolean | array | both (Default: boolean)
);
Here is an example 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)
// } The Entrust::ability('admin,owner', 'create-post,edit-user');
// is identical to
Auth::user()->ability('admin,owner', 'create-post,edit-user'); Blade templatesThree directives are available for use within your Blade templates. What you give as the directive arguments will be directly passed to the corresponding @role('admin')
<p>This is visible to users with the admin role. Gets translated to
\Entrust::role('admin')</p>
@endrole
@permission('manage-admins')
<p>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.</p>
@endpermission
@ability('admin,owner', 'create-post,edit-user')
<p>This is visible to users with the given abilities. Gets translated to
\Entrust::ability('admin,owner', 'create-post,edit-user')</p>
@endability MiddlewareYou can use a middleware to filter routes and route groups by permission or role Route::group(['prefix' => 'admin', 'middleware' => ['role:admin']], function() {
Route::get('/', 'AdminController@welcome');
Route::get('/manage', ['middleware' => ['permission:manage-admins'], 'uses' => 'AdminController@manageAdmins']);
}); It is possible to use pipe symbol as OR operator: 'middleware' => ['role:admin|root'] To emulate AND functionality just use multiple instances of middleware 'middleware' => ['role:owner', 'role:writer'] For more complex situations use 'middleware' => ['ability:admin|owner,create-post|edit-user,true'] Short syntax route filterTo filter a route by permission or role you can call the following in your // only users with roles that have the 'manage_posts' permission will be able to access any route within admin/post
Entrust::routeNeedsPermission('admin/post*', 'create-post');
// only owners will have access to routes within admin/advanced
Entrust::routeNeedsRole('admin/advanced*', 'owner');
// optionally the second parameter can be an array of permissions or roles
// user would need to match all roles or permissions for that route
Entrust::routeNeedsPermission('admin/post*', array('create-post', 'edit-comment'));
Entrust::routeNeedsRole('admin/advanced*', array('owner','writer')); Both of these methods accept a third parameter.
If the third parameter is null then the return of a prohibited access will be Entrust::routeNeedsRole('admin/advanced*', 'owner', Redirect::to('/home')); Furthermore both of these methods accept a fourth parameter. It defaults to true and checks all roles/permissions given. If you set it to false, the function will only fail if all roles/permissions fail for that user. Useful for admin applications where you want to allow access for multiple groups. // if a user has 'create-post', 'edit-comment', or both they will 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 will have access
Entrust::routeNeedsRole('admin/advanced*', array('owner','writer'), null, false);
// if a user is a member of 'owner', 'writer', or both, or user has 'create-post', 'edit-comment' they will have access
// if the 4th parameter is true then the user must be a member of Role and must have Permission
Entrust::routeNeedsRoleOrPermission(
'admin/advanced*',
array('owner', 'writer'),
array('create-post', 'edit-comment'),
null,
false
); Route filterEntrust roles/permissions can be used in filters by simply using the Route::filter('manage_posts', function()
{
// check the current user
if (!Entrust::can('create-post')) {
return Redirect::to('admin');
}
});
// only users with roles that have the 'manage_posts' permission will be able to access any admin/post route
Route::when('admin/post*', 'manage_posts'); Using a filter to check for a role: Route::filter('owner_role', function()
{
// check the current user
if (!Entrust::hasRole('Owner')) {
App::abort(403);
}
});
// only owners will have access to routes within admin/advanced
Route::when('admin/advanced*', 'owner_role'); As you can see TroubleshootingIf you encounter an error when doing the migration that looks like:
Then it's likely that the When trying to use the EntrustUserTrait methods, you encounter the error which looks like
then probably you don't have published Entrust assets or something went wrong when you did it.
First of all check that you have the If your app uses a custom namespace then you'll need to tell entrust where your
LicenseEntrust is free software distributed under the terms of the MIT license. Contribution guidelinesSupport follows PSR-1 and PSR-4 PHP coding standards, and semantic versioning. Please report any issue you find in the issues page. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论