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->getSocialDriver($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 return $this->getSocialDriver($driver)->redirect();
59 * Handle the social registration process on callback.
60 * @param string $socialDriver
61 * @param SocialUser $socialUser
63 * @throws UserRegistrationException
65 public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser)
67 // Check social account has not already been used
68 if ($this->socialAccount->where('driver_id', '=', $socialUser->getId())->exists()) {
69 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver]), '/login');
72 if ($this->userRepo->getByEmail($socialUser->getEmail())) {
73 $email = $socialUser->getEmail();
74 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver, 'email' => $email]), '/login');
81 * Get the social user details via the social driver.
82 * @param string $socialDriver
84 * @throws SocialDriverNotConfigured
86 public function getSocialUser(string $socialDriver)
88 $driver = $this->validateDriver($socialDriver);
89 return $this->socialite->driver($driver)->user();
93 * Handle the login process on a oAuth callback.
94 * @param $socialDriver
95 * @param SocialUser $socialUser
96 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
97 * @throws SocialSignInAccountNotUsed
99 public function handleLoginCallback($socialDriver, SocialUser $socialUser)
101 $socialId = $socialUser->getId();
103 // Get any attached social accounts or users
104 $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
105 $isLoggedIn = auth()->check();
106 $currentUser = user();
108 // When a user is not logged in and a matching SocialAccount exists,
109 // Simply log the user into the application.
110 if (!$isLoggedIn && $socialAccount !== null) {
111 auth()->login($socialAccount->user);
112 return redirect()->intended('/');
115 // When a user is logged in but the social account does not exist,
116 // Create the social account and attach it to the user & redirect to the profile page.
117 if ($isLoggedIn && $socialAccount === null) {
118 $this->fillSocialAccount($socialDriver, $socialUser);
119 $currentUser->socialAccounts()->save($this->socialAccount);
120 session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => title_case($socialDriver)]));
121 return redirect($currentUser->getEditUrl());
124 // When a user is logged in and the social account exists and is already linked to the current user.
125 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
126 session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => title_case($socialDriver)]));
127 return redirect($currentUser->getEditUrl());
130 // When a user is logged in, A social account exists but the users do not match.
131 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
132 session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => title_case($socialDriver)]));
133 return redirect($currentUser->getEditUrl());
136 // Otherwise let the user know this social account is not used by anyone.
137 $message = trans('errors.social_account_not_used', ['socialAccount' => title_case($socialDriver)]);
138 if (setting('registration-enabled')) {
139 $message .= trans('errors.social_account_register_instructions', ['socialAccount' => title_case($socialDriver)]);
142 throw new SocialSignInAccountNotUsed($message, '/login');
146 * Ensure the social driver is correct and supported.
148 * @param $socialDriver
150 * @throws SocialDriverNotConfigured
152 private function validateDriver($socialDriver)
154 $driver = trim(strtolower($socialDriver));
156 if (!in_array($driver, $this->validSocialDrivers)) {
157 abort(404, trans('errors.social_driver_not_found'));
159 if (!$this->checkDriverConfigured($driver)) {
160 throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => title_case($socialDriver)]));
167 * Check a social driver has been configured correctly.
171 private function checkDriverConfigured($driver)
173 $lowerName = strtolower($driver);
174 $configPrefix = 'services.' . $lowerName . '.';
175 $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
176 return !in_array(false, $config) && !in_array(null, $config);
180 * Gets the names of the active social drivers.
183 public function getActiveDrivers()
186 foreach ($this->validSocialDrivers as $driverKey) {
187 if ($this->checkDriverConfigured($driverKey)) {
188 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
191 return $activeDrivers;
195 * Get the presentational name for a driver.
199 public function getDriverName($driver)
201 return config('services.' . strtolower($driver) . '.name');
205 * Check if the current config for the given driver allows auto-registration.
206 * @param string $driver
209 public function driverAutoRegisterEnabled(string $driver)
211 return config('services.' . strtolower($driver) . '.auto_register') === true;
215 * Check if the current config for the given driver allow email address auto-confirmation.
216 * @param string $driver
219 public function driverAutoConfirmEmailEnabled(string $driver)
221 return config('services.' . strtolower($driver) . '.auto_confirm') === true;
225 * @param string $socialDriver
226 * @param SocialUser $socialUser
227 * @return SocialAccount
229 public function fillSocialAccount($socialDriver, $socialUser)
231 $this->socialAccount->fill([
232 'driver' => $socialDriver,
233 'driver_id' => $socialUser->getId(),
234 'avatar' => $socialUser->getAvatar()
236 return $this->socialAccount;
240 * Detach a social account from a user.
241 * @param $socialDriver
242 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
244 public function detachSocialAccount($socialDriver)
246 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
247 session()->flash('success', trans('settings.users_social_disconnected', ['socialAccount' => title_case($socialDriver)]));
248 return redirect(user()->getEditUrl());
252 * Provide redirect options per service for the Laravel Socialite driver
254 * @return \Laravel\Socialite\Contracts\Provider
256 public function getSocialDriver(string $driverName)
258 $driver = $this->socialite->driver($driverName);
260 if ($driverName === 'google' && config('services.google.select_account')) {
261 $driver->with(['prompt' => 'select_account']);