Giter VIP home page Giter VIP logo

entrust's Introduction

ENTRUST (Laravel 5 Package)

Build Status Version License Total Downloads

SensioLabsInsight

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

  1. In order to install Laravel 5 Entrust, just add the following to your composer.json. Then run composer update:
"zizaco/entrust": "5.2.x-dev"
  1. Open your config/app.php and add the following to the providers array:
Zizaco\Entrust\EntrustServiceProvider::class,
  1. In the same config/app.php and add the following to the aliases array:
'Entrust'   => Zizaco\Entrust\EntrustFacade::class,
  1. Run the command below to publish the package config file config/entrust.php:
php artisan vendor:publish
  1. Open your config/auth.php and add the following to it:
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => Namespace\Of\Your\User\Model\User::class,
        'table' => 'users',
    ],
],
  1. If you want to use Middleware (requires Laravel 5.1 or later) you also need to add the following:
    'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
    'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
    'ability' => \Zizaco\Entrust\Middleware\EntrustAbility::class,

to routeMiddleware array in app/Http/Kernel.php.

Configuration

Set the property values in the config/auth.php. These values will be used by entrust to refer to the correct user table and model.

To further customize table names and model namespaces, edit the config/entrust.php.

User relation to roles

Now generate the Entrust migration:

php artisan entrust:migration

It will generate the <timestamp>_entrust_setup_tables.php migration. You may now run it with the artisan migrate command:

php artisan migrate

After the migration, four new tables will be present:

  • roles — stores role records
  • permissions — stores permission records
  • role_user — stores many-to-many relations between roles and users
  • permission_role — stores many-to-many relations between roles and permissions

Models

Role

Create a Role model inside app/models/Role.php using the following example:

<?php namespace App;

use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
{
}

The Role model has three main attributes:

  • name — Unique name for the Role, used for looking up role information in the application layer. For example: "admin", "owner", "employee".
  • display_name — Human readable name for the Role. Not necessarily unique and optional. For example: "User Administrator", "Project Owner", "Widget Co. Employee".
  • description — A more detailed explanation of what the Role does. Also optional.

Both display_name and description are optional; their fields are nullable in the database.

Permission

Create a Permission model inside app/models/Permission.php using the following example:

<?php namespace App;

use Zizaco\Entrust\EntrustPermission;

class Permission extends EntrustPermission
{
}

The Permission model has the same three attributes as the Role:

  • name — Unique name for the permission, used for looking up permission information in the application layer. For example: "create-post", "edit-user", "post-payment", "mailing-list-subscribe".
  • display_name — Human readable name for the permission. Not necessarily unique and optional. For example "Create Posts", "Edit Users", "Post Payments", "Subscribe to mailing list".
  • description — A more detailed explanation of the Permission.

In general, it may be helpful to think of the last two attributes in the form of a sentence: "The permission display_name allows a user to description."

User

Next, use the EntrustUserTrait trait in your existing User model. For example:

<?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 Role and add the following methods roles(), hasRole($name), withRole($name), can($permission), and ability($roles, $permissions, $options) within your User model.

Don't forget to dump composer autoload

composer dump-autoload

And you are ready to go.

Soft Deleting

The default migration takes advantage of onDelete('cascade') clauses within the pivot tables to remove relations when a parent record is deleted. If for some reason you cannot use cascading deletes in your database, the EntrustRole and EntrustPermission classes, and the HasRole trait include event listeners to manually delete records in relevant pivot tables. In the interest of not accidentally deleting data, the event listeners will not delete pivot data if the model uses soft deleting. However, due to limitations in Laravel's event listeners, there is no way to distinguish between a call to delete() versus a call to forceDelete(). For this reason, before you force delete a model, you must manually delete any of the relationship data (unless your pivot tables uses cascading deletes). For example:

$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

Usage

Concepts

Let's start by creating the following Roles and Permissions:

$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 HasRole trait this is as easy as:

$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 & Permissions

Now 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 hasRole() and can() can receive an array of roles & permissions to check:

$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 true as a second parameter instructs the method to require all of the items:

$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 Roles as you want for each User and vice versa.

The Entrust class has shortcuts to both can() and hasRole() for the currently logged in user:

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:

$admins = User::withRole('admin')->get();
// or maybe with a relationsship
$company->users()->withRole('admin')->get();

User ability

More advanced checking can be done using the awesome ability function. It takes in three parameters (roles, permissions, options):

  • roles is a set of roles to check.
  • permissions is a set of permissions to check.

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 admin and has the create-post permission.

The third parameter is an options array:

$options = array(
    'validate_all' => true | false (Default: false),
    'return_type'  => boolean | array | both (Default: boolean)
);
  • validate_all is a boolean flag to set whether to check all the values for true, or to return true if at least one role or permission is matched.
  • return_type specifies whether to return a boolean, array of checked values, or both in an array.

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 class has a shortcut to ability() for the currently logged in user:

Entrust::ability('admin,owner', 'create-post,edit-user');

// is identical to

Auth::user()->ability('admin,owner', 'create-post,edit-user');

Blade templates

Three directives are available for use within your Blade templates. What you give as the directive arguments will be directly passed to the corresponding Entrust function.

@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

Middleware

You 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 ability middleware which accepts 3 parameters: roles, permissions, validate_all

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

Short syntax route filter

To filter a route by permission or role you can call the following in your app/Http/routes.php:

// 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 App::abort(403), otherwise the third parameter will be returned. So you can use it like:

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 filter

Entrust roles/permissions can be used in filters by simply using the can and hasRole methods from within the Facade:

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 Entrust::hasRole() and Entrust::can() checks if the user is logged in, and then if he or she has the role or permission. If the user is not logged the return will also be false.

Troubleshooting

If you encounter an error when doing the migration that looks like:

SQLSTATE[HY000]: General error: 1005 Can't create table 'laravelbootstrapstarter.#sql-42c_f8' (errno: 150)
    (SQL: alter table `role_user` add constraint role_user_user_id_foreign foreign key (`user_id`)
    references `users` (`id`)) (Bindings: array ())

Then it's likely that the id column in your user table does not match the user_id column in role_user. Make sure both are INT(10).

When trying to use the EntrustUserTrait methods, you encounter the error which looks like

Class name must be a valid object or a string

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 entrust.php file in your config directory. If you don't, then try php artisan vendor:publish and, if it does not appear, manually copy the /vendor/zizaco/entrust/src/config/config.php file in your config directory and rename it entrust.php.

If your app uses a custom namespace then you'll need to tell entrust where your permission and role models are, you can do this by editing the config file in config/entrust.php

'role' => 'Custom\Namespace\Role'
'permission' => 'Custom\Namespace\permission'

License

Entrust is free software distributed under the terms of the MIT license.

Contribution guidelines

Support follows PSR-1 and PSR-4 PHP coding standards, and semantic versioning.

Please report any issue you find in the issues page.
Pull requests are welcome.

entrust's People

Contributors

aglipanci avatar andrew13 avatar andrewelkins avatar bbatsche avatar dboskovic avatar dzcpy avatar emir avatar gayanhewa avatar gnanakeethan avatar grahamcampbell avatar imnotjames avatar jacq avatar jobrios avatar jolamar avatar michaeljhopkins avatar micheleangioni avatar miscbits avatar mvestil avatar poma avatar rodriguezmuller avatar soupdiver avatar thefuzzy0ne avatar tonglil avatar unitedworx avatar unnawut avatar vkarampinis avatar vpratfr avatar yamenarahman avatar yelldon avatar zizaco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

entrust's Issues

Composer update throws errors on fresh install of laravel (Can't Install)

I have a fresh install of laravel and I'm trying to include Entrust. I've modified the database config to connect to an empty database for the project. Everything else is untouched. I'm on osx 10.9.

My composer.json require section looks like this:

"require": {
    "laravel/framework": "4.1.*",
    "zizaco/entrust": "dev-master"
},

When I do composer update this is what I get:

$composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for laravel/framework 4.1.8 -> satisfiable by laravel/framework[v4.1.8].
- zizaco/entrust dev-master requires illuminate/support 4.0.x -> satisfiable by laravel/framework[4.0.x-dev, v4.0.0, v4.0.0-BETA2, v4.0.0-BETA3, v4.0.0-BETA4, v4.0.1, v4.0.10, v4.0.2, v4.0.3, v4.0.4, v4.0.5, v4.0.6, v4.0.7, v4.0.8, v4.0.9], illuminate/support[4.0.x-dev, v4.0.0, v4.0.0-BETA2, v4.0.0-BETA3, v4.0.0-BETA4, v4.0.1, v4.0.10, v4.0.2, v4.0.3, v4.0.4, v4.0.5, v4.0.6, v4.0.7, v4.0.8, v4.0.9].
- Can only install one of: laravel/framework[v4.1.8, 4.0.x-dev].
- Can only install one of: laravel/framework[v4.1.8, v4.0.0].
- Can only install one of: laravel/framework[v4.1.8, v4.0.0-BETA2].
- Can only install one of: laravel/framework[v4.1.8, v4.0.0-BETA3].
- Can only install one of: laravel/framework[v4.1.8, v4.0.0-BETA4].
- Can only install one of: laravel/framework[v4.1.8, v4.0.1].
- Can only install one of: laravel/framework[v4.1.8, v4.0.10].
- Can only install one of: laravel/framework[v4.1.8, v4.0.2].
- Can only install one of: laravel/framework[v4.1.8, v4.0.3].
- Can only install one of: laravel/framework[v4.1.8, v4.0.4].
- Can only install one of: laravel/framework[v4.1.8, v4.0.5].
- Can only install one of: laravel/framework[v4.1.8, v4.0.6].
- Can only install one of: laravel/framework[v4.1.8, v4.0.7].
- Can only install one of: laravel/framework[v4.1.8, v4.0.8].
- Can only install one of: laravel/framework[v4.1.8, v4.0.9].
- don't install illuminate/support 4.0.x-dev|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.0|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.0-BETA2|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.0-BETA3|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.0-BETA4|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.1|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.10|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.2|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.3|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.4|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.5|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.6|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.7|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.8|don't install laravel/framework v4.1.8
- don't install illuminate/support v4.0.9|don't install laravel/framework v4.1.8
- Installation request for zizaco/entrust dev-master -> satisfiable by zizaco/entrust[dev-master].

Functions to Get a User's Role and Permissions

Are there functions within Entrust to get a $user objects roles and/or permissions?

I'm trying to print to screen what assigned role the user is and his/her associated permissions...

Thanks,

-Luke

Error migrate:refresh

When I run: php artisan migrate:refresh I got:

PHP Fatal error: Class 'CreateRolesTable' not found in /var/www/karelWeb/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php on line 301
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Class 'CreateRolesTable' not found","file":"/var/www/karelWeb/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php","line":301}}

Anyone knows about this problem?

Is it really required php 5.4?

If still working on 5.3 won't be able to install this via composer.

Many hosting providers do not offer 5.4 yet, is this a really needed feature?

Couldnot load this package..

Loading composer repositories with package information
Installing dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for zizaco/entrust dev-master -> satisfiable by zizac
o/entrust[dev-master].
- zizaco/entrust dev-master requires php >=5.4.0 -> no matching package foun
d.

Potential causes:

Read http://getcomposer.org/doc/articles/troubleshooting.md for further common
problems.

When i run composer intall to include your package it could not take it..
what is the problem ✌️ Thank you

Tagged releases

Hi

Just looking into Confide but I notice the last tagged release is 6 months old. Is that the latest stable code?

Using $this when not in object context (PHP -v 5.3.26 shared hosting)

Hi, This happen when I deploy my app in the server production, I see similar issues but the others was fixed, I dot'n know if is a php version problem or a configuration problem, is the classic "locally works".

$filter_name = implode('_',$roles).'_'.substr(md5($route),0,6);

    if (! $result instanceof Closure) {
        $result = function() use ($roles, $result, $cumulative) {
            $hasARole = array();
            foreach($roles as $role) {
                if ($this->hasRole($role)) {
                    $hasARole[] = true;
                } else {

Thanks beforehand.

Composer Update with Laravel 4

vendor/zizaco/entrust/src/commands/MigrationCommand.php on line 31

[code]
"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"parse error","file":"/Applications/MAMP/htdocs/portall4.dev/vendor/zizaco/entrust/src/commands/MigrationCommand.php","line":31}}Script php artisan clear-compiled handling the pre-update-cmd event returned with an error

[RuntimeException]
Error Output: PHP Parse error: parse error in /Applications/MAMP/htdocs/po
rtall4.dev/vendor/zizaco/entrust/src/commands/MigrationCommand.php on line
31

[/code]

Solution:
remove the pre-update scripts from composer.json

How to solve the problem to let pre-update scripts active?

The Response content must be a string or object implementing __toString(), "object" given.

The Response content must be a string or object implementing __toString(), "object" given.

I get this issue when using closures in Entrust::routeNeedsRole third param.

Entrust::routeNeedsRole('admin*', array('SuperAdmin', 'Admin'), function() {
Session::put('loginRedirect', Request::url());
Session::put('error', 'You must login to view that page.');
return Redirect::to(URL::route('login'));
}
);

Any ideas?

assigned_roles table

Hello,

While checking assigned_roles table I've noticed that it's being setup inefficiently.

Currently the table has 3 fields (id, user_id, role_id), of which only ID is PRIMARY.

I'd suggest making assigned_roles table consist of references to user_id and role_id (in the respective tables) and having both (user_id and role_id) fields as PRIMARY keys for faster lookups.

Code for table creation below:

CREATE  TABLE IF NOT EXISTS `database`.`assigned_roles` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
  `user_id` INT(10) UNSIGNED NOT NULL ,
  `role_id` INT(10) UNSIGNED NOT NULL ,
  PRIMARY KEY (`id`, `user_id`, `role_id`) ,
  INDEX `fk_assigned_roles_users1_idx` (`user_id` ASC) ,
  INDEX `fk_assigned_roles_roles1_idx` (`role_id` ASC) ,
  CONSTRAINT `fk_assigned_roles_users1`
    FOREIGN KEY (`user_id` )
    REFERENCES `database`.`users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_assigned_roles_roles1`
    FOREIGN KEY (`role_id` )
    REFERENCES `database`.`roles` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
AUTO_INCREMENT = 3
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci

Can't install

I'm on my local dev environment and I'm definitely running PHP 5.4.14

When I run composer update, I get this error:

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for zizaco/entrust dev-master -> satisfiable by zizaco/entrust[dev-master].
- zizaco/entrust dev-master requires php >=5.4.0 -> no matching package found.

Potential causes:

  • A typo in the package name
  • The package is not available in a stable-enough version according to your minimum-stability setting

Still doing research to figure out what causes it.

Permissions without roles?

Hey,

is there a way to add permissions to a user without adding a specific role for them?
For example if i want to add permissions for "Modules" (User A has the right to view Module "Documents", User B not - without adding a Role for every Module?)

Should i just create a role for every user?

Thanks.

migration.blade bug

To avoid the migration issue between Entrust and Confide

27 - $table->integer('user_id')->unsigned();

29 - $table->integer('role_id')->unsigned();

Issue saving permissions

When I save permissions it's saving it in the format {4:'permission_here'}
When I attempt to reference that:

        // Get current user and check permission
        $user = Confide::user();
        $canComment = false;
        if(!empty($user)) {
            $canComment = $user->can('permission_here');
        }

It comes back with false.
If the permission is saved as: ["permission_here"]
It will come back true.

See: andrewelkins/Laravel-4-Bootstrap-Starter-Site#38

I'll investigate later.

Permissions stored in the db

I might be nice to store permissions in the db as well. Have a permissions table and then the roles table would reference individual permission ids.

The advantage being you gain more flexibility on the admin side of things. Each permission could then have a name for displaying in an admin panel. Or description field for an explanation of what the permission does.

requires php >=5.4.0 -> no matching package found

I'm running Laravel on my local machine with PHP 5.4.10 installed. When I run:

composer update

I get this message:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1

  • Installation request for zizaco/entrust dev-master -> satisfiable by zizaco/entrust[dev-master].
  • zizaco/entrust dev-master requires php >=5.4.0 -> no matching package found.

Potential causes:

"composer update" works fine if I remove out "zizaco/entrust": "dev-master" from "require" in composer.json.

My PHP version is as follow:

php -v
PHP 5.4.10 (cli) (built: Jan 21 2013 15:12:32)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
with XCache v2.0.1, Copyright (c) 2005-2012, by mOo
with Xdebug v2.2.1, Copyright (c) 2002-2012, by Derick Rethans

Disregard

I had a minor typo. Sorry to clutter things up.

Four char limit on Role names

Hi,

I know it's easy to override the length limit of Role-names, but is it set to 4 by any particular reason?

For anyone having trouble with saving Role's with less than 4 characters, add, and modify, this to your own Role.php model file:

    /**
     * Ardent validation rules
     *
     * @var array
     */
    public static $rules = array(
        'name' => 'required|between:3,16'
    );

EntrustRole->name length limitation

Why is rolename limited to 16 chars? Since database migration creates a string column ( -> varchar(255)), this limitation seems unnecessary?
I propose to either remove the limitation, or at least mention it in the readme.

Polymorphic permissions

Might be nice to be able to have permissions specified against multiple types of data.

Either by class (id column is null), or instance (id column is not null).

Also global permissions are possible by having both class and id as null.

See this rails package for an idea as to how useful it can be: http://eppo.github.com/rolify/

Route Parameters + Permissions

I'm trying to filter a route with parameters, but it doesn't seem to work, as i thought.
Here is my route from routes.php:
Route::get('client/{slug}/thing/create', ThingController@create' );

Here is my filter from filters.php:
Entrust::routeNeedsPermission( 'client/{slug}/thing/create','manage_things');

But this filter is not working. Any ideas or hints?

A problem with route null/redirection

When I use this:

Entrust::routeNeedsPermission('admin/roles*', 'config_manage');

I get an HttpException and 500 Internal Server Error. When I use this:

Entrust::routeNeedsPermission('admin/roles*', 'config_manage',
Redirect::to('admin')->with('message', array(
'type' => 'warning',
'content' => 'No permissions for this resource'
)));

then the flash message appears on every click on the website.

I'm using Laravel 4.0 with the latest updates.

Easier usage for protecting a route

I would love to have a function which that i can protect the current route and which i can call in the Controller function, something like:

public function getIndex()
{
    Entrust::needed('manage_users');
}

So as soon as i hit the route Entrust will check for access and redirect or abort if the permission is not given.

We can do that with a custom function in the Basecontroller but a native function would be nice.

Custom table names or prefix

It would be nice to have posibility to define table names or prefixes.
For example those names could be:

  • cb_roles
  • cb_permissions
  • cb_permission_role
  • cb_assigned_roles

Update user's role, fails with `column not found error`

I kept trying to figure it out, why sync() user roles won't have a go, with the following error:

  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'eloquent_users_repository_id' in 'where clause' (SQL: select `role_id` from `assigned_roles` where `eloquent_users_repository_id` = ?) (Bindings: array ( 0 => '3', ))

My models, are just like those from https://github.com/andrew13/Laravel-4-Bootstrap-Starter-Site

I just can't figure out, what goes wrong. Any ideas?

Allow for a more flexible model

It would be nice if the table and field names could be customized, either through config params or via object properties. As it is now, it is a bit cumbersome to do this, as you have to extend entire methods.

Mock Entrust

Hi, i'm noob in testing and I was wondering how to mock Entrust, because in my view I have this statement: @if ( Entrust::hasRole('Admin') )

I try with Entrust::shouldReceive but I get:

PHP Fatal error: Call to undefined method Zizaco\Entrust\Entrust::shouldReceive()

Routes Needs Role (multiple roles) not working

 Entrust::routeNeedsRole( 'admin*', array('admin','restaurateur'), Redirect::to('/') );

Is not working. As an admin, it redirects to / and as a restaurateur it redirets to /.
But if I just put admin or restaurateur, it works just fine...

Any ideas why?

Thanks,
Ara

Suggestion: Add a permission table

So instead of
$owner->permissions = array('manage_posts','manage_pages','manage_users');

$owner->permissions = array(2,5,6);// where those are the ids of the permissions in the permission table.

    // Creates the permissions table
    Schema::create('permissions', function($table)
    {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });

I say this because in a system where you are creating roles from an admin screen you would likely want to see what permissions are available for two reasons.

  1. To see what permissions to add to the new role.
  2. See if you need to add a new permission.

Currently one would have to parse all of the permission fields, combine them and then spit out the permissions currently used in the system.

With the new table / model, within a controller it would be as easy as:

    $permissions = Permissions::all();

Then in the view something like:

    <select>
    @foreach ($permissions as $permission)
         <option value="{{$permission->id}}">{{$permission->name}}</option>
    @endforeach
    </select>

EntrustRole - failed to open stream

I've followed the instructions to install Entrust. I'm getting hung up on this error when trying to run the app. I'm using laravel 4.0.9:

include(/Users/myuser/Documents/workspace/myapp/app/models/Role.php use Zizaco/Entrust/EntrustRole; class Role extends EntrustRole { }.php): failed to open stream: No such file or directory

I've given my entire app read/write access to everyone and this is a fresh install of Laravel.

My Role model looks like this:

true, /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => 'http://localhost', /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => 'IhmsKHycqz7logrKtJOO4s0olnewRL0n', /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => array( 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Cache\CacheServiceProvider', 'Illuminate\Foundation\Providers\CommandCreatorServiceProvider', 'Illuminate\Session\CommandsServiceProvider', 'Illuminate\Foundation\Providers\ComposerServiceProvider', 'Illuminate\Routing\ControllerServiceProvider', 'Illuminate\Cookie\CookieServiceProvider', 'Illuminate\Database\DatabaseServiceProvider', 'Illuminate\Encryption\EncryptionServiceProvider', 'Illuminate\Filesystem\FilesystemServiceProvider', 'Illuminate\Hashing\HashServiceProvider', 'Illuminate\Html\HtmlServiceProvider', 'Illuminate\Foundation\Providers\KeyGeneratorServiceProvider', 'Illuminate\Log\LogServiceProvider', 'Illuminate\Mail\MailServiceProvider', 'Illuminate\Foundation\Providers\MaintenanceServiceProvider', 'Illuminate\Database\MigrationServiceProvider', 'Illuminate\Foundation\Providers\OptimizeServiceProvider', 'Illuminate\Pagination\PaginationServiceProvider', 'Illuminate\Foundation\Providers\PublisherServiceProvider', 'Illuminate\Queue\QueueServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'Illuminate\Auth\Reminders\ReminderServiceProvider', 'Illuminate\Foundation\Providers\RouteListServiceProvider', 'Illuminate\Database\SeedServiceProvider', 'Illuminate\Foundation\Providers\ServerServiceProvider', 'Illuminate\Session\SessionServiceProvider', 'Illuminate\Foundation\Providers\TinkerServiceProvider', 'Illuminate\Translation\TranslationServiceProvider', 'Illuminate\Validation\ValidationServiceProvider', 'Illuminate\View\ViewServiceProvider', 'Illuminate\Workbench\WorkbenchServiceProvider', 'Zizaco\Entrust\EntrustServiceProvider', ), /* |-------------------------------------------------------------------------- | Service Provider Manifest |-------------------------------------------------------------------------- | | The service provider manifest is used by Laravel to lazy load service | providers which are not needed for each request, as well to keep a | list of all of the services. Here, you may set its storage spot. | */ 'manifest' => storage_path().'/meta', /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => array( 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', 'Auth' => 'Illuminate\Support\Facades\Auth', 'Blade' => 'Illuminate\Support\Facades\Blade', 'Cache' => 'Illuminate\Support\Facades\Cache', 'ClassLoader' => 'Illuminate\Support\ClassLoader', 'Config' => 'Illuminate\Support\Facades\Config', 'Controller' => 'Illuminate\Routing\Controllers\Controller', 'Cookie' => 'Illuminate\Support\Facades\Cookie', 'Crypt' => 'Illuminate\Support\Facades\Crypt', 'DB' => 'Illuminate\Support\Facades\DB', 'Eloquent' => 'Illuminate\Database\Eloquent\Model', 'Event' => 'Illuminate\Support\Facades\Event', 'File' => 'Illuminate\Support\Facades\File', 'Form' => 'Illuminate\Support\Facades\Form', 'Hash' => 'Illuminate\Support\Facades\Hash', 'HTML' => 'Illuminate\Support\Facades\HTML', 'Input' => 'Illuminate\Support\Facades\Input', 'Lang' => 'Illuminate\Support\Facades\Lang', 'Log' => 'Illuminate\Support\Facades\Log', 'Mail' => 'Illuminate\Support\Facades\Mail', 'Paginator' => 'Illuminate\Support\Facades\Paginator', 'Password' => 'Illuminate\Support\Facades\Password', 'Queue' => 'Illuminate\Support\Facades\Queue', 'Redirect' => 'Illuminate\Support\Facades\Redirect', 'Redis' => 'Illuminate\Support\Facades\Redis', 'Request' => 'Illuminate\Support\Facades\Request', 'Response' => 'Illuminate\Support\Facades\Response', 'Route' => 'Illuminate\Support\Facades\Route', 'Schema' => 'Illuminate\Support\Facades\Schema', 'Seeder' => 'Illuminate\Database\Seeder', 'Session' => 'Illuminate\Support\Facades\Session', 'Str' => 'Illuminate\Support\Str', 'URL' => 'Illuminate\Support\Facades\URL', 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', 'Entrust' => 'Zizaco\Entrust\EntrustFacade', ), ``` ); And this is what my routes.php looks like: name = 'Owner'; $owner->save(); $admin = new Role; $admin->name = 'Admin'; $admin->save(); $user = User::where('email','=','[email protected]')->first(); /\* role attach alias */ $user->attachRole( $admin ); // Parameter can be an Role object, array or id. /\* OR the eloquent's original: */ $user->roles()->attach( $admin->id ); // id only $managePosts = new Permission; $managePosts->name = 'manage_posts'; $managePosts->display_name = 'Manage Posts'; $managePosts->save(); $manageUsers = new Permission; $manageUsers->name = 'manage_users'; $manageUsers->display_name = 'Manage Users'; $manageUsers->save(); $owner->perms()->sync(array($managePosts->id,$manageUsers->id)); $admin->perms()->sync(array($managePosts->id)); $user->hasRole("Owner"); // false $user->hasRole("Admin"); // true $user->can("manage_posts"); // true $user->can("manage_users"); // false });

Adding permissions to a role

Hi all,

This is a "proposal issue".

Currently permission assignment to a role requires knowledge of the permission_id attribute and the savePermissions method call. This is what I learned from documentation and the code; Please correct me if I am wrong.

What if permissions assignment will be done by permission name and on calling method save, so it will look more intuitive for the developers?

An example:

$role = new Role;
$role->permissions = [ 'blog.post.add', 'blog.post.edit' ];
$role->save();

This code will try to find permissions "blog.post.add" and "blog.post.edit" by name and assign them to the role on saving the role (this will use pivotal table, of course).

I have already implemented this in my project and wondering if you are interesting in the same behavior. I can do a pull request sometime this weekend if you do.

Can't run $user->attachRole in seed

I can't for the life of me get the seeder to attach roles.

I've followed your README, and have included the Entrust package in my user model and seeder file, yet it still gives the error...

when running:

$ php artisan db:seed --env="local"
Call to undefined method Illuminate\Database\Query\Builder::attachRole()

running it from

RolesTableSeeder.php

<?php
use Zizaco\Entrust\EntrustRole;
use Zizaco\Entrust\HasRole;
class RolesTableSeeder extends Seeder {
    use HasRole;

    public function run()
    {
        DB::table('roles')->delete();
        DB::table('assigned_roles')->delete();

        $admin_role = new Role;
        $admin_role->name = 'Admin';
        $admin_role->permissions = array('manage_settings', 'manage_users', 'view_adminarea', 'manage_posts', 'manage_questions');
        $admin_role->save();

        $user = User::where('username','=','admin')->first();
        $user->attachRole( $admin_role);

    }

}

Any idea as to where I'm screwing up? Any and all help greatly appreciated!

More of a Custom Addition

Someone asked me if they could have a different denied message for staff members vs guests and regular members...

Route::filter('userAdmin',function() {
if (!Entrust::hasRole('userAdmin')) {
// The problem lied here
App::abort('404');
}
});

I could do one of two things...

if (Auth::check()) {
if (Auth::User()->roles) {
App::abort('permissionDenied');
}
}

or a function in Entrust.php

function hasRoles() {
$user = $this->user;

if ($user) {
return $user->roles;
}
return false;
}

this would give me the ability to run

Route::filter('userAdmin',function() {
if (!Entrust::hasRole('userAdmin')) {
if (Entrust::hasRoles()) {
App::abort('permissionDenied');
}
App::abort('404');
}

});

instead of having to use the ability() function and list ALL of my roles individually especially if one changed.

403 instead of 404

I just noticed that you use a HTTP 404 error when a user hasn't the right permissions. A 404 means "Not found", but in fact the page is found, but the user just hasn't the right permission. I suggest you use the 403 wich means "Forbidden".

Saving new role fails with not null contraint violation

When creating a new role as describe in Usage > concepts section of the docs:

$admin = new Role;
$admin->name = "Administrador";
$admin->save();

And running it as part of my seeder, I get this error:

[Exception]
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "permissions" violates
not-null constraint (SQL: insert into "roles" ("name", "updated_at", "created_at") values (
?, ?, ?) returning "id") (Bindings: array (
0 => 'Administrador',
1 => '2013-10-28 04:58:22',
2 => '2013-10-28 04:58:22',
))

So basically it does not work as specified in the docs.

problem with namespaced models

Hi , i am just starting with laravel. So maybe this doesnt make much sense.
Because someone told me its a good practice to namespace you classes i am also namespacing my models. So both, User and Role are using "namespace Models;"
But when i do so, i get an error class 'Role' no found.
If i remove the namespace from Role.php it seems to work fine.
Am i doing something wrong or is entrust not working with my namespaced models ?

thanks

Trait causing weird error

When using hasRole as trait (if I copy the code in to the role everything works), it causes the Auth class to be buggy. Chrome console logs the error: failed to load ressource CURRENT_FILE:LAST_LINE i.e. failed to load ressources localhost:8000/login.

And this causes javascript to stop working if you put it in to the footer (where 99% of javascript belongs).

why not just use a class like you do in the roles?

PHP 5.4 requirement

Is there something I can change in order to use your package in PHP 5.3.x?

Entrust::routeNeedsRole etc should also accept route names

Now you can only add a route path, but when using resource controllers you are unable to add a Entrust::routeNeedsRole etc since the path is the same. only the http method is different.

If these types of methods accept route names this will not be an issue anymore since the route names of a resource controller are all different.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.