+ $socialId = $socialUser->getId();
+
+ // Get any attached social accounts or users
+ $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
+ $isLoggedIn = auth()->check();
+ $currentUser = user();
+
+ // When a user is not logged in and a matching SocialAccount exists,
+ // Simply log the user 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', trans('settings.users_social_connected', ['socialAccount' => title_case($socialDriver)]));
+ 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', trans('errors.social_account_existing', ['socialAccount' => title_case($socialDriver)]));
+ return redirect($currentUser->getEditUrl());
+ }