]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/AuthController.php
ef44b2aef9834f62920338c211086223c9cf761e
[bookstack] / app / Http / Controllers / Auth / AuthController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Auth;
4
5 use BookStack\Exceptions\AuthException;
6 use BookStack\Exceptions\PrettyException;
7 use Illuminate\Contracts\Auth\Authenticatable;
8 use Illuminate\Http\Request;
9 use BookStack\Exceptions\SocialSignInException;
10 use BookStack\Exceptions\UserRegistrationException;
11 use BookStack\Repos\UserRepo;
12 use BookStack\Services\EmailConfirmationService;
13 use BookStack\Services\SocialAuthService;
14 use BookStack\SocialAccount;
15 use Validator;
16 use BookStack\Http\Controllers\Controller;
17 use Illuminate\Foundation\Auth\ThrottlesLogins;
18 use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
19
20 class AuthController extends Controller
21 {
22     /*
23     |--------------------------------------------------------------------------
24     | Registration & Login Controller
25     |--------------------------------------------------------------------------
26     |
27     | This controller handles the registration of new users, as well as the
28     | authentication of existing users. By default, this controller uses
29     | a simple trait to add these behaviors. Why don't you explore it?
30     |
31     */
32
33     use AuthenticatesAndRegistersUsers, ThrottlesLogins;
34
35     protected $redirectPath = '/';
36     protected $redirectAfterLogout = '/login';
37     protected $username = 'email';
38
39
40     protected $socialAuthService;
41     protected $emailConfirmationService;
42     protected $userRepo;
43
44     /**
45      * Create a new authentication controller instance.
46      * @param SocialAuthService $socialAuthService
47      * @param EmailConfirmationService $emailConfirmationService
48      * @param UserRepo $userRepo
49      */
50     public function __construct(SocialAuthService $socialAuthService, EmailConfirmationService $emailConfirmationService, UserRepo $userRepo)
51     {
52         $this->middleware('guest', ['only' => ['getLogin', 'postLogin', 'getRegister', 'postRegister']]);
53         $this->socialAuthService = $socialAuthService;
54         $this->emailConfirmationService = $emailConfirmationService;
55         $this->userRepo = $userRepo;
56         $this->username = config('auth.method') === 'standard' ? 'email' : 'username';
57         parent::__construct();
58     }
59
60     /**
61      * Get a validator for an incoming registration request.
62      * @param  array $data
63      * @return \Illuminate\Contracts\Validation\Validator
64      */
65     protected function validator(array $data)
66     {
67         return Validator::make($data, [
68             'name' => 'required|max:255',
69             'email' => 'required|email|max:255|unique:users',
70             'password' => 'required|min:6',
71         ]);
72     }
73
74     protected function checkRegistrationAllowed()
75     {
76         if (!setting('registration-enabled')) {
77             throw new UserRegistrationException('Registrations are currently disabled.', '/login');
78         }
79     }
80
81     /**
82      * Show the application registration form.
83      * @return \Illuminate\Http\Response
84      */
85     public function getRegister()
86     {
87         $this->checkRegistrationAllowed();
88         $socialDrivers = $this->socialAuthService->getActiveDrivers();
89         return view('auth.register', ['socialDrivers' => $socialDrivers]);
90     }
91
92     /**
93      * Handle a registration request for the application.
94      * @param  \Illuminate\Http\Request $request
95      * @return \Illuminate\Http\Response
96      * @throws UserRegistrationException
97      */
98     public function postRegister(Request $request)
99     {
100         $this->checkRegistrationAllowed();
101         $validator = $this->validator($request->all());
102
103         if ($validator->fails()) {
104             $this->throwValidationException(
105                 $request, $validator
106             );
107         }
108
109         $userData = $request->all();
110         return $this->registerUser($userData);
111     }
112
113
114     /**
115      * Overrides the action when a user is authenticated.
116      * If the user authenticated but does not exist in the user table we create them.
117      * @param Request $request
118      * @param Authenticatable $user
119      * @return \Illuminate\Http\RedirectResponse
120      * @throws AuthException
121      */
122     protected function authenticated(Request $request, Authenticatable $user)
123     {
124         // Explicitly log them out for now if they do no exist.
125         if (!$user->exists) auth()->logout($user);
126
127         if (!$user->exists && $user->email === null && !$request->has('email')) {
128             $request->flash();
129             session()->flash('request-email', true);
130             return redirect('/login');
131         }
132
133         if (!$user->exists && $user->email === null && $request->has('email')) {
134             $user->email = $request->get('email');
135         }
136
137         if (!$user->exists) {
138
139             // Check for users with same email already
140             $alreadyUser = $user->newQuery()->where('email', '=', $user->email)->count() > 0;
141             if ($alreadyUser) {
142                 throw new AuthException('A user with the email ' . $user->email . ' already exists but with different credentials.');
143             }
144
145             $user->save();
146             $this->userRepo->attachDefaultRole($user);
147             auth()->login($user);
148         }
149
150         return redirect()->intended($this->redirectPath());
151     }
152
153     /**
154      * Register a new user after a registration callback.
155      * @param $socialDriver
156      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
157      * @throws UserRegistrationException
158      */
159     protected function socialRegisterCallback($socialDriver)
160     {
161         $socialUser = $this->socialAuthService->handleRegistrationCallback($socialDriver);
162         $socialAccount = $this->socialAuthService->fillSocialAccount($socialDriver, $socialUser);
163
164         // Create an array of the user data to create a new user instance
165         $userData = [
166             'name' => $socialUser->getName(),
167             'email' => $socialUser->getEmail(),
168             'password' => str_random(30)
169         ];
170         return $this->registerUser($userData, $socialAccount);
171     }
172
173     /**
174      * The registrations flow for all users.
175      * @param array $userData
176      * @param bool|false|SocialAccount $socialAccount
177      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
178      * @throws UserRegistrationException
179      * @throws \BookStack\Exceptions\ConfirmationEmailException
180      */
181     protected function registerUser(array $userData, $socialAccount = false)
182     {
183         if (setting('registration-restrict')) {
184             $restrictedEmailDomains = explode(',', str_replace(' ', '', setting('registration-restrict')));
185             $userEmailDomain = $domain = substr(strrchr($userData['email'], "@"), 1);
186             if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
187                 throw new UserRegistrationException('That email domain does not have access to this application', '/register');
188             }
189         }
190
191         $newUser = $this->userRepo->registerNew($userData);
192         if ($socialAccount) {
193             $newUser->socialAccounts()->save($socialAccount);
194         }
195
196         if (setting('registration-confirmation') || setting('registration-restrict')) {
197             $newUser->email_confirmed = false;
198             $newUser->save();
199             $this->emailConfirmationService->sendConfirmation($newUser);
200             return redirect('/register/confirm');
201         }
202
203         $newUser->email_confirmed = true;
204
205         auth()->login($newUser);
206         session()->flash('success', 'Thanks for signing up! You are now registered and signed in.');
207         return redirect($this->redirectPath());
208     }
209
210     /**
211      * Show the page to tell the user to check their email
212      * and confirm their address.
213      */
214     public function getRegisterConfirmation()
215     {
216         return view('auth/register-confirm');
217     }
218
219     /**
220      * View the confirmation email as a standard web page.
221      * @param $token
222      * @return \Illuminate\View\View
223      * @throws UserRegistrationException
224      */
225     public function viewConfirmEmail($token)
226     {
227         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
228         return view('emails/email-confirmation', ['token' => $confirmation->token]);
229     }
230
231     /**
232      * Confirms an email via a token and logs the user into the system.
233      * @param $token
234      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
235      * @throws UserRegistrationException
236      */
237     public function confirmEmail($token)
238     {
239         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
240         $user = $confirmation->user;
241         $user->email_confirmed = true;
242         $user->save();
243         auth()->login($confirmation->user);
244         session()->flash('success', 'Your email has been confirmed!');
245         $this->emailConfirmationService->deleteConfirmationsByUser($user);
246         return redirect($this->redirectPath);
247     }
248
249     /**
250      * Shows a notice that a user's email address has not been confirmed,
251      * Also has the option to re-send the confirmation email.
252      * @return \Illuminate\View\View
253      */
254     public function showAwaitingConfirmation()
255     {
256         return view('auth/user-unconfirmed');
257     }
258
259     /**
260      * Resend the confirmation email
261      * @param Request $request
262      * @return \Illuminate\View\View
263      */
264     public function resendConfirmation(Request $request)
265     {
266         $this->validate($request, [
267             'email' => 'required|email|exists:users,email'
268         ]);
269         $user = $this->userRepo->getByEmail($request->get('email'));
270         $this->emailConfirmationService->sendConfirmation($user);
271         session()->flash('success', 'Confirmation email resent, Please check your inbox.');
272         return redirect('/register/confirm');
273     }
274
275     /**
276      * Show the application login form.
277      * @return \Illuminate\Http\Response
278      */
279     public function getLogin()
280     {
281         $socialDrivers = $this->socialAuthService->getActiveDrivers();
282         $authMethod = config('auth.method');
283         return view('auth/login', ['socialDrivers' => $socialDrivers, 'authMethod' => $authMethod]);
284     }
285
286     /**
287      * Redirect to the relevant social site.
288      * @param $socialDriver
289      * @return \Symfony\Component\HttpFoundation\RedirectResponse
290      */
291     public function getSocialLogin($socialDriver)
292     {
293         session()->put('social-callback', 'login');
294         return $this->socialAuthService->startLogIn($socialDriver);
295     }
296
297     /**
298      * Redirect to the social site for authentication intended to register.
299      * @param $socialDriver
300      * @return mixed
301      */
302     public function socialRegister($socialDriver)
303     {
304         $this->checkRegistrationAllowed();
305         session()->put('social-callback', 'register');
306         return $this->socialAuthService->startRegister($socialDriver);
307     }
308
309     /**
310      * The callback for social login services.
311      * @param $socialDriver
312      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
313      * @throws SocialSignInException
314      */
315     public function socialCallback($socialDriver)
316     {
317         if (session()->has('social-callback')) {
318             $action = session()->pull('social-callback');
319             if ($action == 'login') {
320                 return $this->socialAuthService->handleLoginCallback($socialDriver);
321             } elseif ($action == 'register') {
322                 return $this->socialRegisterCallback($socialDriver);
323             }
324         } else {
325             throw new SocialSignInException('No action defined', '/login');
326         }
327         return redirect()->back();
328     }
329
330     /**
331      * Detach a social account from a user.
332      * @param $socialDriver
333      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
334      */
335     public function detachSocialAccount($socialDriver)
336     {
337         return $this->socialAuthService->detachSocialAccount($socialDriver);
338     }
339
340 }