Check the guard of logged in user #1772
Replies: 8 comments
-
@Daniyal-Javani I'd like to see a future version of this package honor the guard that the user has been assigned during their login/authentication. A PR which updates that functionality would be welcome. Ideally with tests. |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
@musapinar Yes, but the next line overrides it with the model's guard, which leaves many people confused about why the package checks against a different guard than the one the user is using (they would say "it checks against the wrong guard"). It's a complex change to make, because it's messing with a matrix of values created by conflating authorization with authentication. I'd rather remove all mention of guards altogether, and let the application implement guard-related rules. |
Beta Was this translation helpful? Give feedback.
-
@musapinar I think the first starting point though is reviewing where it's not working as desired, writing the tests for that, and then getting those tests to pass. |
Beta Was this translation helpful? Give feedback.
-
OK, what about this test |
Beta Was this translation helpful? Give feedback.
-
@Daniyal-Javani @drbyte I'm afraid I can't/won't help much on this one as I do not make use of that guard feature at all. I enforce Not sure how elegant the following is, but it passes all tests green : ->keys()
->filter(function ($guard) {
return request()->user() ? auth()->guard($guard)->check() : true;
}); https://github.com/spatie/laravel-permission/blob/master/src/Guard.php#L42 Good luck. |
Beta Was this translation helpful? Give feedback.
-
Hi, when you release this patch? Thank's |
Beta Was this translation helpful? Give feedback.
-
If you are looking for a solution that works without this feature: You can set up a second user Model, such as App\User and App\ApiUser. class ApiUser extends Authenticatable {
use HasRoles;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'users';
/**
* The guard that this user should be authenticated with.
*/
protected $guard_name = 'api';
} class User extends Authenticatable {
use HasRoles;
} 'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'apiusers',
'hash' => false,
],
], 'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'apiusers' => [
'driver' => 'eloquent',
'model' => App\Models\ApiUser::class,
],
], I was able to get it working like this, maybe someone will find this helpful. |
Beta Was this translation helpful? Give feedback.
-
Shouldn't it check the guard of logged in user?
like this
How can I check based on the guard of user?
Originally posted by @Daniyal-Javani in #892 (comment)
Beta Was this translation helpful? Give feedback.
All reactions