我正在尝试通过laravel社交网站登录用户。一切正常,但用户未登录!
我从Facebook得到响应,将响应保存在数据库中,然后尝试登录。
代码如下:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Two\InvalidStateException;
use Auth;
use Socialite;
use App\User;
use DB;
use Log;
public function handleProviderCallback($provider)
{
$social = Socialite::driver($provider)->user();
$findUser = User::where('email', $social->email)->first();
if ($findUser) {
// dd($findUser); **************** This returns information of the user who is trying to login through facebook
// dd(Auth::login($findUser, true)); ***************** This line returns null
if (Auth::login($findUser, true)) {
// dd(Auth::loginUsingId($findUser->id, true));
redirect()->route('dashboard');
} else {
return 'Error'; //**************** This get echoed on the screen
}
} else {
$user = new User();
$user->name = $social->name;
$user->email = $social->email;
$user->avatar = $social->avatar;
$user->provider = $provider;
$user->id = $social->id;
$user->password = bcrypt('password');
$user->save();
}
if (Auth::login($user)) {
return redirect()->intended('/home');
} else {
return 'Error';
}
}
注册和登录均无效。
答案 0 :(得分:0)
login()
方法不会返回任何内容,因此if (Auth::login($findUser, true))
将永远不会过去。
另外,可能值得使用firstOrCreate()来缩小您的方法:
public function handleProviderCallback($provider)
{
$social = Socialite::driver($provider)->user();
User::unguard();
$user = User::firstOrCreate([
'email' => $social->email,
], [
'id' => $social->id,
'name' => $social->name,
'avatar' => $social->avatar,
'provider' => $provider,
'password' => bcrypt('password'),
]);
auth()->login($user, true);
return redirect()->intended('/home');
}
如果要检查用户是否已登录,则可以使用auth()->id()
方法检索当前已验证的用户ID,然后将其与$user->id
进行比较:
if (auth()->id() !== $user->id) {
return 'Error';
}
很显然,如果您更喜欢使用Auth
门面而不是auth()
辅助函数,那么可以使用Auth::id()
而不是auth()->id()