Skip to content

Instantly share code, notes, and snippets.

@pbelyaev
Last active August 26, 2022 23:32
Show Gist options
  • Save pbelyaev/e396d5c03cb32ac31959fa2038521f7b to your computer and use it in GitHub Desktop.
Save pbelyaev/e396d5c03cb32ac31959fa2038521f7b to your computer and use it in GitHub Desktop.
Laravel 5.2 Socialite Middleware Example
<?php
/*
* SocialiteFacebookController is just a stub.
* I'm not really sure how to create a route without controller or closure.
* Please, feel free to share this information :)
*/
Route::get('auth/facebook', [
'middleware' => 'App\Http\Middleware\SocialiteRedirectToProviderMiddleware:facebook',
'uses' => 'SocialiteFacebookController@index'
]);
Route::get('auth/facebook/callback', [
'middleware' => 'App\Http\Middleware\SocialiteCallbackMiddleware:facebook',
'uses' => 'SocialiteFacebookController@store'
]);
<?php
namespace App\Http\Middleware;
use Closure;
use Laravel\Socialite\Facades\Socialite;
class SocialiteCallbackMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string $providerDriver
*
* @return mixed
*/
public function handle($request, Closure $next, $providerDriver = null)
{
$socialite = Socialite::driver($providerDriver)->user();
/**
* You can do whatever you want. All user's data are in $socialite.
*
* Such as:
* $socialite->getId();
* $socialite->getEmail();
* $socialite->getName();
* $socialite->getAvatar();
* and etc.
*/
return $next($request);
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use Laravel\Socialite\Facades\Socialite;
class SocialiteRedirectToProviderMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string $providerDriver
*
* @return mixed
*/
public function handle($request, Closure $next, $providerDriver = null)
{
/**
* Redirect authenticated user to homepage
*/
if (auth()->check()) {
return redirect('/');
}
/**
* Making redirect through socialite driver
*/
return Socialite::driver($providerDriver)->redirect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment