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