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 Laravel\Socialite\Two\GoogleProvider;
16 use SocialiteProviders\Manager\SocialiteWasCalled;
17 use Symfony\Component\HttpFoundation\RedirectResponse;
19 class SocialAuthService
22 * The core socialite library used.
31 protected $loginService;
34 * The default built-in social drivers we support.
38 protected $validSocialDrivers = [
52 * Callbacks to run when configuring a social driver
53 * for an initial redirect action.
54 * Array is keyed by social driver name.
55 * Callbacks are passed an instance of the driver.
57 * @var array<string, callable>
59 protected $configureForRedirectCallbacks = [];
62 * SocialAuthService constructor.
64 public function __construct(Socialite $socialite, LoginService $loginService)
66 $this->socialite = $socialite;
67 $this->loginService = $loginService;
71 * Start the social login path.
73 * @throws SocialDriverNotConfigured
75 public function startLogIn(string $socialDriver): RedirectResponse
77 $driver = $this->validateDriver($socialDriver);
79 return $this->getDriverForRedirect($driver)->redirect();
83 * Start the social registration process.
85 * @throws SocialDriverNotConfigured
87 public function startRegister(string $socialDriver): RedirectResponse
89 $driver = $this->validateDriver($socialDriver);
91 return $this->getDriverForRedirect($driver)->redirect();
95 * Handle the social registration process on callback.
97 * @throws UserRegistrationException
99 public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser): SocialUser
101 // Check social account has not already been used
102 if (SocialAccount::query()->where('driver_id', '=', $socialUser->getId())->exists()) {
103 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount' => $socialDriver]), '/login');
106 if (User::query()->where('email', '=', $socialUser->getEmail())->exists()) {
107 $email = $socialUser->getEmail();
109 throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $email]), '/login');
116 * Get the social user details via the social driver.
118 * @throws SocialDriverNotConfigured
120 public function getSocialUser(string $socialDriver): SocialUser
122 $driver = $this->validateDriver($socialDriver);
124 return $this->socialite->driver($driver)->user();
128 * Handle the login process on a oAuth callback.
130 * @throws SocialSignInAccountNotUsed
132 public function handleLoginCallback(string $socialDriver, SocialUser $socialUser)
134 $socialId = $socialUser->getId();
136 // Get any attached social accounts or users
137 $socialAccount = SocialAccount::query()->where('driver_id', '=', $socialId)->first();
138 $isLoggedIn = auth()->check();
139 $currentUser = user();
140 $titleCaseDriver = Str::title($socialDriver);
142 // When a user is not logged in and a matching SocialAccount exists,
143 // Simply log the user into the application.
144 if (!$isLoggedIn && $socialAccount !== null) {
145 $this->loginService->login($socialAccount->user, $socialDriver);
147 return redirect()->intended('/');
150 // When a user is logged in but the social account does not exist,
151 // Create the social account and attach it to the user & redirect to the profile page.
152 if ($isLoggedIn && $socialAccount === null) {
153 $account = $this->newSocialAccount($socialDriver, $socialUser);
154 $currentUser->socialAccounts()->save($account);
155 session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => $titleCaseDriver]));
157 return redirect($currentUser->getEditUrl());
160 // When a user is logged in and the social account exists and is already linked to the current user.
161 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
162 session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => $titleCaseDriver]));
164 return redirect($currentUser->getEditUrl());
167 // When a user is logged in, A social account exists but the users do not match.
168 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
169 session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => $titleCaseDriver]));
171 return redirect($currentUser->getEditUrl());
174 // Otherwise let the user know this social account is not used by anyone.
175 $message = trans('errors.social_account_not_used', ['socialAccount' => $titleCaseDriver]);
176 if (setting('registration-enabled') && config('auth.method') !== 'ldap' && config('auth.method') !== 'saml2') {
177 $message .= trans('errors.social_account_register_instructions', ['socialAccount' => $titleCaseDriver]);
180 throw new SocialSignInAccountNotUsed($message, '/login');
184 * Ensure the social driver is correct and supported.
186 * @throws SocialDriverNotConfigured
188 protected function validateDriver(string $socialDriver): string
190 $driver = trim(strtolower($socialDriver));
192 if (!in_array($driver, $this->validSocialDrivers)) {
193 abort(404, trans('errors.social_driver_not_found'));
196 if (!$this->checkDriverConfigured($driver)) {
197 throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => Str::title($socialDriver)]));
204 * Check a social driver has been configured correctly.
206 protected function checkDriverConfigured(string $driver): bool
208 $lowerName = strtolower($driver);
209 $configPrefix = 'services.' . $lowerName . '.';
210 $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
212 return !in_array(false, $config) && !in_array(null, $config);
216 * Gets the names of the active social drivers.
218 public function getActiveDrivers(): array
222 foreach ($this->validSocialDrivers as $driverKey) {
223 if ($this->checkDriverConfigured($driverKey)) {
224 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
228 return $activeDrivers;
232 * Get the presentational name for a driver.
234 public function getDriverName(string $driver): string
236 return config('services.' . strtolower($driver) . '.name');
240 * Check if the current config for the given driver allows auto-registration.
242 public function driverAutoRegisterEnabled(string $driver): bool
244 return config('services.' . strtolower($driver) . '.auto_register') === true;
248 * Check if the current config for the given driver allow email address auto-confirmation.
250 public function driverAutoConfirmEmailEnabled(string $driver): bool
252 return config('services.' . strtolower($driver) . '.auto_confirm') === true;
256 * Fill and return a SocialAccount from the given driver name and SocialUser.
258 public function newSocialAccount(string $socialDriver, SocialUser $socialUser): SocialAccount
260 return new SocialAccount([
261 'driver' => $socialDriver,
262 'driver_id' => $socialUser->getId(),
263 'avatar' => $socialUser->getAvatar(),
268 * Detach a social account from a user.
270 public function detachSocialAccount(string $socialDriver): void
272 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
276 * Provide redirect options per service for the Laravel Socialite driver.
278 protected function getDriverForRedirect(string $driverName): Provider
280 $driver = $this->socialite->driver($driverName);
282 if ($driver instanceof GoogleProvider && config('services.google.select_account')) {
283 $driver->with(['prompt' => 'select_account']);
286 if (isset($this->configureForRedirectCallbacks[$driverName])) {
287 $this->configureForRedirectCallbacks[$driverName]($driver);
294 * Add a custom socialite driver to be used.
295 * Driver name should be lower_snake_case.
296 * Config array should mirror the structure of a service
297 * within the `Config/services.php` file.
298 * Handler should be a Class@method handler to the SocialiteWasCalled event.
300 public function addSocialDriver(
303 string $socialiteHandler,
304 callable $configureForRedirect = null
306 $this->validSocialDrivers[] = $driverName;
307 config()->set('services.' . $driverName, $config);
308 config()->set('services.' . $driverName . '.redirect', url('/login/service/' . $driverName . '/callback'));
309 config()->set('services.' . $driverName . '.name', $config['name'] ?? $driverName);
310 Event::listen(SocialiteWasCalled::class, $socialiteHandler);
311 if (!is_null($configureForRedirect)) {
312 $this->configureForRedirectCallbacks[$driverName] = $configureForRedirect;