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