Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Socialite Facebook Login Error handling on callback after user cancels app request

I have a Laravel 5 web app with Socialite to login my user by using Facebook account.

This is my callback function:

public function callback(SocialAccountService $service)
{

    $user = $service->createOrGetUser(Socialite::driver('facebook')->user());

    auth()->login($user);

    return redirect()->to('/home');
}

This is my SocialAccountService, basically the function returns the user if existing or creates a new one:

class SocialAccountService
{
    public function createOrGetUser(ProviderUser $providerUser)
    {
        $account = SocialAccount::whereProvider('facebook')
            ->whereProviderUserId($providerUser->getId())
            ->first();

        if ($account) {
            return $account->user;
        } else {

            $account = new SocialAccount([
                'provider_user_id' => $providerUser->getId(),
                'provider' => 'facebook'
            ]);

            $user = User::whereEmail($providerUser->getEmail())->first();

            if (!$user) {

                $user = User::create([
                    'email' => $providerUser->getEmail(),
                    'name' => $providerUser->getName(),
                ]);
            }

            $account->user()->associate($user);
            $account->save();

            return $user;

        }

    }
}

Now the problem is, I am able to make my user login successfully via Facebook, but when the user clicks Cancel on the FB dialog for permission, it breaks.

Callback Error on Facebook app permission denial

How can I handle this error? I can see the error message in URL box, but don't know to handle them.

P.S I am fairly new to Laravel and Socialite

like image 863
krozaine Avatar asked Jun 01 '16 11:06

krozaine


2 Answers

in the callback(...) method you can check for presense of the 'code' input field and if it is not there redirect to back to login page with errors.

Example:

function callback(SocialAccountService $service ,Request $request) {
    if (! $request->input('code')) {
        return redirect('login')->withErrors('Login failed: '.$request->input('error').' - '.$request->input('error_reason'));
    }

    // rest of your code
}    
like image 182
Nicol Bolas Avatar answered Nov 14 '22 15:11

Nicol Bolas


Try catch is the best practice(it catches all exception)

 try
{
    $userSocial =Socialite::driver('facebook')
    ->stateless()->user();
    dd($userSocial);
 }
catch (\Throwable $e) { 

//handle error here for php 7 or 8  

  } catch (\Exception $e) { 
  // for php 5
  handle error here 

  }
like image 25
ßãlãjî Avatar answered Nov 14 '22 13:11

ßãlãjî