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