1 <?php namespace Oxbow\Services;
3 use Laravel\Socialite\Contracts\Factory as Socialite;
4 use Oxbow\Exceptions\SocialDriverNotConfigured;
5 use Oxbow\Exceptions\SocialSignInException;
6 use Oxbow\Repos\UserRepo;
7 use Oxbow\SocialAccount;
10 class SocialAuthService
15 protected $socialAccount;
17 protected $validSocialDrivers = ['google', 'github'];
20 * SocialAuthService constructor.
21 * @param UserRepo $userRepo
22 * @param Socialite $socialite
23 * @param SocialAccount $socialAccount
25 public function __construct(UserRepo $userRepo, Socialite $socialite, SocialAccount $socialAccount)
27 $this->userRepo = $userRepo;
28 $this->socialite = $socialite;
29 $this->socialAccount = $socialAccount;
33 * Start the social login path.
34 * @param $socialDriver
35 * @return \Symfony\Component\HttpFoundation\RedirectResponse
36 * @throws SocialDriverNotConfigured
38 public function startLogIn($socialDriver)
40 $driver = $this->validateDriver($socialDriver);
41 return $this->socialite->driver($driver)->redirect();
45 * Get a user from socialite after a oAuth callback.
47 * @param $socialDriver
49 * @throws SocialDriverNotConfigured
50 * @throws SocialSignInException
52 public function handleCallback($socialDriver)
54 $driver = $this->validateDriver($socialDriver);
56 // Get user details from social driver
57 $socialUser = $this->socialite->driver($driver)->user();
58 $socialId = $socialUser->getId();
60 // Get any attached social accounts or users
61 $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
62 $user = $this->userRepo->getByEmail($socialUser->getEmail());
63 $isLoggedIn = \Auth::check();
64 $currentUser = \Auth::user();
66 // When a user is not logged in but a matching SocialAccount exists,
67 // Log the user found on the SocialAccount into the application.
68 if (!$isLoggedIn && $socialAccount !== null) {
69 return $this->logUserIn($socialAccount->user);
72 // When a user is logged in but the social account does not exist,
73 // Create the social account and attach it to the user & redirect to the profile page.
74 if ($isLoggedIn && $socialAccount === null) {
75 $this->fillSocialAccount($socialDriver, $socialUser);
76 $currentUser->socialAccounts()->save($this->socialAccount);
77 \Session::flash('success', title_case($socialDriver) . ' account was successfully attached to your profile.');
78 return redirect($currentUser->getEditUrl());
81 // When a user is logged in and the social account exists and is already linked to the current user.
82 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
83 \Session::flash('error', 'This ' . title_case($socialDriver) . ' account is already attached to your profile.');
84 return redirect($currentUser->getEditUrl());
87 // When a user is logged in, A social account exists but the users do not match.
88 // Change the user that the social account is assigned to.
89 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
90 $socialAccount->user_id = $currentUser->id;
91 $socialAccount->save();
92 \Session::flash('success', 'This ' . title_case($socialDriver) . ' account is now attached to your profile.');
96 throw new SocialSignInException('A system user with the email ' . $socialUser->getEmail() .
97 ' was not found and this ' . $socialDriver . ' account is not linked to any users.', '/login');
99 return $this->authenticateUserWithNewSocialAccount($user, $socialUser, $socialUser);
103 * Logs a user in and creates a new social account entry for future usage.
105 * @param string $socialDriver
106 * @param \Laravel\Socialite\Contracts\User $socialUser
107 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
109 private function authenticateUserWithNewSocialAccount($user, $socialDriver, $socialUser)
111 $this->fillSocialAccount($socialDriver, $socialUser);
112 $user->socialAccounts()->save($this->socialAccount);
113 return $this->logUserIn($user);
116 private function logUserIn($user)
119 return redirect('/');
123 * Ensure the social driver is correct and supported.
125 * @param $socialDriver
127 * @throws SocialDriverNotConfigured
129 private function validateDriver($socialDriver)
131 $driver = trim(strtolower($socialDriver));
133 if (!in_array($driver, $this->validSocialDrivers)) abort(404, 'Social Driver Not Found');
134 if (!$this->checkDriverConfigured($driver)) throw new SocialDriverNotConfigured;
140 * Check a social driver has been configured correctly.
144 private function checkDriverConfigured($driver)
146 $upperName = strtoupper($driver);
147 $config = [env($upperName . '_APP_ID', false), env($upperName . '_APP_SECRET', false), env('APP_URL', false)];
148 return (!in_array(false, $config) && !in_array(null, $config));
152 * Gets the names of the active social drivers.
155 public function getActiveDrivers()
158 foreach ($this->validSocialDrivers as $driverName) {
159 if ($this->checkDriverConfigured($driverName)) {
160 $activeDrivers[$driverName] = true;
163 return $activeDrivers;
167 * @param $socialDriver
170 private function fillSocialAccount($socialDriver, $socialUser)
172 $this->socialAccount->fill([
173 'driver' => $socialDriver,
174 'driver_id' => $socialUser->getId(),
175 'avatar' => $socialUser->getAvatar()
180 * Detach a social account from a user.
181 * @param $socialDriver
182 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
184 public function detachSocialAccount($socialDriver)
186 \Auth::user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
187 \Session::flash('success', $socialDriver . ' account successfully detached');
188 return redirect(\Auth::user()->getEditUrl());