3 namespace BookStack\Http\Controllers\Auth;
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;
15 class LoginController extends Controller
18 |--------------------------------------------------------------------------
20 |--------------------------------------------------------------------------
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.
27 use AuthenticatesUsers {
28 logout as traitLogout;
34 protected $redirectTo = '/';
35 protected $redirectPath = '/';
37 protected SocialAuthService $socialAuthService;
38 protected LoginService $loginService;
41 * Create a new controller instance.
43 public function __construct(SocialAuthService $socialAuthService, LoginService $loginService)
45 $this->middleware('guest', ['only' => ['getLogin', 'login']]);
46 $this->middleware('guard:standard,ldap', ['only' => ['login']]);
47 $this->middleware('guard:standard,ldap,oidc', ['only' => ['logout']]);
49 $this->socialAuthService = $socialAuthService;
50 $this->loginService = $loginService;
52 $this->redirectPath = url('/');
55 public function username()
57 return config('auth.method') === 'standard' ? 'email' : 'username';
61 * Get the needed authorization credentials from the request.
63 protected function credentials(Request $request)
65 return $request->only('username', 'email', 'password');
69 * Show the application login form.
71 public function getLogin(Request $request)
73 $socialDrivers = $this->socialAuthService->getActiveDrivers();
74 $authMethod = config('auth.method');
75 $preventInitiation = $request->get('prevent_auto_init') === 'true';
77 if ($request->has('email')) {
78 session()->flashInput([
79 'email' => $request->get('email'),
80 'password' => (config('app.env') === 'demo') ? $request->get('password', '') : '',
84 // Store the previous location for redirect after login
85 $this->updateIntendedFromPrevious();
87 if (!$preventInitiation && $this->shouldAutoInitiate()) {
88 return view('auth.login-initiate', [
89 'authMethod' => $authMethod,
93 return view('auth.login', [
94 'socialDrivers' => $socialDrivers,
95 'authMethod' => $authMethod,
100 * Handle a login request to the application.
102 * @param \Illuminate\Http\Request $request
104 * @throws \Illuminate\Validation\ValidationException
106 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
108 public function login(Request $request)
110 $this->validateLogin($request);
111 $username = $request->get($this->username());
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.
117 method_exists($this, 'hasTooManyLoginAttempts') &&
118 $this->hasTooManyLoginAttempts($request)
120 $this->fireLockoutEvent($request);
122 Activity::logFailedLogin($username);
124 return $this->sendLockoutResponse($request);
128 if ($this->attemptLogin($request)) {
129 return $this->sendLoginResponse($request);
131 } catch (LoginAttemptException $exception) {
132 Activity::logFailedLogin($username);
134 return $this->sendLoginAttemptExceptionResponse($exception, $request);
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);
142 Activity::logFailedLogin($username);
144 return $this->sendFailedLoginResponse($request);
148 * Attempt to log the user into the application.
150 * @param \Illuminate\Http\Request $request
154 protected function attemptLogin(Request $request)
156 return $this->loginService->attempt(
157 $this->credentials($request),
158 auth()->getDefaultDriver(),
159 $request->filled('remember')
164 * The user has been authenticated.
166 * @param \Illuminate\Http\Request $request
171 protected function authenticated(Request $request, $user)
173 return redirect()->intended($this->redirectPath());
177 * Validate the user login request.
179 * @param \Illuminate\Http\Request $request
181 * @throws \Illuminate\Validation\ValidationException
185 protected function validateLogin(Request $request)
187 $rules = ['password' => ['required', 'string']];
188 $authMethod = config('auth.method');
190 if ($authMethod === 'standard') {
191 $rules['email'] = ['required', 'email'];
194 if ($authMethod === 'ldap') {
195 $rules['username'] = ['required', 'string'];
196 $rules['email'] = ['email'];
199 $request->validate($rules);
203 * Send a response when a login attempt exception occurs.
205 protected function sendLoginAttemptExceptionResponse(LoginAttemptException $exception, Request $request)
207 if ($exception instanceof LoginAttemptEmailNeededException) {
209 session()->flash('request-email', true);
212 if ($message = $exception->getMessage()) {
213 $this->showWarningNotification($message);
216 return redirect('/login');
220 * Get the failed login response instance.
222 * @param \Illuminate\Http\Request $request
224 * @throws \Illuminate\Validation\ValidationException
226 * @return \Symfony\Component\HttpFoundation\Response
228 protected function sendFailedLoginResponse(Request $request)
230 throw ValidationException::withMessages([
231 $this->username() => [trans('auth.failed')],
232 ])->redirectTo('/login');
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.
240 protected function updateIntendedFromPrevious(): void
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) {
249 $ignorePrefixList = [
254 foreach ($ignorePrefixList as $ignorePrefix) {
255 if (strpos($previous, url($ignorePrefix)) === 0) {
260 redirect()->setIntendedUrl($previous);
264 * Check if login auto-initiate should be valid based upon authentication config.
266 protected function shouldAutoInitiate(): bool
268 $socialDrivers = $this->socialAuthService->getActiveDrivers();
269 $authMethod = config('auth.method');
270 $autoRedirect = config('auth.auto_initiate');
272 return $autoRedirect && count($socialDrivers) === 0 && in_array($authMethod, ['oidc', 'saml2']);
276 * Logout user and perform subsequent redirect.
278 * @param \Illuminate\Http\Request $request
282 public function logout(Request $request)
284 $this->traitLogout($request);
286 $redirectUri = $this->shouldAutoInitiate() ? '/login?prevent_auto_init=true' : '/';
288 return redirect($redirectUri);