1 <?php namespace BookStack\Services;
3 use BookStack\Http\Requests\Request;
4 use GuzzleHttp\Exception\ClientException;
5 use Laravel\Socialite\Contracts\Factory as Socialite;
6 use BookStack\Exceptions\SocialDriverNotConfigured;
7 use BookStack\Exceptions\SocialSignInException;
8 use BookStack\Exceptions\UserRegistrationException;
9 use BookStack\Repos\UserRepo;
10 use BookStack\SocialAccount;
12 class SocialAuthService
17 protected $socialAccount;
19 protected $validSocialDrivers = ['google', 'github', 'facebook', 'slack', 'twitter', 'azure', 'okta', 'gitlab', 'twitch', 'discord'];
22 * SocialAuthService constructor.
23 * @param UserRepo $userRepo
24 * @param Socialite $socialite
25 * @param SocialAccount $socialAccount
27 public function __construct(UserRepo $userRepo, Socialite $socialite, SocialAccount $socialAccount)
29 $this->userRepo = $userRepo;
30 $this->socialite = $socialite;
31 $this->socialAccount = $socialAccount;
36 * Start the social login path.
37 * @param string $socialDriver
38 * @return \Symfony\Component\HttpFoundation\RedirectResponse
39 * @throws SocialDriverNotConfigured
41 public function startLogIn($socialDriver)
43 $driver = $this->validateDriver($socialDriver);
44 return $this->socialite->driver($driver)->redirect();
48 * Start the social registration process
49 * @param string $socialDriver
50 * @return \Symfony\Component\HttpFoundation\RedirectResponse
51 * @throws SocialDriverNotConfigured
53 public function startRegister($socialDriver)
55 $driver = $this->validateDriver($socialDriver);
56 return $this->socialite->driver($driver)->redirect();
60 * Handle the social registration process on callback.
61 * @param $socialDriver
62 * @return \Laravel\Socialite\Contracts\User
63 * @throws SocialDriverNotConfigured
64 * @throws UserRegistrationException
66 public function handleRegistrationCallback($socialDriver)
68 $driver = $this->validateDriver($socialDriver);
70 // Get user details from social driver
71 $socialUser = $this->socialite->driver($driver)->user();
73 // Check social account has not already been used
74 if ($this->socialAccount->where('driver_id', '=', $socialUser->getId())->exists()) {
75 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver]), '/login');
78 if ($this->userRepo->getByEmail($socialUser->getEmail())) {
79 $email = $socialUser->getEmail();
80 throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver, 'email' => $email]), '/login');
87 * Handle the login process on a oAuth callback.
88 * @param $socialDriver
89 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
90 * @throws SocialDriverNotConfigured
91 * @throws SocialSignInException
93 public function handleLoginCallback($socialDriver)
95 $driver = $this->validateDriver($socialDriver);
96 // Get user details from social driver
97 $socialUser = $this->socialite->driver($driver)->user();
98 $socialId = $socialUser->getId();
100 // Get any attached social accounts or users
101 $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
102 $isLoggedIn = auth()->check();
103 $currentUser = user();
105 // When a user is not logged in and a matching SocialAccount exists,
106 // Simply log the user into the application.
107 if (!$isLoggedIn && $socialAccount !== null) {
108 auth()->login($socialAccount->user);
109 return redirect()->intended('/');
112 // When a user is not logged in and no matching SocialAccount exists,
113 // If the auto social registration is enabled, attach the social account, create new user and log him in.
114 if (!$isLoggedIn && $socialAccount === null && setting('autosocialregistration-confirmation')) {
116 // Fill social account
117 $socialAccount = $this->fillSocialAccount($socialDriver, $socialUser);
119 // Create an array of the user data to create a new user instance
121 'name' => $socialUser->getName(),
122 'email' => $socialUser->getEmail(),
123 'password' => str_random(30)
126 // Check domain if domain restriction setting is set
127 if (setting('registration-restrict')) {
128 $restrictedEmailDomains = explode(',', str_replace(' ', '', setting('registration-restrict')));
129 $userEmailDomain = $domain = substr(strrchr($socialUser->getEmail(), "@"), 1);
130 if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
131 throw new SocialSignInException(trans('auth.registration_email_domain_invalid'), '/login');
135 // Register new user with autoVerifyEmail set to true and attach the social account
136 $newUser = $this->userRepo->registerNew($userData, true);
137 $newUser->socialAccounts()->save($socialAccount);
141 auth()->login($newUser);
143 return redirect()->intended('/');
146 // When a user is logged in but the social account does not exist,
147 // Create the social account and attach it to the user & redirect to the profile page.
148 if ($isLoggedIn && $socialAccount === null) {
149 $this->fillSocialAccount($socialDriver, $socialUser);
150 $currentUser->socialAccounts()->save($this->socialAccount);
151 session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => title_case($socialDriver)]));
152 return redirect($currentUser->getEditUrl());
155 // When a user is logged in and the social account exists and is already linked to the current user.
156 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
157 session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => title_case($socialDriver)]));
158 return redirect($currentUser->getEditUrl());
161 // When a user is logged in, A social account exists but the users do not match.
162 if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
163 session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => title_case($socialDriver)]));
164 return redirect($currentUser->getEditUrl());
167 // Otherwise let the user know this social account is not used by anyone.
168 $message = trans('errors.social_account_not_used', ['socialAccount' => title_case($socialDriver)]);
169 if (setting('registration-enabled')) {
170 $message .= trans('errors.social_account_register_instructions', ['socialAccount' => title_case($socialDriver)]);
173 throw new SocialSignInException($message, '/login');
177 * Ensure the social driver is correct and supported.
179 * @param $socialDriver
181 * @throws SocialDriverNotConfigured
183 private function validateDriver($socialDriver)
185 $driver = trim(strtolower($socialDriver));
187 if (!in_array($driver, $this->validSocialDrivers)) {
188 abort(404, trans('errors.social_driver_not_found'));
190 if (!$this->checkDriverConfigured($driver)) {
191 throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => title_case($socialDriver)]));
198 * Check a social driver has been configured correctly.
202 private function checkDriverConfigured($driver)
204 $lowerName = strtolower($driver);
205 $configPrefix = 'services.' . $lowerName . '.';
206 $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
207 return !in_array(false, $config) && !in_array(null, $config);
211 * Gets the names of the active social drivers.
214 public function getActiveDrivers()
217 foreach ($this->validSocialDrivers as $driverKey) {
218 if ($this->checkDriverConfigured($driverKey)) {
219 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
222 return $activeDrivers;
226 * Get the presentational name for a driver.
230 public function getDriverName($driver)
232 return config('services.' . strtolower($driver) . '.name');
236 * @param string $socialDriver
237 * @param \Laravel\Socialite\Contracts\User $socialUser
238 * @return SocialAccount
240 public function fillSocialAccount($socialDriver, $socialUser)
242 $this->socialAccount->fill([
243 'driver' => $socialDriver,
244 'driver_id' => $socialUser->getId(),
245 'avatar' => $socialUser->getAvatar()
247 return $this->socialAccount;
251 * Detach a social account from a user.
252 * @param $socialDriver
253 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
255 public function detachSocialAccount($socialDriver)
257 user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
258 session()->flash('success', trans('settings.users_social_disconnected', ['socialAccount' => title_case($socialDriver)]));
259 return redirect(user()->getEditUrl());