]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/SocialAuthService.php
Merge branch 'master' into master
[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\UserRepo;
6 use BookStack\Exceptions\SocialDriverNotConfigured;
7 use BookStack\Exceptions\SocialSignInAccountNotUsed;
8 use BookStack\Exceptions\UserRegistrationException;
9 use BookStack\Facades\Activity;
10 use Illuminate\Support\Str;
11 use Laravel\Socialite\Contracts\Factory as Socialite;
12 use Laravel\Socialite\Contracts\Provider;
13 use Laravel\Socialite\Contracts\User as SocialUser;
14 use Symfony\Component\HttpFoundation\RedirectResponse;
15
16 class SocialAuthService
17 {
18
19     protected $userRepo;
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(UserRepo $userRepo, Socialite $socialite, SocialAccount $socialAccount)
29     {
30         $this->userRepo = $userRepo;
31         $this->socialite = $socialite;
32         $this->socialAccount = $socialAccount;
33     }
34
35
36     /**
37      * Start the social login path.
38      * @throws SocialDriverNotConfigured
39      */
40     public function startLogIn(string $socialDriver): RedirectResponse
41     {
42         $driver = $this->validateDriver($socialDriver);
43         return $this->getSocialDriver($driver)->redirect();
44     }
45
46     /**
47      * Start the social registration process
48      * @throws SocialDriverNotConfigured
49      */
50     public function startRegister(string $socialDriver): RedirectResponse
51     {
52         $driver = $this->validateDriver($socialDriver);
53         return $this->getSocialDriver($driver)->redirect();
54     }
55
56     /**
57      * Handle the social registration process on callback.
58      * @throws UserRegistrationException
59      */
60     public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser): SocialUser
61     {
62         // Check social account has not already been used
63         if ($this->socialAccount->where('driver_id', '=', $socialUser->getId())->exists()) {
64             throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver]), '/login');
65         }
66
67         if ($this->userRepo->getByEmail($socialUser->getEmail())) {
68             $email = $socialUser->getEmail();
69             throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $email]), '/login');
70         }
71
72         return $socialUser;
73     }
74
75     /**
76      * Get the social user details via the social driver.
77      * @throws SocialDriverNotConfigured
78      */
79     public function getSocialUser(string $socialDriver): SocialUser
80     {
81         $driver = $this->validateDriver($socialDriver);
82         return $this->socialite->driver($driver)->user();
83     }
84
85     /**
86      * Handle the login process on a oAuth callback.
87      * @throws SocialSignInAccountNotUsed
88      */
89     public function handleLoginCallback(string $socialDriver, SocialUser $socialUser)
90     {
91         $socialId = $socialUser->getId();
92
93         // Get any attached social accounts or users
94         $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
95         $isLoggedIn = auth()->check();
96         $currentUser = user();
97         $titleCaseDriver = Str::title($socialDriver);
98
99         // When a user is not logged in and a matching SocialAccount exists,
100         // Simply log the user into the application.
101         if (!$isLoggedIn && $socialAccount !== null) {
102             auth()->login($socialAccount->user);
103             Activity::add(ActivityType::AUTH_LOGIN, $socialAccount);
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             $this->fillSocialAccount($socialDriver, $socialUser);
111             $currentUser->socialAccounts()->save($this->socialAccount);
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 fillSocialAccount(string $socialDriver, SocialUser $socialUser): SocialAccount
211     {
212         $this->socialAccount->fill([
213             'driver'    => $socialDriver,
214             'driver_id' => $socialUser->getId(),
215             'avatar'    => $socialUser->getAvatar()
216         ]);
217         return $this->socialAccount;
218     }
219
220     /**
221      * Detach a social account from a user.
222      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
223      */
224     public function detachSocialAccount(string $socialDriver)
225     {
226         user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
227     }
228
229     /**
230      * Provide redirect options per service for the Laravel Socialite driver
231      */
232     public function getSocialDriver(string $driverName): Provider
233     {
234         $driver = $this->socialite->driver($driverName);
235
236         if ($driverName === 'google' && config('services.google.select_account')) {
237             $driver->with(['prompt' => 'select_account']);
238         }
239         if ($driverName === 'azure') {
240             $driver->with(['resource' => 'https://graph.windows.net']);
241         }
242
243         return $driver;
244     }
245 }