Laravel Authority - 如何将Authority :: can()称为另一个用户?

时间:2013-11-01 10:00:08

标签: php laravel laravel-4

我在Laravel应用程序中使用 Authority 程序包进行访问控制(我将从Laravel 3升级到Laravel 4)。对于访问规则的单元测试,我需要能够以另一个用户的身份调用 Authority :: can()

Laravel 3 Authority中,我使用 as_user()方法:

Authority::as_user($user);
$this->assertTrue(Authority::cannot('read', 'Notifications')); //true

Authority::as_user($superuser);
$this->assertTrue(Authority::can('read', 'Notifications')); //true

Laravel 4 Authority中,某些语法/ API已更改, as_user()不再存在。我已经尝试了两种选择,但我没有得到预期的结果。

尝试1(使用Auth :: login()切换用户):

Auth::login($user);
$this->assertTrue(Authority::cannot('read', 'Notifications')); //true
Auth::logout();

Auth::login($superuser);
$this->assertTrue(Authority::can('read', 'Notifications')); //false (wrong!)
Auth::logout();

在测试中打印 Auth :: user() - > name 表示用户已切换。但是在 Authority :: can()函数中打印 $ this-> getCurrentUser() - > name 作为黑客行为显示用户未在此范围内切换(因此错误的结果)。

尝试2 :(使用Authority :: setCurrentUser()切换用户)

Authority::setCurrentUser($user);
$this->assertTrue(Authority::cannot('read', 'Notifications')); 

Authority::setCurrentUser($superuser);
$this->assertTrue(Authority::can('read', 'Notifications')); 

//exception!

但在这种情况下,我得到一个例外:

Trying to get property of non-object
/var/www/project/app/config/packages/machuga/authority-l4/config.php:9

发生异常的Authority配置文件中的第9行表明当前用户未按预期设置:

8: $user = $authority->getCurrentUser();
9: if(count($user->roles) === 0) return false; 

对于正常的应用程序使用(即不在单元测试中切换用户),权限似乎表现得符合预期。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

Laravel 4 Authority模块(Matthew Machuga)的作者建议对新的权威实例进行测试(注意:不是外观)。这还需要重新加载规则集:

$rules = Config::get('authority-l4::initialize', null);

$authority = new Authority\Authority($user);
$rules($authority);
$this->assertTrue(Authority::cannot('read', 'Notifications')); //true

$authority = new Authority\Authority($superuser);
$rules($authority);
$this->assertTrue(Authority::can('read', 'Notifications')); //true

可以在Laravel forum上看到完整的讨论。