简体   繁体   中英

Laravel 5 and Socialite, how to save in the database and log-in

After reading: http://laravel.com/docs/5.0/authentication I was able to retrieve the user details from the OAuth provider (Facebook) using Socialite:

$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();

But I couldn't find any further documentation on how to save the user in the database or log the user in.

I want to do the equivalent to:

Auth::attempt(['email' => $email, 'password' => $password])

But for the details retrieved via Socialite (I don't have a password)

Can you please show me an example on using "Auth" with user data retrieved via Socialite?

Add to " users " table new column: facebook_user_id . Every time when user tries to login through Facebook, Facebook will return the same user id.

public function handleProviderCallback($provider)
{
    $socialize_user = Socialize::with($provider)->user();
    $facebook_user_id = $socialize_user->getId(); // unique facebook user id

    $user = User::where('facebook_user_id', $facebook_user_id)->first();

    // register (if no user)
    if (!$user) {
        $user = new User;
        $user->facebook_id = $facebook_user_id;
        $user->save();
    }

    // login
    Auth::loginUsingId($user->id);

    return redirect('/');
}

How Laravel Socialite works?

public function redirectToProvider()
{
   // 1. with this method you redirect user to facebook, twitter... to get permission to use user data
   return Socialize::with('github')->redirect();
}

public function handleProviderCallback()
{
   // 2. facebook, twitter... redirects user here, where you write code to log in user
   $user = Socialize::with('github')->user();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM