Laravel Socialite记得我

时间:2017-01-02 17:36:28

标签: php laravel laravel-socialite

我正在使用Socialite进行用户登录,我想设置remember_token以便在用户登录社交网站时记住该用户。

现在我有以下服务来创建或登录用户:

class SocialAccountService {

    public function createOrGetUser(ProviderUser $providerUser) {

        $account = SocialAccount::whereProvider('google')
            ->whereProviderUserId($providerUser->getId())
            ->first();

        if ($account) {
            return $account->user;
        } else {
            $account = new SocialAccount([
                'provider_user_id' => $providerUser->getId(),
                'provider' => 'google'
            ]);

            $user = User::whereEmail($providerUser->getEmail())->first();
            if (!$user) {
                $user = User::create([
                    'email' => $providerUser->getEmail(),
                    'name' => $providerUser->getName()
                ]);
            }
            $account->user()->associate($user);
            $account->save();
            return $user;
        }
    }
}

使用以下控制器调用它:

class AuthController extends Controller {

    public function logout() {
        Auth::logout();
        return redirect('/');
    }

    public function redirectToGoogle() {
        return Socialite::driver('google')->redirect();
    }

    public function handleGoogleCallback(SocialAccountService $service) {
        $user = $service->createOrGetUser(Socialite::driver('google')->user());
        auth()->login($user);
        return redirect('/');
    }
}

问题在于,当用户回来时,他们不会被记住并自动登录。如何使用Socialite进行此操作?

1 个答案:

答案 0 :(得分:3)

根据documentation,将true作为login()的第二个参数传递将设置记忆令牌。

// Login and "remember" the given user... Auth::login($user, true);

Auth外观和auth()辅助函数访问同一个对象。