]> BookStack Code Mirror - bookstack/blob - app/Services/SocialAuthService.php
Made social accounts attachable
[bookstack] / app / Services / SocialAuthService.php
1 <?php namespace Oxbow\Services;
2
3 use Laravel\Socialite\Contracts\Factory as Socialite;
4 use Oxbow\Exceptions\SocialDriverNotConfigured;
5 use Oxbow\Exceptions\SocialSignInException;
6 use Oxbow\Repos\UserRepo;
7 use Oxbow\SocialAccount;
8 use Oxbow\User;
9
10 class SocialAuthService
11 {
12
13     protected $userRepo;
14     protected $socialite;
15     protected $socialAccount;
16
17     protected $validSocialDrivers = ['google', 'github'];
18
19     /**
20      * SocialAuthService constructor.
21      * @param UserRepo      $userRepo
22      * @param Socialite     $socialite
23      * @param SocialAccount $socialAccount
24      */
25     public function __construct(UserRepo $userRepo, Socialite $socialite, SocialAccount $socialAccount)
26     {
27         $this->userRepo = $userRepo;
28         $this->socialite = $socialite;
29         $this->socialAccount = $socialAccount;
30     }
31
32     /**
33      * Start the social login path.
34      * @param $socialDriver
35      * @return \Symfony\Component\HttpFoundation\RedirectResponse
36      * @throws SocialDriverNotConfigured
37      */
38     public function startLogIn($socialDriver)
39     {
40         $driver = $this->validateDriver($socialDriver);
41         return $this->socialite->driver($driver)->redirect();
42     }
43
44     /**
45      * Get a user from socialite after a oAuth callback.
46      *
47      * @param $socialDriver
48      * @return User
49      * @throws SocialDriverNotConfigured
50      * @throws SocialSignInException
51      */
52     public function handleCallback($socialDriver)
53     {
54         $driver = $this->validateDriver($socialDriver);
55
56         // Get user details from social driver
57         $socialUser = $this->socialite->driver($driver)->user();
58         $socialId = $socialUser->getId();
59
60         // Get any attached social accounts or users
61         $socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
62         $user = $this->userRepo->getByEmail($socialUser->getEmail());
63         $isLoggedIn = \Auth::check();
64         $currentUser = \Auth::user();
65
66         // When a user is not logged in but a matching SocialAccount exists,
67         // Log the user found on the SocialAccount into the application.
68         if (!$isLoggedIn && $socialAccount !== null) {
69             return $this->logUserIn($socialAccount->user);
70         }
71
72         // When a user is logged in but the social account does not exist,
73         // Create the social account and attach it to the user & redirect to the profile page.
74         if ($isLoggedIn && $socialAccount === null) {
75             $this->fillSocialAccount($socialDriver, $socialUser);
76             $currentUser->socialAccounts()->save($this->socialAccount);
77             \Session::flash('success', title_case($socialDriver) . ' account was successfully attached to your profile.');
78             return redirect($currentUser->getEditUrl());
79         }
80
81         // When a user is logged in and the social account exists and is already linked to the current user.
82         if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
83             \Session::flash('error', 'This ' . title_case($socialDriver) . ' account is already attached to your profile.');
84             return redirect($currentUser->getEditUrl());
85         }
86
87         // When a user is logged in, A social account exists but the users do not match.
88         // Change the user that the social account is assigned to.
89         if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
90             $socialAccount->user_id = $currentUser->id;
91             $socialAccount->save();
92             \Session::flash('success', 'This ' . title_case($socialDriver) . ' account is now attached to your profile.');
93         }
94
95         if ($user === null) {
96             throw new SocialSignInException('A system user with the email ' . $socialUser->getEmail() .
97                 ' was not found and this ' . $socialDriver . ' account is not linked to any users.', '/login');
98         }
99         return $this->authenticateUserWithNewSocialAccount($user, $socialUser, $socialUser);
100     }
101
102     /**
103      * Logs a user in and creates a new social account entry for future usage.
104      * @param User                              $user
105      * @param string                            $socialDriver
106      * @param \Laravel\Socialite\Contracts\User $socialUser
107      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
108      */
109     private function authenticateUserWithNewSocialAccount($user, $socialDriver, $socialUser)
110     {
111         $this->fillSocialAccount($socialDriver, $socialUser);
112         $user->socialAccounts()->save($this->socialAccount);
113         return $this->logUserIn($user);
114     }
115
116     private function logUserIn($user)
117     {
118         \Auth::login($user);
119         return redirect('/');
120     }
121
122     /**
123      * Ensure the social driver is correct and supported.
124      *
125      * @param $socialDriver
126      * @return string
127      * @throws SocialDriverNotConfigured
128      */
129     private function validateDriver($socialDriver)
130     {
131         $driver = trim(strtolower($socialDriver));
132
133         if (!in_array($driver, $this->validSocialDrivers)) abort(404, 'Social Driver Not Found');
134         if (!$this->checkDriverConfigured($driver)) throw new SocialDriverNotConfigured;
135
136         return $driver;
137     }
138
139     /**
140      * Check a social driver has been configured correctly.
141      * @param $driver
142      * @return bool
143      */
144     private function checkDriverConfigured($driver)
145     {
146         $upperName = strtoupper($driver);
147         $config = [env($upperName . '_APP_ID', false), env($upperName . '_APP_SECRET', false), env('APP_URL', false)];
148         return (!in_array(false, $config) && !in_array(null, $config));
149     }
150
151     /**
152      * Gets the names of the active social drivers.
153      * @return array
154      */
155     public function getActiveDrivers()
156     {
157         $activeDrivers = [];
158         foreach ($this->validSocialDrivers as $driverName) {
159             if ($this->checkDriverConfigured($driverName)) {
160                 $activeDrivers[$driverName] = true;
161             }
162         }
163         return $activeDrivers;
164     }
165
166     /**
167      * @param $socialDriver
168      * @param $socialUser
169      */
170     private function fillSocialAccount($socialDriver, $socialUser)
171     {
172         $this->socialAccount->fill([
173             'driver'    => $socialDriver,
174             'driver_id' => $socialUser->getId(),
175             'avatar'    => $socialUser->getAvatar()
176         ]);
177     }
178
179     /**
180      * Detach a social account from a user.
181      * @param $socialDriver
182      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
183      */
184     public function detachSocialAccount($socialDriver)
185     {
186         \Auth::user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
187         \Session::flash('success', $socialDriver . ' account successfully detached');
188         return redirect(\Auth::user()->getEditUrl());
189     }
190
191 }