+ $isLoggedIn = \Auth::check();
+ $currentUser = \Auth::user();
+
+ // When a user is not logged in but a matching SocialAccount exists,
+ // Log the user found on the SocialAccount into the application.
+ if (!$isLoggedIn && $socialAccount !== null) {
+ return $this->logUserIn($socialAccount->user);
+ }
+
+ // When a user is logged in but the social account does not exist,
+ // Create the social account and attach it to the user & redirect to the profile page.
+ if ($isLoggedIn && $socialAccount === null) {
+ $this->fillSocialAccount($socialDriver, $socialUser);
+ $currentUser->socialAccounts()->save($this->socialAccount);
+ \Session::flash('success', title_case($socialDriver) . ' account was successfully attached to your profile.');
+ return redirect($currentUser->getEditUrl());
+ }
+
+ // When a user is logged in and the social account exists and is already linked to the current user.
+ if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
+ \Session::flash('error', 'This ' . title_case($socialDriver) . ' account is already attached to your profile.');
+ return redirect($currentUser->getEditUrl());
+ }
+
+ // When a user is logged in, A social account exists but the users do not match.
+ // Change the user that the social account is assigned to.
+ if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
+ $socialAccount->user_id = $currentUser->id;
+ $socialAccount->save();
+ \Session::flash('success', 'This ' . title_case($socialDriver) . ' account is now attached to your profile.');
+ }