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 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 protected $socialAccount;
23 protected $validSocialDrivers = ['google', 'github', 'facebook', 'slack', 'twitter', 'azure', 'okta', 'gitlab', 'twitch', 'discord'];
26 * SocialAuthService constructor.
28 public function __construct(Socialite $socialite)
30 $this->socialite = $socialite;
34 * Start the social login path.
35 * @throws SocialDriverNotConfigured
37 public function startLogIn(string $socialDriver): RedirectResponse
39 $driver = $this->validateDriver($socialDriver);
40 return $this->getSocialDriver($driver)->redirect();
44 * Start the social registration process
45 * @throws SocialDriverNotConfigured
47 public function startRegister(string $socialDriver): RedirectResponse
49 $driver = $this->validateDriver($socialDriver);
50 return $this->getSocialDriver($driver)->redirect();
54 * Handle the social registration process on callback.
55 * @throws UserRegistrationException
57 public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser): SocialUser
59 // Check social account has not already been used
60 if (SocialAccount::query()->where('driver_id', '=', $socialUser->getId())->exists()) {
61 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver]), '/login');
64 if (User::query()->where('email', '=', $socialUser->getEmail())->exists()) {
65 $email = $socialUser->getEmail();
66 throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $email]), '/login');
73 * Get the social user details via the social driver.
74 * @throws SocialDriverNotConfigured
76 public function getSocialUser(string $socialDriver): SocialUser
78 $driver = $this->validateDriver($socialDriver);
79 return $this->socialite->driver($driver)->user();
83 * Handle the login process on a oAuth callback.
84 * @throws SocialSignInAccountNotUsed
86 public function handleLoginCallback(string $socialDriver, SocialUser $socialUser)
88 $socialId = $socialUser->getId();
90 // Get any attached social accounts or users
91 $socialAccount = SocialAccount::query()->where('driver_id', '=', $socialId)->first();
92 $isLoggedIn = auth()->check();
93 $currentUser = user();
94 $titleCaseDriver = Str::title($socialDriver);
96 // When a user is not logged in and a matching SocialAccount exists,
97 // Simply log the user into the application.
98 if (!$isLoggedIn && $socialAccount !== null) {
99 auth()->login($socialAccount->user);
100 Activity::add(ActivityType::AUTH_LOGIN, $socialAccount);
101 return redirect()->intended('/');
104 // When a user is logged in but the social account does not exist,
105 // Create the social account and attach it to the user & redirect to the profile page.
106 if ($isLoggedIn && $socialAccount === null) {
107 $account = $this->newSocialAccount($socialDriver, $socialUser);
108 $currentUser->socialAccounts()->save($account);
109 session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => $titleCaseDriver]));
110 return redirect($currentUser->getEditUrl());
113 // When a user is logged in and the social account exists and is already linked to the current user.
114 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
115 session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => $titleCaseDriver]));
116 return redirect($currentUser->getEditUrl());
119 // When a user is logged in, A social account exists but the users do not match.
120 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
121 session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => $titleCaseDriver]));
122 return redirect($currentUser->getEditUrl());
125 // Otherwise let the user know this social account is not used by anyone.
126 $message = trans('errors.social_account_not_used', ['socialAccount' => $titleCaseDriver]);
127 if (setting('registration-enabled') && config('auth.method') !== 'ldap' && config('auth.method') !== 'saml2') {
128 $message .= trans('errors.social_account_register_instructions', ['socialAccount' => $titleCaseDriver]);
131 throw new SocialSignInAccountNotUsed($message, '/login');
135 * Ensure the social driver is correct and supported.
136 * @throws SocialDriverNotConfigured
138 protected function validateDriver(string $socialDriver): string
140 $driver = trim(strtolower($socialDriver));
142 if (!in_array($driver, $this->validSocialDrivers)) {
143 abort(404, trans('errors.social_driver_not_found'));
146 if (!$this->checkDriverConfigured($driver)) {
147 throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => Str::title($socialDriver)]));
154 * Check a social driver has been configured correctly.
156 protected function checkDriverConfigured(string $driver): bool
158 $lowerName = strtolower($driver);
159 $configPrefix = 'services.' . $lowerName . '.';
160 $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
161 return !in_array(false, $config) && !in_array(null, $config);
165 * Gets the names of the active social drivers.
167 public function getActiveDrivers(): array
171 foreach ($this->validSocialDrivers as $driverKey) {
172 if ($this->checkDriverConfigured($driverKey)) {
173 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
177 return $activeDrivers;
181 * Get the presentational name for a driver.
183 public function getDriverName(string $driver): string
185 return config('services.' . strtolower($driver) . '.name');
189 * Check if the current config for the given driver allows auto-registration.
191 public function driverAutoRegisterEnabled(string $driver): bool
193 return config('services.' . strtolower($driver) . '.auto_register') === true;
197 * Check if the current config for the given driver allow email address auto-confirmation.
199 public function driverAutoConfirmEmailEnabled(string $driver): bool
201 return config('services.' . strtolower($driver) . '.auto_confirm') === true;
205 * Fill and return a SocialAccount from the given driver name and SocialUser.
207 public function newSocialAccount(string $socialDriver, SocialUser $socialUser): SocialAccount
209 return new SocialAccount([
210 'driver' => $socialDriver,
211 'driver_id' => $socialUser->getId(),
212 'avatar' => $socialUser->getAvatar()
217 * Detach a social account from a user.
219 public function detachSocialAccount(string $socialDriver): void
221 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
225 * Provide redirect options per service for the Laravel Socialite driver
227 public function getSocialDriver(string $driverName): Provider
229 $driver = $this->socialite->driver($driverName);
231 if ($driverName === 'google' && config('services.google.select_account')) {
232 $driver->with(['prompt' => 'select_account']);
234 if ($driverName === 'azure') {
235 $driver->with(['resource' => 'https://graph.windows.net']);
242 * Add a custom socialite driver to be used.
243 * Driver name should be lower_snake_case.
244 * Config array should mirror the structure of a service
245 * within the `Config/services.php` file.
246 * Handler should be a Class@method handler to the SocialiteWasCalled event.
248 public function addSocialDriver(string $driverName, array $config, string $socialiteHandler)
250 $this->validSocialDrivers[] = $driverName;
251 config()->set('services.' . $driverName, $config);
252 config()->set('services.' . $driverName . '.redirect', url('/login/service/' . $driverName . '/callback'));
253 config()->set('services.' . $driverName . '.name', $config['name'] ?? $driverName);
254 Event::listen(SocialiteWasCalled::class, $socialiteHandler);