Reputation: 297
I setup a middleware on a route so that if anyone browses to it, they should be logged to facebook first, if not they'll be redirected to facebook:
Route::get( '/events/facebook', 'EventsController@facebookEvents' )->middleware('CheckFB');
It works fine, however, now the route keeps redirecting back to Facebook over and over.
This is the middleware:
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $provider=null)
{
$provider = 'facebook';
$this->validateProvider($provider);
if ($provider === 'facebook') {
return Socialite::driver($provider)->scopes([
'email',
'public_profile',
'rsvp_event',
'user_birthday',
'user_events',
'user_friends',
])->redirect();
}
return Socialite::driver($provider)->redirect();
}
What I want is that if the user is already logged, he shouldn't be redirected! only the first once.
I tried this:
$user = Socialite::driver('facebook')->user();
But it makes this error:
GuzzleHttp \ Exception \ ClientException (400) Client error:
POST https://graph.facebook.com/v2.10/oauth/access_token
resulted in a400 Bad Request
response: {"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100,"fbtrace_id":"*** (truncated...)
Upvotes: 1
Views: 1226
Reputation: 112
Im using Auth::check(); to know if an user is logged
use App\User;
use Auth;
use Socialite;
use Redirect;
The method recives as param a $service in this case Facebook
//route to handle the callback
Route::get('/callback/{service}', 'SocialAuthController@handleProviderCallback');
public function handleProviderCallback($service)
{
if(Auth::check())//if user is logged
{
$user_id = Auth::id(); //you get the user ID
$authUser = User::where('id', $user_id)->first(); //you should find the user in the User table
$user_service = $authUser->service; //I saved in the database the service used to log in, so I call it
return view ( 'home' )->withDetails ( $authUser )->withService ( $user_service ); //then I return the view with the details
}else //if user is not login in
{
$user = Socialite::driver( $service )->user();
$authUser = $this->findOrCreateUser($user, $service);//personal method to know if the user is new or it is already saved on DB
Auth::login($authUser, true);//Login if the authUser return is true
return view ( 'home' )->withDetails ( $user )->withService ( $service );
}
Hope it works for you!
Upvotes: 0