0

I'm using the Authority package for access control in my Laravel application (which I'm upgrading from Laravel 3 to Laravel 4). For unit testing of the access rules, I need to be able to call Authority::can() as another user.

In Laravel 3 Authority, I used the as_user() method:

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

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

In Laravel 4 Authority, some of the syntax/APIs have changed and as_user() no longer exists. I've tried two alternatives but I'm not getting expected results.

Attempt 1 (use Auth::login() to switch user):

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();

Printing Auth::user()->name in the test shows the user has been switched. But printing $this->getCurrentUser()->name as a hack inside the Authority::can() function shows the user is not being switched within this scope (hence the wrong result).

Attempt 2: (use Authority::setCurrentUser() to switch user)

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

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

//exception!

But in this case I get an exception:

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

Line 9 in the Authority config file where the exception happens suggests the current user is not being set as expected:

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

For normal application usage (i.e. not switching users within unit tests) Authority appears to be behaving as expected.

What am I doing wrong?

1 Answer 1

0

The author of the Laravel 4 Authority module (Matthew Machuga) recommended testing against a new instance of Authority (NB: not the façade). This also requires reloading the ruleset:

$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

The full discussion can be seen on the Laravel forum.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.