]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/SocialAuthService.php
0df5ceb5ee679fe655c33a1fafd78f86226ab7af
[bookstack] / app / Auth / Access / SocialAuthService.php
1 <?php
2
3 namespace BookStack\Auth\Access;
4
5 use BookStack\Auth\SocialAccount;
6 use BookStack\Auth\User;
7 use BookStack\Exceptions\SocialDriverNotConfigured;
8 use BookStack\Exceptions\SocialSignInAccountNotUsed;
9 use BookStack\Exceptions\UserRegistrationException;
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 Laravel\Socialite\Two\GoogleProvider;
16 use SocialiteProviders\Manager\SocialiteWasCalled;
17 use Symfony\Component\HttpFoundation\RedirectResponse;
18
19 class SocialAuthService
20 {
21     /**
22      * The core socialite library used.
23      *
24      * @var Socialite
25      */
26     protected $socialite;
27
28     /**
29      * @var LoginService
30      */
31     protected $loginService;
32
33     /**
34      * The default built-in social drivers we support.
35      *
36      * @var string[]
37      */
38     protected $validSocialDrivers = [
39         'google',
40         'github',
41         'facebook',
42         'slack',
43         'twitter',
44         'azure',
45         'okta',
46         'gitlab',
47         'twitch',
48         'discord',
49     ];
50
51     /**
52      * Callbacks to run when configuring a social driver
53      * for an initial redirect action.
54      * Array is keyed by social driver name.
55      * Callbacks are passed an instance of the driver.
56      *
57      * @var array<string, callable>
58      */
59     protected $configureForRedirectCallbacks = [];
60
61     /**
62      * SocialAuthService constructor.
63      */
64     public function __construct(Socialite $socialite, LoginService $loginService)
65     {
66         $this->socialite = $socialite;
67         $this->loginService = $loginService;
68     }
69
70     /**
71      * Start the social login path.
72      *
73      * @throws SocialDriverNotConfigured
74      */
75     public function startLogIn(string $socialDriver): RedirectResponse
76     {
77         $driver = $this->validateDriver($socialDriver);
78
79         return $this->getDriverForRedirect($driver)->redirect();
80     }
81
82     /**
83      * Start the social registration process.
84      *
85      * @throws SocialDriverNotConfigured
86      */
87     public function startRegister(string $socialDriver): RedirectResponse
88     {
89         $driver = $this->validateDriver($socialDriver);
90
91         return $this->getDriverForRedirect($driver)->redirect();
92     }
93
94     /**
95      * Handle the social registration process on callback.
96      *
97      * @throws UserRegistrationException
98      */
99     public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser): SocialUser
100     {
101         // Check social account has not already been used
102         if (SocialAccount::query()->where('driver_id', '=', $socialUser->getId())->exists()) {
103             throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount' => $socialDriver]), '/login');
104         }
105
106         if (User::query()->where('email', '=', $socialUser->getEmail())->exists()) {
107             $email = $socialUser->getEmail();
108
109             throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $email]), '/login');
110         }
111
112         return $socialUser;
113     }
114
115     /**
116      * Get the social user details via the social driver.
117      *
118      * @throws SocialDriverNotConfigured
119      */
120     public function getSocialUser(string $socialDriver): SocialUser
121     {
122         $driver = $this->validateDriver($socialDriver);
123
124         return $this->socialite->driver($driver)->user();
125     }
126
127     /**
128      * Handle the login process on a oAuth callback.
129      *
130      * @throws SocialSignInAccountNotUsed
131      */
132     public function handleLoginCallback(string $socialDriver, SocialUser $socialUser)
133     {
134         $socialId = $socialUser->getId();
135
136         // Get any attached social accounts or users
137         $socialAccount = SocialAccount::query()->where('driver_id', '=', $socialId)->first();
138         $isLoggedIn = auth()->check();
139         $currentUser = user();
140         $titleCaseDriver = Str::title($socialDriver);
141
142         // When a user is not logged in and a matching SocialAccount exists,
143         // Simply log the user into the application.
144         if (!$isLoggedIn && $socialAccount !== null) {
145             $this->loginService->login($socialAccount->user, $socialDriver);
146
147             return redirect()->intended('/');
148         }
149
150         // When a user is logged in but the social account does not exist,
151         // Create the social account and attach it to the user & redirect to the profile page.
152         if ($isLoggedIn && $socialAccount === null) {
153             $account = $this->newSocialAccount($socialDriver, $socialUser);
154             $currentUser->socialAccounts()->save($account);
155             session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => $titleCaseDriver]));
156
157             return redirect($currentUser->getEditUrl());
158         }
159
160         // When a user is logged in and the social account exists and is already linked to the current user.
161         if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
162             session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => $titleCaseDriver]));
163
164             return redirect($currentUser->getEditUrl());
165         }
166
167         // When a user is logged in, A social account exists but the users do not match.
168         if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
169             session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => $titleCaseDriver]));
170
171             return redirect($currentUser->getEditUrl());
172         }
173
174         // Otherwise let the user know this social account is not used by anyone.
175         $message = trans('errors.social_account_not_used', ['socialAccount' => $titleCaseDriver]);
176         if (setting('registration-enabled') && config('auth.method') !== 'ldap' && config('auth.method') !== 'saml2') {
177             $message .= trans('errors.social_account_register_instructions', ['socialAccount' => $titleCaseDriver]);
178         }
179
180         throw new SocialSignInAccountNotUsed($message, '/login');
181     }
182
183     /**
184      * Ensure the social driver is correct and supported.
185      *
186      * @throws SocialDriverNotConfigured
187      */
188     protected function validateDriver(string $socialDriver): string
189     {
190         $driver = trim(strtolower($socialDriver));
191
192         if (!in_array($driver, $this->validSocialDrivers)) {
193             abort(404, trans('errors.social_driver_not_found'));
194         }
195
196         if (!$this->checkDriverConfigured($driver)) {
197             throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => Str::title($socialDriver)]));
198         }
199
200         return $driver;
201     }
202
203     /**
204      * Check a social driver has been configured correctly.
205      */
206     protected function checkDriverConfigured(string $driver): bool
207     {
208         $lowerName = strtolower($driver);
209         $configPrefix = 'services.' . $lowerName . '.';
210         $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
211
212         return !in_array(false, $config) && !in_array(null, $config);
213     }
214
215     /**
216      * Gets the names of the active social drivers.
217      */
218     public function getActiveDrivers(): array
219     {
220         $activeDrivers = [];
221
222         foreach ($this->validSocialDrivers as $driverKey) {
223             if ($this->checkDriverConfigured($driverKey)) {
224                 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
225             }
226         }
227
228         return $activeDrivers;
229     }
230
231     /**
232      * Get the presentational name for a driver.
233      */
234     public function getDriverName(string $driver): string
235     {
236         return config('services.' . strtolower($driver) . '.name');
237     }
238
239     /**
240      * Check if the current config for the given driver allows auto-registration.
241      */
242     public function driverAutoRegisterEnabled(string $driver): bool
243     {
244         return config('services.' . strtolower($driver) . '.auto_register') === true;
245     }
246
247     /**
248      * Check if the current config for the given driver allow email address auto-confirmation.
249      */
250     public function driverAutoConfirmEmailEnabled(string $driver): bool
251     {
252         return config('services.' . strtolower($driver) . '.auto_confirm') === true;
253     }
254
255     /**
256      * Fill and return a SocialAccount from the given driver name and SocialUser.
257      */
258     public function newSocialAccount(string $socialDriver, SocialUser $socialUser): SocialAccount
259     {
260         return new SocialAccount([
261             'driver'    => $socialDriver,
262             'driver_id' => $socialUser->getId(),
263             'avatar'    => $socialUser->getAvatar(),
264         ]);
265     }
266
267     /**
268      * Detach a social account from a user.
269      */
270     public function detachSocialAccount(string $socialDriver): void
271     {
272         user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
273     }
274
275     /**
276      * Provide redirect options per service for the Laravel Socialite driver.
277      */
278     protected function getDriverForRedirect(string $driverName): Provider
279     {
280         $driver = $this->socialite->driver($driverName);
281
282         if ($driver instanceof GoogleProvider && config('services.google.select_account')) {
283             $driver->with(['prompt' => 'select_account']);
284         }
285
286         if (isset($this->configureForRedirectCallbacks[$driverName])) {
287             $this->configureForRedirectCallbacks[$driverName]($driver);
288         }
289
290         return $driver;
291     }
292
293     /**
294      * Add a custom socialite driver to be used.
295      * Driver name should be lower_snake_case.
296      * Config array should mirror the structure of a service
297      * within the `Config/services.php` file.
298      * Handler should be a Class@method handler to the SocialiteWasCalled event.
299      */
300     public function addSocialDriver(
301         string $driverName,
302         array $config,
303         string $socialiteHandler,
304         callable $configureForRedirect = null
305     ) {
306         $this->validSocialDrivers[] = $driverName;
307         config()->set('services.' . $driverName, $config);
308         config()->set('services.' . $driverName . '.redirect', url('/login/service/' . $driverName . '/callback'));
309         config()->set('services.' . $driverName . '.name', $config['name'] ?? $driverName);
310         Event::listen(SocialiteWasCalled::class, $socialiteHandler);
311         if (!is_null($configureForRedirect)) {
312             $this->configureForRedirectCallbacks[$driverName] = $configureForRedirect;
313         }
314     }
315 }