Use Multiple Auth Guards for One Policy

I implemented several out-guards in the Laravel 5.4 project (one of administrators and another for regular users). So far, this has worked successfully, and both administrators and users can log in. Now I'm trying to implement a Policy class that works for both Auth guards. This is because I have certain models that I want all administrators to edit, and only users who own the model to be able to edit. Therefore, I defined the policy using this method.

App \ Policies \ ModelPolicy

public function update(User $user, Model $model)
{
    if ($user->id === $model->user_id) {
        return true;
    }

    if (Auth::guard('admin')->check()) {
        return true;
    }

    return false;
}

Then in any controller method that I have for my model:

App \ Http \ Controllers \ ModelController

public function update(Model $model)
{
    $this->authorize('update', $model);

    // update model
}

, . , , ( ). , Policy -, , Auth::check() . , ( ), .

, , , -admin:

public function update(Model $model)
{
    if (!Auth::guard('admin')->check()) {
        $this->authorize('update', $model);
    }

    // update model
}

- , , . , , .

?

+4
2

authorize , Guard Guard . $user, , - , .

/Http//Controller.php

use Auth

class Controller extends BaseController
{
    use DispatchesJobs, ValidatesRequests;
    use AuthorizesRequests {
        authorize as protected baseAuthorize;
    }

    public function authorize($ability, $arguments = [])
    {
        if (Auth::guard('admin')->check()) {
            Auth::shouldUse('admin');
        }

        $this->baseAuthorize($ability, $arguments);
    }
}

, , , , - . t Auth::check(), , $user , .

App\Policies\ModelPolicy

use App\User;

public function update($user, Model $model)
{
    if ($user instanceof User) {
        return $user->id == $userId;
    }

    // Is an Admin
    return true;
}

Auth, , , .

0

"authorize" (/app/Http/Controllers/Controller.php):

class Controller extends BaseController
{
    use AuthorizesResources, DispatchesJobs, ValidatesRequests;
    use AuthorizesRequests {
        authorize as protected laravelAuthorize;
    }

    public function authorize($ability, $arguments = [])
    {
        if (!Auth::guard('admin')->check()) {
            $this->laravelAuthorize($ability, $arguments);
        }
    }
}
0

Source: https://habr.com/ru/post/1682247/


All Articles