Laravel 5 和 Socialite,如何在数据库中保存并登录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28470551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 and Socialite, how to save in the database and log-in
提问by Agu Dondo
After reading: http://laravel.com/docs/5.0/authenticationI was able to retrieve the user details from the OAuth provider (Facebook) using Socialite:
阅读后:http: //laravel.com/docs/5.0/authentication我能够使用 Socialite 从 OAuth 提供商 (Facebook) 检索用户详细信息:
$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)
但是对于通过 Socialite 检索到的详细信息(我没有密码)
Can you please show me an example on using "Auth" with user data retrieved via Socialite?
你能告诉我一个关于使用“Auth”和通过 Socialite 检索的用户数据的例子吗?
回答by Mantas D
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.
添加到“用户”表新列:facebook_user_id。每次当用户尝试通过 Facebook 登录时,Facebook 都会返回相同的用户 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?
Laravel Socialite 如何运作?
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();
}