mardi 28 août 2018

Use OAuth middleware to get user inside Laravel model

I'm trying to eager load my Tutorials model with a where clause based on the logged in User's profile. I'm using Laravel 5.1 with Lucadegasperi's OAuth 2.

I want to find only the tutorials which belong to user profile ID 1. To do this, I first request an access token, then log the user into the application via DHC:

GET http://myapi.localhost/1.0/login
Headers: Authorization: Bearer xyZ... // valid token

Then make the request for the tutorials:

GET http://myapi.localhost/1.0/tutorials/1
Headers: Authorization: Bearer xyZ... // valid token

But the response says there's no valid token? Yet, when I perform login in AuthController.php, OAuth2 middleware's Authorizer::getResourceOwnerId() is able to locate the user. But in the Tutorial model, I get error:

NoActiveAccessTokenException in Authorizer.php line 104:

Tried to access session data without an active access token

AuthController.php:

...
public function login(Request $request)
{
    $user = User::find(Authorizer::getResourceOwnerId()); // Finds user

    if (!is_null($user)) {
        Auth::login($user);
        $request->session()->put('user', Auth::user());
        return $user;
    }

    return response()->json(['status' => 500, 'message' => 'Invalid email!']);
}
...

Tutorial Model:

use LucaDegasperi\OAuth2Server\Facades\Authorizer;
use Illuminate\Support\Facades\Auth;
use App\User;

class Tutorial extends BaseModel
{
     public function profiles()
     {
         $user = User::find(Authorizer::getResourceOwnerId()); // Throws error
         $user = Auth::user(); // Works fine

         return $this->belongsToMany(Profile::class, 'profile_tutorials')
             ->where('profile_id', '=', $user->profiles[0]->id)
             ->withPivot('view_count')
             ->withTimestamps();
     }
     ...
}

How can I use the OAuth middleware to get the user within a model?

Note: This works fine in the model when I use $user = Auth::user();, but don't see why I can't use the Authorizer.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire