1 <?php namespace BookStack\Services;
3 use BookStack\Http\Requests\Request;
4 use GuzzleHttp\Exception\ClientException;
5 use Laravel\Socialite\Contracts\Factory as Socialite;
6 use BookStack\Exceptions\SocialDriverNotConfigured;
7 use BookStack\Exceptions\SocialSignInException;
8 use BookStack\Exceptions\UserRegistrationException;
9 use BookStack\Repos\UserRepo;
10 use BookStack\SocialAccount;
12 class SocialAuthService
17 protected $socialAccount;
19 protected $validSocialDrivers = ['google', 'github', 'facebook', 'slack', 'twitter', 'azure', 'okta', 'gitlab'];
22 * SocialAuthService constructor.
23 * @param UserRepo $userRepo
24 * @param Socialite $socialite
25 * @param SocialAccount $socialAccount
27 public function __construct(UserRepo $userRepo, Socialite $socialite, SocialAccount $socialAccount)
29 $this->userRepo = $userRepo;
30 $this->socialite = $socialite;
31 $this->socialAccount = $socialAccount;
36 * Start the social login path.
37 * @param string $socialDriver
38 * @return \Symfony\Component\HttpFoundation\RedirectResponse
39 * @throws SocialDriverNotConfigured
41 public function startLogIn($socialDriver)
43 $driver = $this->validateDriver($socialDriver);
44 return $this->socialite->driver($driver)->redirect();
48 * Start the social registration process
49 * @param string $socialDriver
50 * @return \Symfony\Component\HttpFoundation\RedirectResponse
51 * @throws SocialDriverNotConfigured
53 public function startRegister($socialDriver)
55 $driver = $this->validateDriver($socialDriver);
56 return $this->socialite->driver($driver)->redirect();
60 * Handle the social registration process on callback.
61 * @param $socialDriver
62 * @return \Laravel\Socialite\Contracts\User
63 * @throws SocialDriverNotConfigured
64 * @throws UserRegistrationException
66 public function handleRegistrationCallback($socialDriver)
68 $driver = $this->validateDriver($socialDriver);
70 // Get user details from social driver
71 $socialUser = $this->socialite->driver($driver)->user();
73 // Check social account has not already been used
74 if ($this->socialAccount->where('driver_id', '=', $socialUser->getId())->exists()) {
75 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver]), '/login');
78 if ($this->userRepo->getByEmail($socialUser->getEmail())) {
79 $email = $socialUser->getEmail();
80 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver, 'email' => $email]), '/login');
87 * Handle the login process on a oAuth callback.
88 * @param $socialDriver
89 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
90 * @throws SocialDriverNotConfigured
91 * @throws SocialSignInException
93 public function handleLoginCallback($socialDriver)
95 $driver = $this->validateDriver($socialDriver);
96 // Get user details from social driver
97 $socialUser = $this->socialite->driver($driver)->user();
98 $socialId = $socialUser->getId();
100 // Get any attached social accounts or users
101 $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
102 $isLoggedIn = auth()->check();
103 $currentUser = user();
105 // When a user is not logged in and a matching SocialAccount exists,
106 // Simply log the user into the application.
107 if (!$isLoggedIn && $socialAccount !== null) {
108 auth()->login($socialAccount->user);
109 return redirect()->intended('/');
112 // When a user is logged in but the social account does not exist,
113 // Create the social account and attach it to the user & redirect to the profile page.
114 if ($isLoggedIn && $socialAccount === null) {
115 $this->fillSocialAccount($socialDriver, $socialUser);
116 $currentUser->socialAccounts()->save($this->socialAccount);
117 session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => title_case($socialDriver)]));
118 return redirect($currentUser->getEditUrl());
121 // When a user is logged in and the social account exists and is already linked to the current user.
122 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
123 session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => title_case($socialDriver)]));
124 return redirect($currentUser->getEditUrl());
127 // When a user is logged in, A social account exists but the users do not match.
128 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
129 session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => title_case($socialDriver)]));
130 return redirect($currentUser->getEditUrl());
133 // Otherwise let the user know this social account is not used by anyone.
134 $message = trans('errors.social_account_not_used', ['socialAccount' => title_case($socialDriver)]);
135 if (setting('registration-enabled')) {
136 $message .= trans('errors.social_account_register_instructions', ['socialAccount' => title_case($socialDriver)]);
139 throw new SocialSignInException($message, '/login');
143 * Ensure the social driver is correct and supported.
145 * @param $socialDriver
147 * @throws SocialDriverNotConfigured
149 private function validateDriver($socialDriver)
151 $driver = trim(strtolower($socialDriver));
153 if (!in_array($driver, $this->validSocialDrivers)) {
154 abort(404, trans('errors.social_driver_not_found'));
156 if (!$this->checkDriverConfigured($driver)) {
157 throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => title_case($socialDriver)]));
164 * Check a social driver has been configured correctly.
168 private function checkDriverConfigured($driver)
170 $lowerName = strtolower($driver);
171 $configPrefix = 'services.' . $lowerName . '.';
172 $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
173 return !in_array(false, $config) && !in_array(null, $config);
177 * Gets the names of the active social drivers.
180 public function getActiveDrivers()
183 foreach ($this->validSocialDrivers as $driverKey) {
184 if ($this->checkDriverConfigured($driverKey)) {
185 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
188 return $activeDrivers;
192 * Get the presentational name for a driver.
196 public function getDriverName($driver)
198 return config('services.' . strtolower($driver) . '.name');
202 * @param string $socialDriver
203 * @param \Laravel\Socialite\Contracts\User $socialUser
204 * @return SocialAccount
206 public function fillSocialAccount($socialDriver, $socialUser)
208 $this->socialAccount->fill([
209 'driver' => $socialDriver,
210 'driver_id' => $socialUser->getId(),
211 'avatar' => $socialUser->getAvatar()
213 return $this->socialAccount;
217 * Detach a social account from a user.
218 * @param $socialDriver
219 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
221 public function detachSocialAccount($socialDriver)
223 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
224 session()->flash('success', trans('settings.users_social_disconnected', ['socialAccount' => title_case($socialDriver)]));
225 return redirect(user()->getEditUrl());