1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\SocialAccount;
4 use BookStack\Auth\UserRepo;
5 use BookStack\Exceptions\SocialDriverNotConfigured;
6 use BookStack\Exceptions\SocialSignInAccountNotUsed;
7 use BookStack\Exceptions\UserRegistrationException;
8 use Illuminate\Support\Str;
9 use Laravel\Socialite\Contracts\Factory as Socialite;
10 use Laravel\Socialite\Contracts\Provider;
11 use Laravel\Socialite\Contracts\User as SocialUser;
12 use Symfony\Component\HttpFoundation\RedirectResponse;
14 class SocialAuthService
19 protected $socialAccount;
21 protected $validSocialDrivers = ['google', 'github', 'facebook', 'slack', 'twitter', 'azure', 'okta', 'gitlab', 'twitch', 'discord'];
24 * SocialAuthService constructor.
26 public function __construct(UserRepo $userRepo, Socialite $socialite, SocialAccount $socialAccount)
28 $this->userRepo = $userRepo;
29 $this->socialite = $socialite;
30 $this->socialAccount = $socialAccount;
35 * Start the social login path.
36 * @throws SocialDriverNotConfigured
38 public function startLogIn(string $socialDriver): RedirectResponse
40 $driver = $this->validateDriver($socialDriver);
41 return $this->getSocialDriver($driver)->redirect();
45 * Start the social registration process
46 * @throws SocialDriverNotConfigured
48 public function startRegister(string $socialDriver): RedirectResponse
50 $driver = $this->validateDriver($socialDriver);
51 return $this->getSocialDriver($driver)->redirect();
55 * Handle the social registration process on callback.
56 * @throws UserRegistrationException
58 public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser): SocialUser
60 // Check social account has not already been used
61 if ($this->socialAccount->where('driver_id', '=', $socialUser->getId())->exists()) {
62 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver]), '/login');
65 if ($this->userRepo->getByEmail($socialUser->getEmail())) {
66 $email = $socialUser->getEmail();
67 throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $email]), '/login');
74 * Get the social user details via the social driver.
75 * @throws SocialDriverNotConfigured
77 public function getSocialUser(string $socialDriver): SocialUser
79 $driver = $this->validateDriver($socialDriver);
80 return $this->socialite->driver($driver)->user();
84 * Handle the login process on a oAuth callback.
85 * @throws SocialSignInAccountNotUsed
87 public function handleLoginCallback(string $socialDriver, SocialUser $socialUser)
89 $socialId = $socialUser->getId();
91 // Get any attached social accounts or users
92 $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
93 $isLoggedIn = auth()->check();
94 $currentUser = user();
95 $titleCaseDriver = Str::title($socialDriver);
97 // When a user is not logged in and a matching SocialAccount exists,
98 // Simply log the user into the application.
99 if (!$isLoggedIn && $socialAccount !== null) {
100 auth()->login($socialAccount->user);
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 $this->fillSocialAccount($socialDriver, $socialUser);
108 $currentUser->socialAccounts()->save($this->socialAccount);
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 fillSocialAccount(string $socialDriver, SocialUser $socialUser): SocialAccount
209 $this->socialAccount->fill([
210 'driver' => $socialDriver,
211 'driver_id' => $socialUser->getId(),
212 'avatar' => $socialUser->getAvatar()
214 return $this->socialAccount;
218 * Detach a social account from a user.
219 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
221 public function detachSocialAccount(string $socialDriver)
223 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
227 * Provide redirect options per service for the Laravel Socialite driver
229 public function getSocialDriver(string $driverName): Provider
231 $driver = $this->socialite->driver($driverName);
233 if ($driverName === 'google' && config('services.google.select_account')) {
234 $driver->with(['prompt' => 'select_account']);
236 if ($driverName === 'azure') {
237 $driver->with(['resource' => 'https://graph.windows.net']);