mercredi 15 février 2017

Way to use Config::set() twice in a function

I have googled and stackoverflowed (if you may) for this question, and couldn't find a succint enough answer to it: (some ref: Laravel 4: when using Config::set to change auth.model then Auth::user() not work , Laravel 5.2 how to use config::set in middleware)

How can I successfully set a variable twice at runtime with Config::set() in Laravel 5.2.*?

Here is an example of what I tried to achieve:

I have two tables companies and users (they both login from different routes with JWTAuth). Now I want to fetch all computers record at this single route Route::get('/computers')

Now the issue have is that I want to use the same middleware to do that, but I want to ensure that any of those users (i.e company or user) is authenticated before they can access this resource

Here is what I have attempted trying to use Config::set() in my middleware:

//all.auth middleware
public function handle($request, Closure $next)
{
    Config::set('auth.providers.users.model', \App\Company::class);
    Config::set('jwt.user', \App\Company::class);

      //check if the request is for company
    if($company = JWTAuth::toUser(($request->has('token')) ? $request->token : $request->bearerToken())) 
    {
        return ['COMPANY' => $company];
    }

    //Unfortunately its not company, lets try users

    Config::set('auth.providers.users.model', \App\User::class);
    Config::set('jwt.user', \App\User::class);

    if($user = JWTAuth::toUser(($request->has('token')) ? $request->token : $request->bearerToken())) 
    {
        return ['USER' => $user];
    }
    throw new NotFoundHttpException('Your account could not be found.');
    ...............
}

Now, the behaviour I noticed is that it successfully changed the model JWT would use to Company but didn't change it to User in case the token sent with the request is for a User.

I will be grateful if someone can help out, to understand at least if this is possible or not.

If there is a need to provide more explanations, I am ready to do that.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2kx61CM
via IFTTT

Aucun commentaire:

Enregistrer un commentaire