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 Laravel\Socialite\Contracts\Factory as Socialite;
9 use Laravel\Socialite\Contracts\User as SocialUser;
11 class SocialAuthService
16 protected $socialAccount;
18 protected $validSocialDrivers = ['google', 'github', 'facebook', 'slack', 'twitter', 'azure', 'okta', 'gitlab', 'twitch', 'discord'];
21 * SocialAuthService constructor.
22 * @param \BookStack\Auth\UserRepo $userRepo
23 * @param Socialite $socialite
24 * @param SocialAccount $socialAccount
26 public function __construct(UserRepo $userRepo, Socialite $socialite, SocialAccount $socialAccount)
28 $this->userRepo = $userRepo;
29 $this->socialite = $socialite;
30 $this->socialAccount = $socialAccount;
35 * Start the social login path.
36 * @param string $socialDriver
37 * @return \Symfony\Component\HttpFoundation\RedirectResponse
38 * @throws SocialDriverNotConfigured
40 public function startLogIn($socialDriver)
42 $driver = $this->validateDriver($socialDriver);
43 return $this->socialite->driver($driver)->redirect();
47 * Start the social registration process
48 * @param string $socialDriver
49 * @return \Symfony\Component\HttpFoundation\RedirectResponse
50 * @throws SocialDriverNotConfigured
52 public function startRegister($socialDriver)
54 $driver = $this->validateDriver($socialDriver);
55 if ($socialDriver == 'google') {
56 return $this->socialite->driver($driver)->with(['prompt' => 'select_account'])->redirect();
58 return $this->socialite->driver($driver)->redirect();
62 * Handle the social registration process on callback.
63 * @param string $socialDriver
64 * @param SocialUser $socialUser
66 * @throws UserRegistrationException
68 public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser)
70 // Check social account has not already been used
71 if ($this->socialAccount->where('driver_id', '=', $socialUser->getId())->exists()) {
72 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver]), '/login');
75 if ($this->userRepo->getByEmail($socialUser->getEmail())) {
76 $email = $socialUser->getEmail();
77 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver, 'email' => $email]), '/login');
84 * Get the social user details via the social driver.
85 * @param string $socialDriver
87 * @throws SocialDriverNotConfigured
89 public function getSocialUser(string $socialDriver)
91 $driver = $this->validateDriver($socialDriver);
92 return $this->socialite->driver($driver)->user();
96 * Handle the login process on a oAuth callback.
97 * @param $socialDriver
98 * @param SocialUser $socialUser
99 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
100 * @throws SocialSignInAccountNotUsed
102 public function handleLoginCallback($socialDriver, SocialUser $socialUser)
104 $socialId = $socialUser->getId();
106 // Get any attached social accounts or users
107 $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
108 $isLoggedIn = auth()->check();
109 $currentUser = user();
111 // When a user is not logged in and a matching SocialAccount exists,
112 // Simply log the user into the application.
113 if (!$isLoggedIn && $socialAccount !== null) {
114 auth()->login($socialAccount->user);
115 return redirect()->intended('/');
118 // When a user is logged in but the social account does not exist,
119 // Create the social account and attach it to the user & redirect to the profile page.
120 if ($isLoggedIn && $socialAccount === null) {
121 $this->fillSocialAccount($socialDriver, $socialUser);
122 $currentUser->socialAccounts()->save($this->socialAccount);
123 session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => title_case($socialDriver)]));
124 return redirect($currentUser->getEditUrl());
127 // When a user is logged in and the social account exists and is already linked to the current user.
128 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
129 session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => title_case($socialDriver)]));
130 return redirect($currentUser->getEditUrl());
133 // When a user is logged in, A social account exists but the users do not match.
134 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
135 session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => title_case($socialDriver)]));
136 return redirect($currentUser->getEditUrl());
139 // Otherwise let the user know this social account is not used by anyone.
140 $message = trans('errors.social_account_not_used', ['socialAccount' => title_case($socialDriver)]);
141 if (setting('registration-enabled')) {
142 $message .= trans('errors.social_account_register_instructions', ['socialAccount' => title_case($socialDriver)]);
145 throw new SocialSignInAccountNotUsed($message, '/login');
149 * Ensure the social driver is correct and supported.
151 * @param $socialDriver
153 * @throws SocialDriverNotConfigured
155 private function validateDriver($socialDriver)
157 $driver = trim(strtolower($socialDriver));
159 if (!in_array($driver, $this->validSocialDrivers)) {
160 abort(404, trans('errors.social_driver_not_found'));
162 if (!$this->checkDriverConfigured($driver)) {
163 throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => title_case($socialDriver)]));
170 * Check a social driver has been configured correctly.
174 private function checkDriverConfigured($driver)
176 $lowerName = strtolower($driver);
177 $configPrefix = 'services.' . $lowerName . '.';
178 $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
179 return !in_array(false, $config) && !in_array(null, $config);
183 * Gets the names of the active social drivers.
186 public function getActiveDrivers()
189 foreach ($this->validSocialDrivers as $driverKey) {
190 if ($this->checkDriverConfigured($driverKey)) {
191 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
194 return $activeDrivers;
198 * Get the presentational name for a driver.
202 public function getDriverName($driver)
204 return config('services.' . strtolower($driver) . '.name');
208 * Check if the current config for the given driver allows auto-registration.
209 * @param string $driver
212 public function driverAutoRegisterEnabled(string $driver)
214 return config('services.' . strtolower($driver) . '.auto_register') === true;
218 * Check if the current config for the given driver allow email address auto-confirmation.
219 * @param string $driver
222 public function driverAutoConfirmEmailEnabled(string $driver)
224 return config('services.' . strtolower($driver) . '.auto_confirm') === true;
228 * @param string $socialDriver
229 * @param SocialUser $socialUser
230 * @return SocialAccount
232 public function fillSocialAccount($socialDriver, $socialUser)
234 $this->socialAccount->fill([
235 'driver' => $socialDriver,
236 'driver_id' => $socialUser->getId(),
237 'avatar' => $socialUser->getAvatar()
239 return $this->socialAccount;
243 * Detach a social account from a user.
244 * @param $socialDriver
245 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
247 public function detachSocialAccount($socialDriver)
249 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
250 session()->flash('success', trans('settings.users_social_disconnected', ['socialAccount' => title_case($socialDriver)]));
251 return redirect(user()->getEditUrl());