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