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