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