Andy Holmes
Andy Holmes

Reputation: 8077

Laravel 5.1 and Socialite Questions

This isn't a post about a problem I'm having right now. I'm planning on using the Laravel Socialite plugin in my App, I already have a fully working login/register system using Laravel's built in Auth system but I'm wondering if there is a good way to allow users that already have their accounts in my app to link their social profiles to the already existing account?

The plan would be that they can login with their username and password or any of their social profiles. All the research I've done so far explains how to set up Socialite and utilise that data for registering/logging in new users, however I can't find anything to marry the two together.

I'm not looking for anyone to write this for me so please don't get confused by this post.

Thanks for any info, Andy

Upvotes: 0

Views: 147

Answers (1)

Chris
Chris

Reputation: 3795

Absolutely.

I have FB and Twitter OAuth on one site. The way I do it is by adding oauth_facebook_id and oauth_twitter_id columns to the users table (as well as an avatar column, if you want that).

I have the routes set up as /auth/{provider} and /auth/{provider}/callback, so /auth/facebook and /auth/facebook/callback for example.

In my handleProviderCallback($provider) method on my AuthController, I grab the returned user's details and check to see if they already exist in my database with their email, Facebook OAuth ID or Twitter OAuth ID. If they exist, I set their email, OAuth IDs and their avatar, if they don't exist I create them. Then I log them in.

    $user = Socialite::driver($provider)->user();

    $user_query = User::where('email', $user->email)
        ->orWhere('oauth_facebook_id', $user->id)
        ->orWhere('oauth_twitter_id', $user->id)
        ->get();

    if($user_query->count() > 0) {

        $the_user = $user_query->first();

        if($provider === 'facebook') {
            $the_user->oauth_facebook_id = $user->id;
        }

        if($provider === 'twitter') {
            $the_user->oauth_twitter_id = $user->id;
        }

        $the_user->avatar = $user->avatar;

        $the_user->save();

        \Auth::login($the_user, true);

        return redirect('/');
    }

    $new_user = User::create([
        'name' => $user->name,
        'email' => $user->email,
        'oauth_facebook_id' => $provider === 'facebook' ? $user->id : NULL,
        'oauth_twitter_id' => $provider === 'twitter' ? $user->id : NULL,
        'avatar' => $user->avatar
    ]);

    \Auth::login($new_user, true);

    return redirect('/');

Hopefully this helps you make sense of how to do it.

Upvotes: 2

Related Questions