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