在使用laravel和socialite获取信息后强制用户填写表单

时间:2017-06-27 09:24:22

标签: php laravel eloquent laravel-socialite

如何在用google或facebook登录后强制用户填写表单。我使用laravel 5.4与社交。在我的应用程序中,我想允许谷歌和Facebook登录,但用户也可以创建一个标准用户。当使用其中一个社交提供商(facebook或google)登录时,我希望用户填写表单中的其他字段以完成注册。

handleProviderCallback:

public function handleProviderCallback($provider)
{
    try{
        $socialUser = Socialite::driver($provider)->stateless()->user();
    }catch (Exception $e){
        return redirect('/');
    }

    // check if we have logged PROVIDER
    $socialProvider = Social::where('provider_id', $socialUser->getId())->first();

    // if we don`t have a provider create a user and provider
    if(!$socialProvider){

        // i want the user to go back in the form and finish the registration 
        return view('auth.socials')->with('socialUser', $socialUser)->with('provider', $provider);

    }
    else{
        // return the user
        $user = $socialProvider->user;
    }

    // log the user in our app :)
    auth()->login($user);
    return redirect('/home');

问题是提交表单时我得到一个例外:

Client error: `POST https://accounts.google.com/o/oauth2/token` resulted in 
   a `400 Bad Request` response:
{
  "error" : "invalid_grant",
  "error_description" : "Invalid code."
}

如果我像这样使用方法handleProviderCallback:

 public function handleProviderCallback($provider)
{
    try{
        $socialUser = Socialite::driver($provider)->stateless()->user();
    }catch (Exception $e){
        return redirect('/');
    }

    // check if we have logged PROVIDER
    $socialProvider = Social::where('provider_id', $socialUser->getId())->first();

    // if we don`t have a provider create a user and provider
    if(!$socialProvider){
        $user = User::firstOrCreate(
            ['email' => $socialUser->getEmail()],
            // i have to manualy add the missing fields
            ['name' => $socialUser->getName(), 'forename' => 'test', 'password' => '' ,'address' => 'adasda', 'country' => 'asasfasf', 'town' => 'asfasfsfsfs',  'legal_person' => '0', 'newsletter' => '1', 'phone' => '1235241521']

        );          

        // add provider for this user
        $user->socials()->create(
            ['provider_id' => $socialUser->getId(), 'provider' => $provider]
        );
    }
    else{
        // return the user
        $user = $socialProvider->user;
    }

    // log the user in our app :)
    auth()->login($user);
    return redirect('/home');
}

用户登录,但正如您所看到的,我必须手动在firstOrCreate方法中插入缺少的字段(这些在users表中是必需的)

有任何建议怎么做?

0 个答案:

没有答案