]> BookStack Code Mirror - bookstack/blob - app/Services/SocialAuthService.php
Refactored the code to first check for the permissions before sorting the book.
[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'];
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 logged in but the social account does not exist,
113         // Create the social account and attach it to the user & redirect to the profile page.
114         if ($isLoggedIn && $socialAccount === null) {
115             $this->fillSocialAccount($socialDriver, $socialUser);
116             $currentUser->socialAccounts()->save($this->socialAccount);
117             session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => title_case($socialDriver)]));
118             return redirect($currentUser->getEditUrl());
119         }
120
121         // When a user is logged in and the social account exists and is already linked to the current user.
122         if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
123             session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => title_case($socialDriver)]));
124             return redirect($currentUser->getEditUrl());
125         }
126
127         // When a user is logged in, A social account exists but the users do not match.
128         if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
129             session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => title_case($socialDriver)]));
130             return redirect($currentUser->getEditUrl());
131         }
132
133         // Otherwise let the user know this social account is not used by anyone.
134         $message = trans('errors.social_account_not_used', ['socialAccount' => title_case($socialDriver)]);
135         if (setting('registration-enabled')) {
136             $message .= trans('errors.social_account_register_instructions', ['socialAccount' => title_case($socialDriver)]);
137         }
138         
139         throw new SocialSignInException($message, '/login');
140     }
141
142     /**
143      * Ensure the social driver is correct and supported.
144      *
145      * @param $socialDriver
146      * @return string
147      * @throws SocialDriverNotConfigured
148      */
149     private function validateDriver($socialDriver)
150     {
151         $driver = trim(strtolower($socialDriver));
152
153         if (!in_array($driver, $this->validSocialDrivers)) abort(404, trans('errors.social_driver_not_found'));
154         if (!$this->checkDriverConfigured($driver)) throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => title_case($socialDriver)]));
155
156         return $driver;
157     }
158
159     /**
160      * Check a social driver has been configured correctly.
161      * @param $driver
162      * @return bool
163      */
164     private function checkDriverConfigured($driver)
165     {
166         $lowerName = strtolower($driver);
167         $configPrefix = 'services.' . $lowerName . '.';
168         $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
169         return !in_array(false, $config) && !in_array(null, $config);
170     }
171
172     /**
173      * Gets the names of the active social drivers.
174      * @return array
175      */
176     public function getActiveDrivers()
177     {
178         $activeDrivers = [];
179         foreach ($this->validSocialDrivers as $driverKey) {
180             if ($this->checkDriverConfigured($driverKey)) {
181                 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
182             }
183         }
184         return $activeDrivers;
185     }
186
187     /**
188      * Get the presentational name for a driver.
189      * @param $driver
190      * @return mixed
191      */
192     public function getDriverName($driver)
193     {
194         return config('services.' . strtolower($driver) . '.name');
195     }
196
197     /**
198      * @param string                            $socialDriver
199      * @param \Laravel\Socialite\Contracts\User $socialUser
200      * @return SocialAccount
201      */
202     public function fillSocialAccount($socialDriver, $socialUser)
203     {
204         $this->socialAccount->fill([
205             'driver'    => $socialDriver,
206             'driver_id' => $socialUser->getId(),
207             'avatar'    => $socialUser->getAvatar()
208         ]);
209         return $this->socialAccount;
210     }
211
212     /**
213      * Detach a social account from a user.
214      * @param $socialDriver
215      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
216      */
217     public function detachSocialAccount($socialDriver)
218     {
219         user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
220         session()->flash('success', trans('settings.users_social_disconnected', ['socialAccount' => title_case($socialDriver)]));
221         return redirect(user()->getEditUrl());
222     }
223
224 }