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