]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/LoginController.php
1d6a36c5bbb072097414224caaa717c162bc451c
[bookstack] / app / Http / Controllers / Auth / LoginController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Auth;
4
5 use BookStack\Auth\Access\LoginService;
6 use BookStack\Auth\Access\SocialAuthService;
7 use BookStack\Exceptions\LoginAttemptEmailNeededException;
8 use BookStack\Exceptions\LoginAttemptException;
9 use BookStack\Facades\Activity;
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     use AuthenticatesUsers {
28         logout as traitLogout;
29     }
30
31     /**
32      * Redirection paths.
33      */
34     protected $redirectTo = '/';
35     protected $redirectPath = '/';
36
37     protected SocialAuthService $socialAuthService;
38     protected LoginService $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']]);
47         $this->middleware('guard:standard,ldap,oidc', ['only' => ['logout']]);
48
49         $this->socialAuthService = $socialAuthService;
50         $this->loginService = $loginService;
51
52         $this->redirectPath = url('/');
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         $preventInitiation = $request->get('prevent_auto_init') === 'true';
76
77         if ($request->has('email')) {
78             session()->flashInput([
79                 'email'    => $request->get('email'),
80                 'password' => (config('app.env') === 'demo') ? $request->get('password', '') : '',
81             ]);
82         }
83
84         // Store the previous location for redirect after login
85         $this->updateIntendedFromPrevious();
86
87         if (!$preventInitiation && $this->shouldAutoInitiate()) {
88             return view('auth.login-initiate', [
89                 'authMethod'    => $authMethod,
90             ]);
91         }
92
93         return view('auth.login', [
94             'socialDrivers' => $socialDrivers,
95             'authMethod'    => $authMethod,
96         ]);
97     }
98
99     /**
100      * Handle a login request to the application.
101      *
102      * @param \Illuminate\Http\Request $request
103      *
104      * @throws \Illuminate\Validation\ValidationException
105      *
106      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
107      */
108     public function login(Request $request)
109     {
110         $this->validateLogin($request);
111         $username = $request->get($this->username());
112
113         // If the class is using the ThrottlesLogins trait, we can automatically throttle
114         // the login attempts for this application. We'll key this by the username and
115         // the IP address of the client making these requests into this application.
116         if (
117             method_exists($this, 'hasTooManyLoginAttempts') &&
118             $this->hasTooManyLoginAttempts($request)
119         ) {
120             $this->fireLockoutEvent($request);
121
122             Activity::logFailedLogin($username);
123
124             return $this->sendLockoutResponse($request);
125         }
126
127         try {
128             if ($this->attemptLogin($request)) {
129                 return $this->sendLoginResponse($request);
130             }
131         } catch (LoginAttemptException $exception) {
132             Activity::logFailedLogin($username);
133
134             return $this->sendLoginAttemptExceptionResponse($exception, $request);
135         }
136
137         // If the login attempt was unsuccessful we will increment the number of attempts
138         // to login and redirect the user back to the login form. Of course, when this
139         // user surpasses their maximum number of attempts they will get locked out.
140         $this->incrementLoginAttempts($request);
141
142         Activity::logFailedLogin($username);
143
144         return $this->sendFailedLoginResponse($request);
145     }
146
147     /**
148      * Attempt to log the user into the application.
149      *
150      * @param \Illuminate\Http\Request $request
151      *
152      * @return bool
153      */
154     protected function attemptLogin(Request $request)
155     {
156         return $this->loginService->attempt(
157             $this->credentials($request),
158             auth()->getDefaultDriver(),
159             $request->filled('remember')
160         );
161     }
162
163     /**
164      * The user has been authenticated.
165      *
166      * @param \Illuminate\Http\Request $request
167      * @param mixed                    $user
168      *
169      * @return mixed
170      */
171     protected function authenticated(Request $request, $user)
172     {
173         return redirect()->intended($this->redirectPath());
174     }
175
176     /**
177      * Validate the user login request.
178      *
179      * @param \Illuminate\Http\Request $request
180      *
181      * @throws \Illuminate\Validation\ValidationException
182      *
183      * @return void
184      */
185     protected function validateLogin(Request $request)
186     {
187         $rules = ['password' => ['required', 'string']];
188         $authMethod = config('auth.method');
189
190         if ($authMethod === 'standard') {
191             $rules['email'] = ['required', 'email'];
192         }
193
194         if ($authMethod === 'ldap') {
195             $rules['username'] = ['required', 'string'];
196             $rules['email'] = ['email'];
197         }
198
199         $request->validate($rules);
200     }
201
202     /**
203      * Send a response when a login attempt exception occurs.
204      */
205     protected function sendLoginAttemptExceptionResponse(LoginAttemptException $exception, Request $request)
206     {
207         if ($exception instanceof LoginAttemptEmailNeededException) {
208             $request->flash();
209             session()->flash('request-email', true);
210         }
211
212         if ($message = $exception->getMessage()) {
213             $this->showWarningNotification($message);
214         }
215
216         return redirect('/login');
217     }
218
219     /**
220      * Get the failed login response instance.
221      *
222      * @param \Illuminate\Http\Request $request
223      *
224      * @throws \Illuminate\Validation\ValidationException
225      *
226      * @return \Symfony\Component\HttpFoundation\Response
227      */
228     protected function sendFailedLoginResponse(Request $request)
229     {
230         throw ValidationException::withMessages([
231             $this->username() => [trans('auth.failed')],
232         ])->redirectTo('/login');
233     }
234
235     /**
236      * Update the intended URL location from their previous URL.
237      * Ignores if not from the current app instance or if from certain
238      * login or authentication routes.
239      */
240     protected function updateIntendedFromPrevious(): void
241     {
242         // Store the previous location for redirect after login
243         $previous = url()->previous('');
244         $isPreviousFromInstance = (strpos($previous, url('/')) === 0);
245         if (!$previous || !setting('app-public') || !$isPreviousFromInstance) {
246             return;
247         }
248
249         $ignorePrefixList = [
250             '/login',
251             '/mfa',
252         ];
253
254         foreach ($ignorePrefixList as $ignorePrefix) {
255             if (strpos($previous, url($ignorePrefix)) === 0) {
256                 return;
257             }
258         }
259
260         redirect()->setIntendedUrl($previous);
261     }
262
263     /**
264      * Check if login auto-initiate should be valid based upon authentication config.
265      */
266     protected function shouldAutoInitiate(): bool
267     {
268         $socialDrivers = $this->socialAuthService->getActiveDrivers();
269         $authMethod = config('auth.method');
270         $autoRedirect = config('auth.auto_initiate');
271
272         return $autoRedirect && count($socialDrivers) === 0 && in_array($authMethod, ['oidc', 'saml2']);
273     }
274
275     /**
276      * Logout user and perform subsequent redirect.
277      *
278      * @param \Illuminate\Http\Request $request
279      *
280      * @return mixed
281      */
282     public function logout(Request $request)
283     {
284         $this->traitLogout($request);
285
286         $redirectUri = $this->shouldAutoInitiate() ? '/login?prevent_auto_init=true' : '/';
287
288         return redirect($redirectUri);
289     }
290 }