]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/LoginController.php
Log failed accesses
[bookstack] / app / Http / Controllers / Auth / LoginController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Auth;
4
5 use BookStack\Auth\Access\SocialAuthService;
6 use BookStack\Exceptions\LoginAttemptEmailNeededException;
7 use BookStack\Exceptions\LoginAttemptException;
8 use BookStack\Exceptions\UserRegistrationException;
9 use BookStack\Http\Controllers\Controller;
10 use Illuminate\Foundation\Auth\AuthenticatesUsers;
11 use Illuminate\Http\Request;
12
13 class LoginController extends Controller
14 {
15     /*
16     |--------------------------------------------------------------------------
17     | Login Controller
18     |--------------------------------------------------------------------------
19     |
20     | This controller handles authenticating users for the application and
21     | redirecting them to your home screen. The controller uses a trait
22     | to conveniently provide its functionality to your applications.
23     |
24     */
25
26     use AuthenticatesUsers;
27
28     /**
29      * Redirection paths
30      */
31     protected $redirectTo = '/';
32     protected $redirectPath = '/';
33     protected $redirectAfterLogout = '/login';
34
35     protected $socialAuthService;
36
37     /**
38      * Create a new controller instance.
39      */
40     public function __construct(SocialAuthService $socialAuthService)
41     {
42         $this->middleware('guest', ['only' => ['getLogin', 'login']]);
43         $this->middleware('guard:standard,ldap', ['only' => ['login', 'logout']]);
44
45         $this->socialAuthService = $socialAuthService;
46         $this->redirectPath = url('/');
47         $this->redirectAfterLogout = url('/login');
48         parent::__construct();
49     }
50
51     public function username()
52     {
53         return config('auth.method') === 'standard' ? 'email' : 'username';
54     }
55
56     /**
57      * Get the needed authorization credentials from the request.
58      */
59     protected function credentials(Request $request)
60     {
61         return $request->only('username', 'email', 'password');
62     }
63
64     /**
65      * Show the application login form.
66      */
67     public function getLogin(Request $request)
68     {
69         $socialDrivers = $this->socialAuthService->getActiveDrivers();
70         $authMethod = config('auth.method');
71
72         if ($request->has('email')) {
73             session()->flashInput([
74                 'email' => $request->get('email'),
75                 'password' => (config('app.env') === 'demo') ? $request->get('password', '') : ''
76             ]);
77         }
78
79         return view('auth.login', [
80           'socialDrivers' => $socialDrivers,
81           'authMethod' => $authMethod,
82         ]);
83     }
84
85     /**
86      * Handle a login request to the application.
87      *
88      * @param  \Illuminate\Http\Request  $request
89      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
90      *
91      * @throws \Illuminate\Validation\ValidationException
92      */
93     public function login(Request $request)
94     {
95         $this->validateLogin($request);
96
97         // If the class is using the ThrottlesLogins trait, we can automatically throttle
98         // the login attempts for this application. We'll key this by the username and
99         // the IP address of the client making these requests into this application.
100         if (method_exists($this, 'hasTooManyLoginAttempts') &&
101             $this->hasTooManyLoginAttempts($request)) {
102             $this->fireLockoutEvent($request);
103
104             // Also log some error message
105             $this->logFailedAccess($request);
106
107             return $this->sendLockoutResponse($request);
108         }
109
110         try {
111             if ($this->attemptLogin($request)) {
112                 return $this->sendLoginResponse($request);
113             }
114         } catch (LoginAttemptException $exception) {
115             return $this->sendLoginAttemptExceptionResponse($exception, $request);
116         }
117
118         // If the login attempt was unsuccessful we will increment the number of attempts
119         // to login and redirect the user back to the login form. Of course, when this
120         // user surpasses their maximum number of attempts they will get locked out.
121         $this->incrementLoginAttempts($request);
122
123         // Also log some error message
124         $this->logFailedAccess($request);
125
126         return $this->sendFailedLoginResponse($request);
127     }
128
129     /**
130      * Validate the user login request.
131      *
132      * @param  \Illuminate\Http\Request  $request
133      * @return void
134      *
135      * @throws \Illuminate\Validation\ValidationException
136      */
137     protected function validateLogin(Request $request)
138     {
139         $rules = ['password' => 'required|string'];
140         $authMethod = config('auth.method');
141
142         if ($authMethod === 'standard') {
143             $rules['email'] = 'required|email';
144         }
145
146         if ($authMethod === 'ldap') {
147             $rules['username'] = 'required|string';
148             $rules['email'] = 'email';
149         }
150
151         $request->validate($rules);
152     }
153
154     /**
155      * Send a response when a login attempt exception occurs.
156      */
157     protected function sendLoginAttemptExceptionResponse(LoginAttemptException $exception, Request $request)
158     {
159         if ($exception instanceof LoginAttemptEmailNeededException) {
160             $request->flash();
161             session()->flash('request-email', true);
162         }
163
164         if ($message = $exception->getMessage()) {
165             $this->showWarningNotification($message);
166         }
167
168         return redirect('/login');
169     }
170
171     /**
172      * Log failed accesses, matching the default fail2ban nginx/apache auth rules.
173      */
174     protected function logFailedAccess(Request $request)
175     {
176         if (isset($_SERVER['SERVER_SOFTWARE']) && preg_match('/nginx/i', $_SERVER['SERVER_SOFTWARE'])) {
177              error_log('user "' . $request->get($this->username()) . '" was not found in "BookStack"', 4);
178          } else {
179              error_log('user "' . $request->get($this->username()) . '" authentication failure for "BookStack"', 4);
180          }
181     }
182
183 }