Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sentry/Sentinel if user is in role

I am trying to run a check to see if the current user is in a certain role with Cartalyst's Sentinel/Sentry package.

I have found Sentinel::inRole('admin') but can't seem to get it to work. I want something like this:

if(Sentinel::getUser()->hasRole('admin'){ // do some stuff }

I've searched and searched for this and can't find an example to work with. Should I be looking more into permissions or something?

Hopefully someone out there can point me in the right direction.

Cheers

like image 550
T2theC Avatar asked Aug 18 '14 14:08

T2theC


2 Answers

You can use inRole here, Sentinel::getUser()->inRole('role_slug');. Of course this would only work if a user is logged in.

You might wanna change it to something like this to prevent calling inRole on a non object.


    if ($user = Sentinel::getUser())
    {
        if ($user->inRole('administrator'))
        {
            // Your logic
        }
    }

Hope that helps.

like image 74
Suhayb El Wardany Avatar answered Oct 20 '22 00:10

Suhayb El Wardany


Have your User model extend Cartalyst's 'EloquentUser' model. This model has a getRoles() function that will return the roles for that user. Each user also has an inRole( $role ) function that will return true if the user has the role specified in the parameter.

Extention would look like this:

use Cartalyst\Sentinel\Users\EloquentUser;

class User extends EloquentUser implements ... {
    ....
}

In my opinion this is the cleanest way to accomplish what you want.

If you don't want to do that you could check permissions instead and have your permissions configured like a role

$admin = Sentinel::create()

$admin->permissions = [
    'admin' => true,
];

$admin->save();

Then check the user's permissions instead of checking their role

if($admin->hasAccess('admin') { // do some stuff }

Hope this helps.

-Josh E

like image 41
jerney Avatar answered Oct 19 '22 22:10

jerney