]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/LoginController.php
Updated the login redirect logic to ignore mfa routes
[bookstack] / app / Http / Controllers / Auth / LoginController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Auth;
4
5 use Activity;
6 use BookStack\Auth\Access\LoginService;
7 use BookStack\Auth\Access\SocialAuthService;
8 use BookStack\Exceptions\LoginAttemptEmailNeededException;
9 use BookStack\Exceptions\LoginAttemptException;
10 use BookStack\Http\Controllers\Controller;
11 use Illuminate\Foundation\Auth\AuthenticatesUsers;
12 use Illuminate\Http\Request;
13 use Illuminate\Validation\ValidationException;
14
15 class LoginController extends Controller
16 {
17     /*
18     |--------------------------------------------------------------------------
19     | Login Controller
20     |--------------------------------------------------------------------------
21     |
22     | This controller handles authenticating users for the application and
23     | redirecting them to your home screen. The controller uses a trait
24     | to conveniently provide its functionality to your applications.
25     |
26     */
27
28     use AuthenticatesUsers;
29
30     /**
31      * Redirection paths.
32      */
33     protected $redirectTo = '/';
34     protected $redirectPath = '/';
35     protected $redirectAfterLogout = '/login';
36
37     protected $socialAuthService;
38     protected $loginService;
39
40     /**
41      * Create a new controller instance.
42      */
43     public function __construct(SocialAuthService $socialAuthService, LoginService $loginService)
44     {
45         $this->middleware('guest', ['only' => ['getLogin', 'login']]);
46         $this->middleware('guard:standard,ldap', ['only' => ['login', 'logout']]);
47
48         $this->socialAuthService = $socialAuthService;
49         $this->loginService = $loginService;
50
51         $this->redirectPath = url('/');
52         $this->redirectAfterLogout = url('/login');
53     }
54
55     public function username()
56     {
57         return config('auth.method') === 'standard' ? 'email' : 'username';
58     }
59
60     /**
61      * Get the needed authorization credentials from the request.
62      */
63     protected function credentials(Request $request)
64     {
65         return $request->only('username', 'email', 'password');
66     }
67
68     /**
69      * Show the application login form.
70      */
71     public function getLogin(Request $request)
72     {
73         $socialDrivers = $this->socialAuthService->getActiveDrivers();
74         $authMethod = config('auth.method');
75
76         if ($request->has('email')) {
77             session()->flashInput([
78                 'email'    => $request->get('email'),
79                 'password' => (config('app.env') === 'demo') ? $request->get('password', '') : '',
80             ]);
81         }
82
83         // Store the previous location for redirect after login
84         $this->updateIntendedFromPrevious();
85
86         return view('auth.login', [
87             'socialDrivers' => $socialDrivers,
88             'authMethod'    => $authMethod,
89         ]);
90     }
91
92     /**
93      * Handle a login request to the application.
94      *
95      * @param \Illuminate\Http\Request $request
96      *
97      * @throws \Illuminate\Validation\ValidationException
98      *
99      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
100      */
101     public function login(Request $request)
102     {
103         $this->validateLogin($request);
104         $username = $request->get($this->username());
105
106         // If the class is using the ThrottlesLogins trait, we can automatically throttle
107         // the login attempts for this application. We'll key this by the username and
108         // the IP address of the client making these requests into this application.
109         if (method_exists($this, 'hasTooManyLoginAttempts') &&
110             $this->hasTooManyLoginAttempts($request)) {
111             $this->fireLockoutEvent($request);
112
113             Activity::logFailedLogin($username);
114
115             return $this->sendLockoutResponse($request);
116         }
117
118         try {
119             if ($this->attemptLogin($request)) {
120                 return $this->sendLoginResponse($request);
121             }
122         } catch (LoginAttemptException $exception) {
123             Activity::logFailedLogin($username);
124
125             return $this->sendLoginAttemptExceptionResponse($exception, $request);
126         }
127
128         // If the login attempt was unsuccessful we will increment the number of attempts
129         // to login and redirect the user back to the login form. Of course, when this
130         // user surpasses their maximum number of attempts they will get locked out.
131         $this->incrementLoginAttempts($request);
132
133         Activity::logFailedLogin($username);
134
135         return $this->sendFailedLoginResponse($request);
136     }
137
138     /**
139      * Attempt to log the user into the application.
140      *
141      * @param \Illuminate\Http\Request $request
142      *
143      * @return bool
144      */
145     protected function attemptLogin(Request $request)
146     {
147         return $this->loginService->attempt(
148             $this->credentials($request),
149             auth()->getDefaultDriver(),
150             $request->filled('remember')
151         );
152     }
153
154     /**
155      * The user has been authenticated.
156      *
157      * @param \Illuminate\Http\Request $request
158      * @param mixed                    $user
159      *
160      * @return mixed
161      */
162     protected function authenticated(Request $request, $user)
163     {
164         return redirect()->intended($this->redirectPath());
165     }
166
167     /**
168      * Validate the user login request.
169      *
170      * @param \Illuminate\Http\Request $request
171      *
172      * @throws \Illuminate\Validation\ValidationException
173      *
174      * @return void
175      */
176     protected function validateLogin(Request $request)
177     {
178         $rules = ['password' => 'required|string'];
179         $authMethod = config('auth.method');
180
181         if ($authMethod === 'standard') {
182             $rules['email'] = 'required|email';
183         }
184
185         if ($authMethod === 'ldap') {
186             $rules['username'] = 'required|string';
187             $rules['email'] = 'email';
188         }
189
190         $request->validate($rules);
191     }
192
193     /**
194      * Send a response when a login attempt exception occurs.
195      */
196     protected function sendLoginAttemptExceptionResponse(LoginAttemptException $exception, Request $request)
197     {
198         if ($exception instanceof LoginAttemptEmailNeededException) {
199             $request->flash();
200             session()->flash('request-email', true);
201         }
202
203         if ($message = $exception->getMessage()) {
204             $this->showWarningNotification($message);
205         }
206
207         return redirect('/login');
208     }
209
210     /**
211      * Get the failed login response instance.
212      *
213      * @param \Illuminate\Http\Request $request
214      *
215      * @throws \Illuminate\Validation\ValidationException
216      *
217      * @return \Symfony\Component\HttpFoundation\Response
218      */
219     protected function sendFailedLoginResponse(Request $request)
220     {
221         throw ValidationException::withMessages([
222             $this->username() => [trans('auth.failed')],
223         ])->redirectTo('/login');
224     }
225
226     /**
227      * Update the intended URL location from their previous URL.
228      * Ignores if not from the current app instance or if from certain
229      * login or authentication routes.
230      */
231     protected function updateIntendedFromPrevious(): void
232     {
233         // Store the previous location for redirect after login
234         $previous = url()->previous('');
235         $isPreviousFromInstance = (strpos($previous, url('/')) === 0);
236         if (!$previous || !setting('app-public') || !$isPreviousFromInstance) {
237             return;
238         }
239
240         $ignorePrefixList = [
241             '/login',
242             '/mfa',
243         ];
244
245         foreach ($ignorePrefixList as $ignorePrefix) {
246             if (strpos($previous, url($ignorePrefix)) === 0) {
247                 return;
248             }
249         }
250
251         redirect()->setIntendedUrl($previous);
252     }
253 }