Search code examples
laravellaravel-socialitelaravel-middleware

Laravel: Create middleware for Sociailite Auth


I'm using JavaScript to receive an access token to the user facebook account.

When I get the token, I send a request to the server with the token to get information about the user using Socialite.

$user = Socialite::driver('facebook')->userFromToken($request->token);
        return $user->getName();

Now I'm trying to group API calls that only authenticated user can make, for example /my-profile, my-data, etc...

The middleware purpose is to check if the user is authenticated for a group of API calls instead typing the same condition in all methods:

if ($user->getName()) {
...Execute...
}

Any idea how I can place the following condition for a list of routes for autehnticated users?

My condition is simple:

$user = Socialite::driver('facebook')->userFromToken($request->token);
if ($user->getName()) {
return true;
}
else { return false; }

Solution

  • Okay, First create the middleware:

    php artisan make:middleware name_of_your_middleware
    

    After that, inside the middleware file that has been created:

    public function handle($request, Closure $next)
        {
             $user = Socialite::driver('facebook')->userFromToken($request->token);
    
             if ($user->getName()) {
               return $next($request);
             }
             return redirect('some_other_route_for_error');            
        } 
    

    Then assign the middleware to the routes middelware in app/Http/Kernel.php

    protected $routeMiddleware = [
         //.......
        'name_of_your_middleware' => \Illuminate\Auth\Middleware\Authenticate::class,
    ];
    

    In your Route file (api.php):

    Route::group(['middleware'=>['name_of_your_middleware']],function(){
        //your routes
    });
    

    Hope it helps :)