1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Actions\ActivityType;
4 use BookStack\Auth\SocialAccount;
5 use BookStack\Auth\UserRepo;
6 use BookStack\Exceptions\SocialDriverNotConfigured;
7 use BookStack\Exceptions\SocialSignInAccountNotUsed;
8 use BookStack\Exceptions\UserRegistrationException;
9 use BookStack\Facades\Activity;
10 use Illuminate\Support\Str;
11 use Laravel\Socialite\Contracts\Factory as Socialite;
12 use Laravel\Socialite\Contracts\Provider;
13 use Laravel\Socialite\Contracts\User as SocialUser;
14 use Symfony\Component\HttpFoundation\RedirectResponse;
16 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(UserRepo $userRepo, Socialite $socialite, SocialAccount $socialAccount)
30 $this->userRepo = $userRepo;
31 $this->socialite = $socialite;
32 $this->socialAccount = $socialAccount;
37 * Start the social login path.
38 * @throws SocialDriverNotConfigured
40 public function startLogIn(string $socialDriver): RedirectResponse
42 $driver = $this->validateDriver($socialDriver);
43 return $this->getSocialDriver($driver)->redirect();
47 * Start the social registration process
48 * @throws SocialDriverNotConfigured
50 public function startRegister(string $socialDriver): RedirectResponse
52 $driver = $this->validateDriver($socialDriver);
53 return $this->getSocialDriver($driver)->redirect();
57 * Handle the social registration process on callback.
58 * @throws UserRegistrationException
60 public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser): SocialUser
62 // Check social account has not already been used
63 if ($this->socialAccount->where('driver_id', '=', $socialUser->getId())->exists()) {
64 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver]), '/login');
67 if ($this->userRepo->getByEmail($socialUser->getEmail())) {
68 $email = $socialUser->getEmail();
69 throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $email]), '/login');
76 * Get the social user details via the social driver.
77 * @throws SocialDriverNotConfigured
79 public function getSocialUser(string $socialDriver): SocialUser
81 $driver = $this->validateDriver($socialDriver);
82 return $this->socialite->driver($driver)->user();
86 * Handle the login process on a oAuth callback.
87 * @throws SocialSignInAccountNotUsed
89 public function handleLoginCallback(string $socialDriver, SocialUser $socialUser)
91 $socialId = $socialUser->getId();
93 // Get any attached social accounts or users
94 $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
95 $isLoggedIn = auth()->check();
96 $currentUser = user();
97 $titleCaseDriver = Str::title($socialDriver);
99 // When a user is not logged in and a matching SocialAccount exists,
100 // Simply log the user into the application.
101 if (!$isLoggedIn && $socialAccount !== null) {
102 auth()->login($socialAccount->user);
103 Activity::add(ActivityType::AUTH_LOGIN, $socialAccount);
104 return redirect()->intended('/');
107 // When a user is logged in but the social account does not exist,
108 // Create the social account and attach it to the user & redirect to the profile page.
109 if ($isLoggedIn && $socialAccount === null) {
110 $this->fillSocialAccount($socialDriver, $socialUser);
111 $currentUser->socialAccounts()->save($this->socialAccount);
112 session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => $titleCaseDriver]));
113 return redirect($currentUser->getEditUrl());
116 // When a user is logged in and the social account exists and is already linked to the current user.
117 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
118 session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => $titleCaseDriver]));
119 return redirect($currentUser->getEditUrl());
122 // When a user is logged in, A social account exists but the users do not match.
123 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
124 session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => $titleCaseDriver]));
125 return redirect($currentUser->getEditUrl());
128 // Otherwise let the user know this social account is not used by anyone.
129 $message = trans('errors.social_account_not_used', ['socialAccount' => $titleCaseDriver]);
130 if (setting('registration-enabled') && config('auth.method') !== 'ldap' && config('auth.method') !== 'saml2') {
131 $message .= trans('errors.social_account_register_instructions', ['socialAccount' => $titleCaseDriver]);
134 throw new SocialSignInAccountNotUsed($message, '/login');
138 * Ensure the social driver is correct and supported.
139 * @throws SocialDriverNotConfigured
141 protected function validateDriver(string $socialDriver): string
143 $driver = trim(strtolower($socialDriver));
145 if (!in_array($driver, $this->validSocialDrivers)) {
146 abort(404, trans('errors.social_driver_not_found'));
149 if (!$this->checkDriverConfigured($driver)) {
150 throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => Str::title($socialDriver)]));
157 * Check a social driver has been configured correctly.
159 protected function checkDriverConfigured(string $driver): bool
161 $lowerName = strtolower($driver);
162 $configPrefix = 'services.' . $lowerName . '.';
163 $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
164 return !in_array(false, $config) && !in_array(null, $config);
168 * Gets the names of the active social drivers.
170 public function getActiveDrivers(): array
174 foreach ($this->validSocialDrivers as $driverKey) {
175 if ($this->checkDriverConfigured($driverKey)) {
176 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
180 return $activeDrivers;
184 * Get the presentational name for a driver.
186 public function getDriverName(string $driver): string
188 return config('services.' . strtolower($driver) . '.name');
192 * Check if the current config for the given driver allows auto-registration.
194 public function driverAutoRegisterEnabled(string $driver): bool
196 return config('services.' . strtolower($driver) . '.auto_register') === true;
200 * Check if the current config for the given driver allow email address auto-confirmation.
202 public function driverAutoConfirmEmailEnabled(string $driver): bool
204 return config('services.' . strtolower($driver) . '.auto_confirm') === true;
208 * Fill and return a SocialAccount from the given driver name and SocialUser.
210 public function fillSocialAccount(string $socialDriver, SocialUser $socialUser): SocialAccount
212 $this->socialAccount->fill([
213 'driver' => $socialDriver,
214 'driver_id' => $socialUser->getId(),
215 'avatar' => $socialUser->getAvatar()
217 return $this->socialAccount;
221 * Detach a social account from a user.
222 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
224 public function detachSocialAccount(string $socialDriver)
226 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
230 * Provide redirect options per service for the Laravel Socialite driver
232 public function getSocialDriver(string $driverName): Provider
234 $driver = $this->socialite->driver($driverName);
236 if ($driverName === 'google' && config('services.google.select_account')) {
237 $driver->with(['prompt' => 'select_account']);
239 if ($driverName === 'azure') {
240 $driver->with(['resource' => 'https://graph.windows.net']);