3 namespace BookStack\Auth\Access;
5 use BookStack\Auth\SocialAccount;
6 use BookStack\Auth\User;
7 use BookStack\Exceptions\SocialDriverNotConfigured;
8 use BookStack\Exceptions\SocialSignInAccountNotUsed;
9 use BookStack\Exceptions\UserRegistrationException;
10 use Illuminate\Support\Facades\Event;
11 use Illuminate\Support\Str;
12 use Laravel\Socialite\Contracts\Factory as Socialite;
13 use Laravel\Socialite\Contracts\Provider;
14 use Laravel\Socialite\Contracts\User as SocialUser;
15 use SocialiteProviders\Manager\SocialiteWasCalled;
16 use Symfony\Component\HttpFoundation\RedirectResponse;
18 class SocialAuthService
21 * The core socialite library used.
30 protected $loginService;
33 * The default built-in social drivers we support.
37 protected $validSocialDrivers = [
51 * Callbacks to run when configuring a social driver
52 * for an initial redirect action.
53 * Array is keyed by social driver name.
54 * Callbacks are passed an instance of the driver.
56 * @var array<string, callable>
58 protected $configureForRedirectCallbacks = [];
61 * SocialAuthService constructor.
63 public function __construct(Socialite $socialite, LoginService $loginService)
65 $this->socialite = $socialite;
66 $this->loginService = $loginService;
70 * Start the social login path.
72 * @throws SocialDriverNotConfigured
74 public function startLogIn(string $socialDriver): RedirectResponse
76 $driver = $this->validateDriver($socialDriver);
78 return $this->getDriverForRedirect($driver)->redirect();
82 * Start the social registration process.
84 * @throws SocialDriverNotConfigured
86 public function startRegister(string $socialDriver): RedirectResponse
88 $driver = $this->validateDriver($socialDriver);
90 return $this->getDriverForRedirect($driver)->redirect();
94 * Handle the social registration process on callback.
96 * @throws UserRegistrationException
98 public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser): SocialUser
100 // Check social account has not already been used
101 if (SocialAccount::query()->where('driver_id', '=', $socialUser->getId())->exists()) {
102 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount' => $socialDriver]), '/login');
105 if (User::query()->where('email', '=', $socialUser->getEmail())->exists()) {
106 $email = $socialUser->getEmail();
108 throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $email]), '/login');
115 * Get the social user details via the social driver.
117 * @throws SocialDriverNotConfigured
119 public function getSocialUser(string $socialDriver): SocialUser
121 $driver = $this->validateDriver($socialDriver);
123 return $this->socialite->driver($driver)->user();
127 * Handle the login process on a oAuth callback.
129 * @throws SocialSignInAccountNotUsed
131 public function handleLoginCallback(string $socialDriver, SocialUser $socialUser)
133 $socialId = $socialUser->getId();
135 // Get any attached social accounts or users
136 $socialAccount = SocialAccount::query()->where('driver_id', '=', $socialId)->first();
137 $isLoggedIn = auth()->check();
138 $currentUser = user();
139 $titleCaseDriver = Str::title($socialDriver);
141 // When a user is not logged in and a matching SocialAccount exists,
142 // Simply log the user into the application.
143 if (!$isLoggedIn && $socialAccount !== null) {
144 $this->loginService->login($socialAccount->user, $socialDriver);
146 return redirect()->intended('/');
149 // When a user is logged in but the social account does not exist,
150 // Create the social account and attach it to the user & redirect to the profile page.
151 if ($isLoggedIn && $socialAccount === null) {
152 $account = $this->newSocialAccount($socialDriver, $socialUser);
153 $currentUser->socialAccounts()->save($account);
154 session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => $titleCaseDriver]));
156 return redirect($currentUser->getEditUrl());
159 // When a user is logged in and the social account exists and is already linked to the current user.
160 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
161 session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => $titleCaseDriver]));
163 return redirect($currentUser->getEditUrl());
166 // When a user is logged in, A social account exists but the users do not match.
167 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
168 session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => $titleCaseDriver]));
170 return redirect($currentUser->getEditUrl());
173 // Otherwise let the user know this social account is not used by anyone.
174 $message = trans('errors.social_account_not_used', ['socialAccount' => $titleCaseDriver]);
175 if (setting('registration-enabled') && config('auth.method') !== 'ldap' && config('auth.method') !== 'saml2') {
176 $message .= trans('errors.social_account_register_instructions', ['socialAccount' => $titleCaseDriver]);
179 throw new SocialSignInAccountNotUsed($message, '/login');
183 * Ensure the social driver is correct and supported.
185 * @throws SocialDriverNotConfigured
187 protected function validateDriver(string $socialDriver): string
189 $driver = trim(strtolower($socialDriver));
191 if (!in_array($driver, $this->validSocialDrivers)) {
192 abort(404, trans('errors.social_driver_not_found'));
195 if (!$this->checkDriverConfigured($driver)) {
196 throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => Str::title($socialDriver)]));
203 * Check a social driver has been configured correctly.
205 protected function checkDriverConfigured(string $driver): bool
207 $lowerName = strtolower($driver);
208 $configPrefix = 'services.' . $lowerName . '.';
209 $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
211 return !in_array(false, $config) && !in_array(null, $config);
215 * Gets the names of the active social drivers.
217 public function getActiveDrivers(): array
221 foreach ($this->validSocialDrivers as $driverKey) {
222 if ($this->checkDriverConfigured($driverKey)) {
223 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
227 return $activeDrivers;
231 * Get the presentational name for a driver.
233 public function getDriverName(string $driver): string
235 return config('services.' . strtolower($driver) . '.name');
239 * Check if the current config for the given driver allows auto-registration.
241 public function driverAutoRegisterEnabled(string $driver): bool
243 return config('services.' . strtolower($driver) . '.auto_register') === true;
247 * Check if the current config for the given driver allow email address auto-confirmation.
249 public function driverAutoConfirmEmailEnabled(string $driver): bool
251 return config('services.' . strtolower($driver) . '.auto_confirm') === true;
255 * Fill and return a SocialAccount from the given driver name and SocialUser.
257 public function newSocialAccount(string $socialDriver, SocialUser $socialUser): SocialAccount
259 return new SocialAccount([
260 'driver' => $socialDriver,
261 'driver_id' => $socialUser->getId(),
262 'avatar' => $socialUser->getAvatar(),
267 * Detach a social account from a user.
269 public function detachSocialAccount(string $socialDriver): void
271 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
275 * Provide redirect options per service for the Laravel Socialite driver.
277 protected function getDriverForRedirect(string $driverName): Provider
279 $driver = $this->socialite->driver($driverName);
281 if ($driverName === 'google' && config('services.google.select_account')) {
282 $driver->with(['prompt' => 'select_account']);
285 if (isset($this->configureForRedirectCallbacks[$driverName])) {
286 $this->configureForRedirectCallbacks[$driverName]($driver);
293 * Add a custom socialite driver to be used.
294 * Driver name should be lower_snake_case.
295 * Config array should mirror the structure of a service
296 * within the `Config/services.php` file.
297 * Handler should be a Class@method handler to the SocialiteWasCalled event.
299 public function addSocialDriver(
302 string $socialiteHandler,
303 callable $configureForRedirect = null
305 $this->validSocialDrivers[] = $driverName;
306 config()->set('services.' . $driverName, $config);
307 config()->set('services.' . $driverName . '.redirect', url('/login/service/' . $driverName . '/callback'));
308 config()->set('services.' . $driverName . '.name', $config['name'] ?? $driverName);
309 Event::listen(SocialiteWasCalled::class, $socialiteHandler);
310 if (!is_null($configureForRedirect)) {
311 $this->configureForRedirectCallbacks[$driverName] = $configureForRedirect;