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