1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\SocialAccount;
4 use BookStack\Auth\UserRepo;
5 use BookStack\Exceptions\SocialDriverNotConfigured;
6 use BookStack\Exceptions\SocialSignInAccountNotUsed;
7 use BookStack\Exceptions\UserRegistrationException;
8 use Illuminate\Support\Str;
9 use Laravel\Socialite\Contracts\Factory as Socialite;
10 use Laravel\Socialite\Contracts\User as SocialUser;
12 class SocialAuthService
17 protected $socialAccount;
19 protected $validSocialDrivers = ['google', 'github', 'facebook', 'slack', 'twitter', 'azure', 'okta', 'gitlab', 'twitch', 'discord'];
22 * SocialAuthService constructor.
23 * @param \BookStack\Auth\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->getSocialDriver($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->getSocialDriver($driver)->redirect();
60 * Handle the social registration process on callback.
61 * @param string $socialDriver
62 * @param SocialUser $socialUser
64 * @throws UserRegistrationException
66 public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser)
68 // Check social account has not already been used
69 if ($this->socialAccount->where('driver_id', '=', $socialUser->getId())->exists()) {
70 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver]), '/login');
73 if ($this->userRepo->getByEmail($socialUser->getEmail())) {
74 $email = $socialUser->getEmail();
75 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver, 'email' => $email]), '/login');
82 * Get the social user details via the social driver.
83 * @param string $socialDriver
85 * @throws SocialDriverNotConfigured
87 public function getSocialUser(string $socialDriver)
89 $driver = $this->validateDriver($socialDriver);
90 return $this->socialite->driver($driver)->user();
94 * Handle the login process on a oAuth callback.
95 * @param $socialDriver
96 * @param SocialUser $socialUser
97 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
98 * @throws SocialSignInAccountNotUsed
100 public function handleLoginCallback($socialDriver, SocialUser $socialUser)
102 $socialId = $socialUser->getId();
104 // Get any attached social accounts or users
105 $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
106 $isLoggedIn = auth()->check();
107 $currentUser = user();
108 $titleCaseDriver = Str::title($socialDriver);
110 // When a user is not logged in and a matching SocialAccount exists,
111 // Simply log the user into the application.
112 if (!$isLoggedIn && $socialAccount !== null) {
113 auth()->login($socialAccount->user);
114 return redirect()->intended('/');
117 // When a user is logged in but the social account does not exist,
118 // Create the social account and attach it to the user & redirect to the profile page.
119 if ($isLoggedIn && $socialAccount === null) {
120 $this->fillSocialAccount($socialDriver, $socialUser);
121 $currentUser->socialAccounts()->save($this->socialAccount);
122 session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => $titleCaseDriver]));
123 return redirect($currentUser->getEditUrl());
126 // When a user is logged in and the social account exists and is already linked to the current user.
127 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
128 session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => $titleCaseDriver]));
129 return redirect($currentUser->getEditUrl());
132 // When a user is logged in, A social account exists but the users do not match.
133 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
134 session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => $titleCaseDriver]));
135 return redirect($currentUser->getEditUrl());
138 // Otherwise let the user know this social account is not used by anyone.
139 $message = trans('errors.social_account_not_used', ['socialAccount' => $titleCaseDriver]);
140 if (setting('registration-enabled')) {
141 $message .= trans('errors.social_account_register_instructions', ['socialAccount' => $titleCaseDriver]);
144 throw new SocialSignInAccountNotUsed($message, '/login');
148 * Ensure the social driver is correct and supported.
150 * @param $socialDriver
152 * @throws SocialDriverNotConfigured
154 private function validateDriver($socialDriver)
156 $driver = trim(strtolower($socialDriver));
158 if (!in_array($driver, $this->validSocialDrivers)) {
159 abort(404, trans('errors.social_driver_not_found'));
161 if (!$this->checkDriverConfigured($driver)) {
162 throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => Str::title($socialDriver)]));
169 * Check a social driver has been configured correctly.
173 private function checkDriverConfigured($driver)
175 $lowerName = strtolower($driver);
176 $configPrefix = 'services.' . $lowerName . '.';
177 $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
178 return !in_array(false, $config) && !in_array(null, $config);
182 * Gets the names of the active social drivers.
185 public function getActiveDrivers()
188 foreach ($this->validSocialDrivers as $driverKey) {
189 if ($this->checkDriverConfigured($driverKey)) {
190 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
193 return $activeDrivers;
197 * Get the presentational name for a driver.
201 public function getDriverName($driver)
203 return config('services.' . strtolower($driver) . '.name');
207 * Check if the current config for the given driver allows auto-registration.
208 * @param string $driver
211 public function driverAutoRegisterEnabled(string $driver)
213 return config('services.' . strtolower($driver) . '.auto_register') === true;
217 * Check if the current config for the given driver allow email address auto-confirmation.
218 * @param string $driver
221 public function driverAutoConfirmEmailEnabled(string $driver)
223 return config('services.' . strtolower($driver) . '.auto_confirm') === true;
227 * @param string $socialDriver
228 * @param SocialUser $socialUser
229 * @return SocialAccount
231 public function fillSocialAccount($socialDriver, $socialUser)
233 $this->socialAccount->fill([
234 'driver' => $socialDriver,
235 'driver_id' => $socialUser->getId(),
236 'avatar' => $socialUser->getAvatar()
238 return $this->socialAccount;
242 * Detach a social account from a user.
243 * @param $socialDriver
244 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
246 public function detachSocialAccount($socialDriver)
248 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
249 session()->flash('success', trans('settings.users_social_disconnected', ['socialAccount' => Str::title($socialDriver)]));
250 return redirect(user()->getEditUrl());
254 * Provide redirect options per service for the Laravel Socialite driver
256 * @return \Laravel\Socialite\Contracts\Provider
258 public function getSocialDriver(string $driverName)
260 $driver = $this->socialite->driver($driverName);
262 if ($driverName === 'google' && config('services.google.select_account')) {
263 $driver->with(['prompt' => 'select_account']);