1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Actions\ActivityType;
4 use BookStack\Auth\SocialAccount;
5 use BookStack\Auth\User;
6 use BookStack\Exceptions\SocialDriverNotConfigured;
7 use BookStack\Exceptions\SocialSignInAccountNotUsed;
8 use BookStack\Exceptions\UserRegistrationException;
9 use BookStack\Facades\Activity;
10 use BookStack\Facades\Theme;
11 use BookStack\Theming\ThemeEvents;
12 use Illuminate\Support\Facades\Event;
13 use Illuminate\Support\Str;
14 use Laravel\Socialite\Contracts\Factory as Socialite;
15 use Laravel\Socialite\Contracts\Provider;
16 use Laravel\Socialite\Contracts\User as SocialUser;
17 use SocialiteProviders\Manager\SocialiteWasCalled;
18 use Symfony\Component\HttpFoundation\RedirectResponse;
20 class SocialAuthService
23 * The core socialite library used.
29 * The default built-in social drivers we support.
32 protected $validSocialDrivers = [
46 * Callbacks to run when configuring a social driver
47 * for an initial redirect action.
48 * Array is keyed by social driver name.
49 * Callbacks are passed an instance of the driver.
50 * @var array<string, callable>
52 protected $configureForRedirectCallbacks = [];
55 * SocialAuthService constructor.
57 public function __construct(Socialite $socialite)
59 $this->socialite = $socialite;
63 * Start the social login path.
64 * @throws SocialDriverNotConfigured
66 public function startLogIn(string $socialDriver): RedirectResponse
68 $driver = $this->validateDriver($socialDriver);
69 return $this->getDriverForRedirect($driver)->redirect();
73 * Start the social registration process
74 * @throws SocialDriverNotConfigured
76 public function startRegister(string $socialDriver): RedirectResponse
78 $driver = $this->validateDriver($socialDriver);
79 return $this->getDriverForRedirect($driver)->redirect();
83 * Handle the social registration process on callback.
84 * @throws UserRegistrationException
86 public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser): SocialUser
88 // Check social account has not already been used
89 if (SocialAccount::query()->where('driver_id', '=', $socialUser->getId())->exists()) {
90 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount' => $socialDriver]), '/login');
93 if (User::query()->where('email', '=', $socialUser->getEmail())->exists()) {
94 $email = $socialUser->getEmail();
95 throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $email]), '/login');
102 * Get the social user details via the social driver.
103 * @throws SocialDriverNotConfigured
105 public function getSocialUser(string $socialDriver): SocialUser
107 $driver = $this->validateDriver($socialDriver);
108 return $this->socialite->driver($driver)->user();
112 * Handle the login process on a oAuth callback.
113 * @throws SocialSignInAccountNotUsed
115 public function handleLoginCallback(string $socialDriver, SocialUser $socialUser)
117 $socialId = $socialUser->getId();
119 // Get any attached social accounts or users
120 $socialAccount = SocialAccount::query()->where('driver_id', '=', $socialId)->first();
121 $isLoggedIn = auth()->check();
122 $currentUser = user();
123 $titleCaseDriver = Str::title($socialDriver);
125 // When a user is not logged in and a matching SocialAccount exists,
126 // Simply log the user into the application.
127 if (!$isLoggedIn && $socialAccount !== null) {
128 auth()->login($socialAccount->user);
129 Activity::add(ActivityType::AUTH_LOGIN, $socialAccount);
130 Theme::dispatch(ThemeEvents::AUTH_LOGIN, $socialDriver, $socialAccount->user);
131 return redirect()->intended('/');
134 // When a user is logged in but the social account does not exist,
135 // Create the social account and attach it to the user & redirect to the profile page.
136 if ($isLoggedIn && $socialAccount === null) {
137 $account = $this->newSocialAccount($socialDriver, $socialUser);
138 $currentUser->socialAccounts()->save($account);
139 session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => $titleCaseDriver]));
140 return redirect($currentUser->getEditUrl());
143 // When a user is logged in and the social account exists and is already linked to the current user.
144 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
145 session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => $titleCaseDriver]));
146 return redirect($currentUser->getEditUrl());
149 // When a user is logged in, A social account exists but the users do not match.
150 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
151 session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => $titleCaseDriver]));
152 return redirect($currentUser->getEditUrl());
155 // Otherwise let the user know this social account is not used by anyone.
156 $message = trans('errors.social_account_not_used', ['socialAccount' => $titleCaseDriver]);
157 if (setting('registration-enabled') && config('auth.method') !== 'ldap' && config('auth.method') !== 'saml2') {
158 $message .= trans('errors.social_account_register_instructions', ['socialAccount' => $titleCaseDriver]);
161 throw new SocialSignInAccountNotUsed($message, '/login');
165 * Ensure the social driver is correct and supported.
166 * @throws SocialDriverNotConfigured
168 protected function validateDriver(string $socialDriver): string
170 $driver = trim(strtolower($socialDriver));
172 if (!in_array($driver, $this->validSocialDrivers)) {
173 abort(404, trans('errors.social_driver_not_found'));
176 if (!$this->checkDriverConfigured($driver)) {
177 throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => Str::title($socialDriver)]));
184 * Check a social driver has been configured correctly.
186 protected function checkDriverConfigured(string $driver): bool
188 $lowerName = strtolower($driver);
189 $configPrefix = 'services.' . $lowerName . '.';
190 $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
191 return !in_array(false, $config) && !in_array(null, $config);
195 * Gets the names of the active social drivers.
197 public function getActiveDrivers(): array
201 foreach ($this->validSocialDrivers as $driverKey) {
202 if ($this->checkDriverConfigured($driverKey)) {
203 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
207 return $activeDrivers;
211 * Get the presentational name for a driver.
213 public function getDriverName(string $driver): string
215 return config('services.' . strtolower($driver) . '.name');
219 * Check if the current config for the given driver allows auto-registration.
221 public function driverAutoRegisterEnabled(string $driver): bool
223 return config('services.' . strtolower($driver) . '.auto_register') === true;
227 * Check if the current config for the given driver allow email address auto-confirmation.
229 public function driverAutoConfirmEmailEnabled(string $driver): bool
231 return config('services.' . strtolower($driver) . '.auto_confirm') === true;
235 * Fill and return a SocialAccount from the given driver name and SocialUser.
237 public function newSocialAccount(string $socialDriver, SocialUser $socialUser): SocialAccount
239 return new SocialAccount([
240 'driver' => $socialDriver,
241 'driver_id' => $socialUser->getId(),
242 'avatar' => $socialUser->getAvatar()
247 * Detach a social account from a user.
249 public function detachSocialAccount(string $socialDriver): void
251 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
255 * Provide redirect options per service for the Laravel Socialite driver
257 protected function getDriverForRedirect(string $driverName): Provider
259 $driver = $this->socialite->driver($driverName);
261 if ($driverName === 'google' && config('services.google.select_account')) {
262 $driver->with(['prompt' => 'select_account']);
264 if ($driverName === 'azure') {
265 $driver->with(['resource' => 'https://graph.windows.net']);
268 if (isset($this->configureForRedirectCallbacks[$driverName])) {
269 $this->configureForRedirectCallbacks[$driverName]($driver);
276 * Add a custom socialite driver to be used.
277 * Driver name should be lower_snake_case.
278 * Config array should mirror the structure of a service
279 * within the `Config/services.php` file.
280 * Handler should be a Class@method handler to the SocialiteWasCalled event.
282 public function addSocialDriver(
285 string $socialiteHandler,
286 callable $configureForRedirect = null
288 $this->validSocialDrivers[] = $driverName;
289 config()->set('services.' . $driverName, $config);
290 config()->set('services.' . $driverName . '.redirect', url('/login/service/' . $driverName . '/callback'));
291 config()->set('services.' . $driverName . '.name', $config['name'] ?? $driverName);
292 Event::listen(SocialiteWasCalled::class, $socialiteHandler);
293 if (!is_null($configureForRedirect)) {
294 $this->configureForRedirectCallbacks[$driverName] = $configureForRedirect;