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