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