]> BookStack Code Mirror - bookstack/blob - app/Services/SocialAuthService.php
Updated grid view to use CSS grid and flexbox
[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'];
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)) {
154             abort(404, trans('errors.social_driver_not_found'));
155         }
156         if (!$this->checkDriverConfigured($driver)) {
157             throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => title_case($socialDriver)]));
158         }
159
160         return $driver;
161     }
162
163     /**
164      * Check a social driver has been configured correctly.
165      * @param $driver
166      * @return bool
167      */
168     private function checkDriverConfigured($driver)
169     {
170         $lowerName = strtolower($driver);
171         $configPrefix = 'services.' . $lowerName . '.';
172         $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')];
173         return !in_array(false, $config) && !in_array(null, $config);
174     }
175
176     /**
177      * Gets the names of the active social drivers.
178      * @return array
179      */
180     public function getActiveDrivers()
181     {
182         $activeDrivers = [];
183         foreach ($this->validSocialDrivers as $driverKey) {
184             if ($this->checkDriverConfigured($driverKey)) {
185                 $activeDrivers[$driverKey] = $this->getDriverName($driverKey);
186             }
187         }
188         return $activeDrivers;
189     }
190
191     /**
192      * Get the presentational name for a driver.
193      * @param $driver
194      * @return mixed
195      */
196     public function getDriverName($driver)
197     {
198         return config('services.' . strtolower($driver) . '.name');
199     }
200
201     /**
202      * @param string                            $socialDriver
203      * @param \Laravel\Socialite\Contracts\User $socialUser
204      * @return SocialAccount
205      */
206     public function fillSocialAccount($socialDriver, $socialUser)
207     {
208         $this->socialAccount->fill([
209             'driver'    => $socialDriver,
210             'driver_id' => $socialUser->getId(),
211             'avatar'    => $socialUser->getAvatar()
212         ]);
213         return $this->socialAccount;
214     }
215
216     /**
217      * Detach a social account from a user.
218      * @param $socialDriver
219      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
220      */
221     public function detachSocialAccount($socialDriver)
222     {
223         user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
224         session()->flash('success', trans('settings.users_social_disconnected', ['socialAccount' => title_case($socialDriver)]));
225         return redirect(user()->getEditUrl());
226     }
227 }