]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/LoginController.php
Cleaned some unused elements during testing
[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         $previous = url()->previous('');
85         if ($previous && $previous !== url('/login') && setting('app-public')) {
86             $isPreviousFromInstance = (strpos($previous, url('/')) === 0);
87             if ($isPreviousFromInstance) {
88                 redirect()->setIntendedUrl($previous);
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      * @return bool
149      */
150     protected function attemptLogin(Request $request)
151     {
152         return $this->loginService->attempt(
153             $this->credentials($request), auth()->getDefaultDriver(), $request->filled('remember')
154         );
155     }
156
157     /**
158      * The user has been authenticated.
159      *
160      * @param \Illuminate\Http\Request $request
161      * @param mixed                    $user
162      *
163      * @return mixed
164      */
165     protected function authenticated(Request $request, $user)
166     {
167         return redirect()->intended($this->redirectPath());
168     }
169
170     /**
171      * Validate the user login request.
172      *
173      * @param \Illuminate\Http\Request $request
174      *
175      * @throws \Illuminate\Validation\ValidationException
176      *
177      * @return void
178      */
179     protected function validateLogin(Request $request)
180     {
181         $rules = ['password' => 'required|string'];
182         $authMethod = config('auth.method');
183
184         if ($authMethod === 'standard') {
185             $rules['email'] = 'required|email';
186         }
187
188         if ($authMethod === 'ldap') {
189             $rules['username'] = 'required|string';
190             $rules['email'] = 'email';
191         }
192
193         $request->validate($rules);
194     }
195
196     /**
197      * Send a response when a login attempt exception occurs.
198      */
199     protected function sendLoginAttemptExceptionResponse(LoginAttemptException $exception, Request $request)
200     {
201         if ($exception instanceof LoginAttemptEmailNeededException) {
202             $request->flash();
203             session()->flash('request-email', true);
204         }
205
206         if ($message = $exception->getMessage()) {
207             $this->showWarningNotification($message);
208         }
209
210         return redirect('/login');
211     }
212
213     /**
214      * Get the failed login response instance.
215      *
216      * @param \Illuminate\Http\Request $request
217      *
218      * @throws \Illuminate\Validation\ValidationException
219      *
220      * @return \Symfony\Component\HttpFoundation\Response
221      */
222     protected function sendFailedLoginResponse(Request $request)
223     {
224         throw ValidationException::withMessages([
225             $this->username() => [trans('auth.failed')],
226         ])->redirectTo('/login');
227     }
228 }