laravellaravel-socialitelaravel-5.4

Dynamic social app credentials in socialite package in Laravel


I'm trying to build a multi tenant app, where I have configured the database, the views folder, I know there must be some way out to configure the credentials of social app login for socialite. Well I tried few things to set it dynamically.

STEP 1

I created a class with the name of socialite in a separate folder and when the social login is called I'm implementing the following in my controller:

public function redirectSocialLogin()
{
    $social = new SocialiteProvider();
    $fb = $social->makeFacebookDriver();
    return $fb->redirect();
}

and while callback I used following:

public function callbackSocialLogin($media)
{
    $user = Socialite::driver($media)->user();
    $data['name'] = $user->getName();
    $data['email'] = $user->getEmail();
    dd($data);
}

In my class I've following codes:

public function makeFacebookDriver()
{
    $config['client_id'] = 'XXXXXXXXXXXXXXX';
    $config['client_secret'] = 'XXXXXXXXXXXXXXX';
    $config['redirect'] = 'http://XXXXXXXXXXXX/auth/facebook/callback';
    return  Socialite::buildProvider('\Laravel\Socialite\Two\FacebookProvider', $config);
}

It redirects perfectly to the social page but while getting a callback I'm getting an error, It again fetches the services.php file for configuration and doesn't get any.

STEP 2

I made a ServiceProvider under the name of SocialiteServiceProvider and extended the core SocialiteServiceProvider and placed the following codes:

protected function createFacebookDriver()
{
    $config['client_id'] = 'XXXXXXXXXXXXXXX';
    $config['client_secret'] = 'XXXXXXXXXXXXXXXXXXXX';
    $config['redirect'] = 'http://XXXXXXXXXXX/auth/facebook/callback';

    return $this->buildProvider(
        'Laravel\Socialite\Two\FacebookProvider', $config
    );
}

But again it throws back error which says driver is not setup. Help me out in this. Thanks.


Solution

  • In your STEP 1, update the callback as below mentioned & try. $media is actually Request. So when initialising Socialite::driver($media) you are actually passing Request where you have to pass Facebook.

    public function callbackSocialLogin(Request $request) {
        $fbDriver = (new SocialiteProvider())->makeFacebookDriver();
    
        $user = $fbDriver->user();
        $data['name']  = $user->getName();
        $data['email'] = $user->getEmail();
        ...
    }