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