How to: implement sentry 2 permissions with Laravel 4?

爱⌒轻易说出口 提交于 2019-11-30 11:01:02

问题


I'm trying to use cartalyst sentry 2 in my site being built with Laravel 4. Basically I don't understand how to implement permissions.

The examples I've seen for permissions for a group specify the following as an example:

{
    "name" : "Administrator",
    "permissions" : 
    {
        "user.create" : 1,
        "user.delete" : 1,
        "user.view"   : 1,
        "user.update" : 1
    }
}

SO this is setting permissions for the admin group. BUT where are these permissions set?

In the table 'groups' there is a field called permissions which is a text field - are they set there - if so how? Or are these set in a model or controller?

Can anyone point me to s step by step on how to use in a laravel 4 app? I've read the supporting docs which foes through the functions but I'm just not sure how to set the data to get the functions to work.


回答1:


Basically you have to..

Create your groups

Sentry::getGroupProvider()->create([
    'name' => 'Super Administrators',
    'permissions' => [
        'system' => 1,
    ],
]);

Sentry::getGroupProvider()->create([
    'name' => 'Managers',
    'permissions' => [
        'system.products' => 1,
        'system.store' => 1,
        'system.profile' => 1,
    ],
]);

Set a group to a particular user, in this case it is setting Managers to the current logged user

Sentry::getUser()->addGroup( Sentry::getGroupProvider()->findByName('Managers') );

Check if a user has a particular access

if ( Sentry::getUser()->hasAnyAccess(['system','system.products']) )
{
    // Will be able to do a thing
}

Check if a user is Super Administrator (only this group has the 'system' access)

if ( Sentry::getUser()->hasAnyAccess(['system']) )
{
    // Will be able to do a thing
}

Get all groups from a particular user

try
{
    // Find the user using the user id
    $user = Sentry::getUserProvider()->findById(1);

    // Get the user groups
    $groups = $user->getGroups();
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
    echo 'User was not found.';
}



回答2:


In your groups table you set the permissions using JSON.

I have the following columns:

id | name | permissions

And a row:

1 | admin | {"admin":1, "create_news": 1}

Assign a user to a group using the table users_groups

Now you can use the following example to check if a user have a given permission:

$user = Sentry::getUser();
if ($user->hasAccess('create_news')) {
    echo "You can create a news item";
}
else {
    echo "You can't create a news item";
}


来源:https://stackoverflow.com/questions/17012553/how-to-implement-sentry-2-permissions-with-laravel-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!