This is the error. Not very helpfull:
http://imgur.com/TD84G0W
This is the controller. The redirect method redirects to the social provider for the user the accept the login. The callback method handels the callback where is user is created etc.
class SocialLoginController extends Controller
{
protected $social;
public function __construct(SocialAuthentication $social)
{
$this->social = $social;
}
public function redirect($service)
{
return $this->social->redirectToSocialProvider($service);
}
public function callback($service)
{
$user = $this->social->registerUsingService($service);
auth()->login($user, true);
event(new UserLoggedIn($user, session()->pull('item_tokens')));
return redirect()->route('users.show');
}
}
This is the logic:
class SocialAuthentication
{
protected $parser;
public function __construct(Parser $parser)
{
$this->parser = $parser;
}
public function redirectToSocialProvider($service)
{
return Socialite::driver($service)->redirect();
}
public function registerUsingService($service)
{
$serviceUser = Socialite::driver($service)->user();
$user = $this->getExistingUser($serviceUser, $service);
if ( ! $user) {
$user = $this->createUser($serviceUser);
}
if ($this->needsToCreateSocial($user, $service)) {
$this->createSocialLink($user, $service, $serviceUser);
}
return $user;
}
protected function createUser($serviceUser)
{
return User::create([
'email' => $serviceUser->getEmail(),
'first_name' => $this->parser->parse($serviceUser->getName())->getFirstName(),
'last_name' => $this->parser->parse($serviceUser->getName())->getLastName(),
'confirmed' => true
]);
}
protected function createSocialLink($user, $service, $serviceUser)
{
$user->social()->create([
'social_id' => $serviceUser->getId(),
'service' => $service,
]);
}
protected function needsToCreateSocial(User $user, $service)
{
return ! $user->hasSocialLinked($service);
}
protected function getExistingUser($serviceUser, $service)
{
return User::where('email', $serviceUser->getEmail())->orWhereHas('social', function ($q) use ($serviceUser, $service) {
$q->where('social_id', $serviceUser->getId())->where('service', $service);
})->first();
}
}
web.php
Route::get('login/{service}', ['as' => 'social_login', 'uses' => 'SocialLoginController@redirect']);
Route::get('login/{service}/callback', 'SocialLoginController@callback');