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