Laravel Authorization for Multi Authentication

Asked

Viewed 198 times

0

I have an ACL app for Laravel where I have two sessions(Guards), one for users and another to admins.

The configuration of Guards auth.php file looks like this:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'admin-api' => [
            'driver' => 'token',
            'provider' => 'admins',
        ],
    ],
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => Crebs86\TrustMultiAuth\Model\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => Crebs86\TrustMultiAuth\Model\Admin::class,
        ],
    ],

The function boot() of AuthServiceProvider gets that way:

    public function boot()
{
    $this->registerPolicies();
    $permissions = Permission::with('roles')->get();
    foreach ($permissions as $permission):
        Gate::define($permission->name, function (User $user) use ($permission) {
            return $user->hasPermission($permission);
        });
    endforeach;
    Gate::before(function(User $user, $ability){
        if($user->hasAnyRoles('super-admin'))
            return true;
    });
}

As you can see I can only inject one Guard, in case the web Gate::define($permission->name, function (User $user)..., and all the logic based on access control works for the login done on model User,.

But I can’t get the Guard of the origin of the request and request the model Admin when this is the case.

2 answers

1


I found a solution during debug, editing the Authserviceprovider like this:

public function boot()
    {
        $this->registerPolicies();
        $permissions = Permission::with('roles')->select('id', 'name')->get()->toArray();
        foreach ($permissions as $permission):
            Gate::define($permission['name'], function ($user = null, $guard) use ($permission) {
                return $guard->hasPermission($permission['name']);
            });
        endforeach;
    }

Where ... $user=null is the expected standard Guard and $Guard is the Model you set when doing the check.

0

Cara I need to do the same thing, please let me know.

I have my second Guard and I also need to access the Gate for another Model

  • Hello. try what I said above! Anything ask here!

  • Cleber, show caraa!! worked but only with the option $user = null. Ai to get permission from which user was logging in I did in User Model protected $Guard = 'user'; and did the function public Function pegGuard(){ Return $this->Guard; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.