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();
59 return $this->socialite->driver($driver)->redirect();
64 * Handle the social registration process on callback.
65 * @param string $socialDriver
66 * @param SocialUser $socialUser
68 * @throws UserRegistrationException
70 public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser)
72 // Check social account has not already been used
73 if ($this->socialAccount->where('driver_id', '=', $socialUser->getId())->exists()) {
74 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver]), '/login');
77 if ($this->userRepo->getByEmail($socialUser->getEmail())) {
78 $email = $socialUser->getEmail();
79 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver, 'email' => $email]), '/login');
86 * Get the social user details via the social driver.
87 * @param string $socialDriver
89 * @throws SocialDriverNotConfigured
91 public function getSocialUser(string $socialDriver)
93 $driver = $this->validateDriver($socialDriver);
94 return $this->socialite->driver($driver)->user();
98 * Handle the login process on a oAuth callback.
99 * @param $socialDriver
100 * @param SocialUser $socialUser
101 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
102 * @throws SocialSignInAccountNotUsed
104 public function handleLoginCallback($socialDriver, SocialUser $socialUser)
106 $socialId = $socialUser->getId();
108 // Get any attached social accounts or users
109 $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
110 $isLoggedIn = auth()->check();
111 $currentUser = user();
113 // When a user is not logged in and a matching SocialAccount exists,
114 // Simply log the user into the application.
115 if (!$isLoggedIn && $socialAccount !== null) {
116 auth()->login($socialAccount->user);
117 return redirect()->intended('/');
120 // When a user is logged in but the social account does not exist,
121 // Create the social account and attach it to the user & redirect to the profile page.
122 if ($isLoggedIn && $socialAccount === null) {
123 $this->fillSocialAccount($socialDriver, $socialUser);
124 $currentUser->socialAccounts()->save($this->socialAccount);
125 session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => title_case($socialDriver)]));
126 return redirect($currentUser->getEditUrl());
129 // When a user is logged in and the social account exists and is already linked to the current user.
130 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
131 session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => title_case($socialDriver)]));
132 return redirect($currentUser->getEditUrl());
135 // When a user is logged in, A social account exists but the users do not match.
136 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
137 session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => title_case($socialDriver)]));
138 return redirect($currentUser->getEditUrl());
141 // Otherwise let the user know this social account is not used by anyone.
142 $message = trans('errors.social_account_not_used', ['socialAccount' => title_case($socialDriver)]);
143 if (setting('registration-enabled')) {
144 $message .= trans('errors.social_account_register_instructions', ['socialAccount' => title_case($socialDriver)]);
147 throw new SocialSignInAccountNotUsed($message, '/login');
151 * Ensure the social driver is correct and supported.
153 * @param $socialDriver
155 * @throws SocialDriverNotConfigured
157 private function validateDriver($socialDriver)
159 $driver = trim(strtolower($socialDriver));
161 if (!in_array($driver, $this->validSocialDrivers)) {
162 abort(404, trans('errors.social_driver_not_found'));
164 if (!$this->checkDriverConfigured($driver)) {
165 throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => title_case($socialDriver)]));
172 * Check a social driver has been configured correctly.
176 private function checkDriverConfigured($driver)
178 $lowerName = strtolower($driver);
179 $configPrefix = 'services.' . $lowerName . '.';
180 $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
181 return !in_array(false, $config) && !in_array(null, $config);
185 * Gets the names of the active social drivers.
188 public function getActiveDrivers()
191 foreach ($this->validSocialDrivers as $driverKey) {
192 if ($this->checkDriverConfigured($driverKey)) {
193 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
196 return $activeDrivers;
200 * Get the presentational name for a driver.
204 public function getDriverName($driver)
206 return config('services.' . strtolower($driver) . '.name');
210 * Check if the current config for the given driver allows auto-registration.
211 * @param string $driver
214 public function driverAutoRegisterEnabled(string $driver)
216 return config('services.' . strtolower($driver) . '.auto_register') === true;
220 * Check if the current config for the given driver allow email address auto-confirmation.
221 * @param string $driver
224 public function driverAutoConfirmEmailEnabled(string $driver)
226 return config('services.' . strtolower($driver) . '.auto_confirm') === true;
230 * @param string $socialDriver
231 * @param SocialUser $socialUser
232 * @return SocialAccount
234 public function fillSocialAccount($socialDriver, $socialUser)
236 $this->socialAccount->fill([
237 'driver' => $socialDriver,
238 'driver_id' => $socialUser->getId(),
239 'avatar' => $socialUser->getAvatar()
241 return $this->socialAccount;
245 * Detach a social account from a user.
246 * @param $socialDriver
247 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
249 public function detachSocialAccount($socialDriver)
251 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
252 session()->flash('success', trans('settings.users_social_disconnected', ['socialAccount' => title_case($socialDriver)]));
253 return redirect(user()->getEditUrl());