Search code examples
phpapilaravellaravel-5.1middleware

Executing Service Provider after Middleware


I'm using jwt-auth, but I need to do something with service provider (Policy stuffs) and I need to get the logged user.

The "boot" function is not working for me. Any idea how I can run the service provider after jwt-auth ?

<?php

namespace App\Providers;

use CareerTown\Privileges\PrivilegesHolder;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application authentication / authorization services.
     *
     * @param  \Illuminate\Contracts\Auth\Access\Gate $gate
     *  parent::registerPolicies($gate);
     *
     * @return void
     */
    public function boot(GateContract $gate)
    {
        parent::boot($gate);

        if ( ! auth()->check()) {
            return false;
        }
        $userPrivileges = auth()->user()->privileges;

        $privilegesHolder = PrivilegesHolder::getInstance();

        foreach ($userPrivileges as $up) {
            if ($privilege = $privilegesHolder->getLevel($up->level)) {
                $privileges = array_dot($privilege->getPrivileges());
                foreach ($privileges as $key => $value) {
                    $gate->define($key.$up->company->key, function ($user, $object = null) use ($value, $up) {

                        if ($object->profile->user_id == $user->id) {
                            return true;
                        }
                        if ($object->id == $up->company_id) {
                            return boolval($value);
                        }

                        return false;
                    });
                }
            }
        }
    }
}

Solution

  • You could extend the jwt-auth middleware and overwrite the handle function with your service provider stuff. Or you could register your own middleware to check your policy after jwt-auth middleware.

    Maybe this hint helps