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