]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/LoginController.php
Merge branch 'v21.05.x'
[bookstack] / app / Http / Controllers / Auth / LoginController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Auth;
4
5 use Activity;
6 use BookStack\Actions\ActivityType;
7 use BookStack\Auth\Access\SocialAuthService;
8 use BookStack\Exceptions\LoginAttemptEmailNeededException;
9 use BookStack\Exceptions\LoginAttemptException;
10 use BookStack\Facades\Theme;
11 use BookStack\Http\Controllers\Controller;
12 use BookStack\Theming\ThemeEvents;
13 use Illuminate\Foundation\Auth\AuthenticatesUsers;
14 use Illuminate\Http\Request;
15 use Illuminate\Validation\ValidationException;
16
17 class LoginController extends Controller
18 {
19     /*
20     |--------------------------------------------------------------------------
21     | Login Controller
22     |--------------------------------------------------------------------------
23     |
24     | This controller handles authenticating users for the application and
25     | redirecting them to your home screen. The controller uses a trait
26     | to conveniently provide its functionality to your applications.
27     |
28     */
29
30     use AuthenticatesUsers;
31
32     /**
33      * Redirection paths.
34      */
35     protected $redirectTo = '/';
36     protected $redirectPath = '/';
37     protected $redirectAfterLogout = '/login';
38
39     protected $socialAuthService;
40
41     /**
42      * Create a new controller instance.
43      */
44     public function __construct(SocialAuthService $socialAuthService)
45     {
46         $this->middleware('guest', ['only' => ['getLogin', 'login']]);
47         $this->middleware('guard:standard,ldap', ['only' => ['login', 'logout']]);
48
49         $this->socialAuthService = $socialAuthService;
50         $this->redirectPath = url('/');
51         $this->redirectAfterLogout = url('/login');
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
75         if ($request->has('email')) {
76             session()->flashInput([
77                 'email'    => $request->get('email'),
78                 'password' => (config('app.env') === 'demo') ? $request->get('password', '') : '',
79             ]);
80         }
81
82         // Store the previous location for redirect after login
83         $previous = url()->previous('');
84         if ($previous && $previous !== url('/login') && setting('app-public')) {
85             $isPreviousFromInstance = (strpos($previous, url('/')) === 0);
86             if ($isPreviousFromInstance) {
87                 redirect()->setIntendedUrl($previous);
88             }
89         }
90
91         return view('auth.login', [
92             'socialDrivers' => $socialDrivers,
93             'authMethod'    => $authMethod,
94         ]);
95     }
96
97     /**
98      * Handle a login request to the application.
99      *
100      * @param \Illuminate\Http\Request $request
101      *
102      * @throws \Illuminate\Validation\ValidationException
103      *
104      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
105      */
106     public function login(Request $request)
107     {
108         $this->validateLogin($request);
109         $username = $request->get($this->username());
110
111         // If the class is using the ThrottlesLogins trait, we can automatically throttle
112         // the login attempts for this application. We'll key this by the username and
113         // the IP address of the client making these requests into this application.
114         if (method_exists($this, 'hasTooManyLoginAttempts') &&
115             $this->hasTooManyLoginAttempts($request)) {
116             $this->fireLockoutEvent($request);
117
118             Activity::logFailedLogin($username);
119
120             return $this->sendLockoutResponse($request);
121         }
122
123         try {
124             if ($this->attemptLogin($request)) {
125                 return $this->sendLoginResponse($request);
126             }
127         } catch (LoginAttemptException $exception) {
128             Activity::logFailedLogin($username);
129
130             return $this->sendLoginAttemptExceptionResponse($exception, $request);
131         }
132
133         // If the login attempt was unsuccessful we will increment the number of attempts
134         // to login and redirect the user back to the login form. Of course, when this
135         // user surpasses their maximum number of attempts they will get locked out.
136         $this->incrementLoginAttempts($request);
137
138         Activity::logFailedLogin($username);
139
140         return $this->sendFailedLoginResponse($request);
141     }
142
143     /**
144      * The user has been authenticated.
145      *
146      * @param \Illuminate\Http\Request $request
147      * @param mixed                    $user
148      *
149      * @return mixed
150      */
151     protected function authenticated(Request $request, $user)
152     {
153         // Authenticate on all session guards if a likely admin
154         if ($user->can('users-manage') && $user->can('user-roles-manage')) {
155             $guards = ['standard', 'ldap', 'saml2'];
156             foreach ($guards as $guard) {
157                 auth($guard)->login($user);
158             }
159         }
160
161         Theme::dispatch(ThemeEvents::AUTH_LOGIN, auth()->getDefaultDriver(), $user);
162         $this->logActivity(ActivityType::AUTH_LOGIN, $user);
163
164         return redirect()->intended($this->redirectPath());
165     }
166
167     /**
168      * Validate the user login request.
169      *
170      * @param \Illuminate\Http\Request $request
171      *
172      * @throws \Illuminate\Validation\ValidationException
173      *
174      * @return void
175      */
176     protected function validateLogin(Request $request)
177     {
178         $rules = ['password' => 'required|string'];
179         $authMethod = config('auth.method');
180
181         if ($authMethod === 'standard') {
182             $rules['email'] = 'required|email';
183         }
184
185         if ($authMethod === 'ldap') {
186             $rules['username'] = 'required|string';
187             $rules['email'] = 'email';
188         }
189
190         $request->validate($rules);
191     }
192
193     /**
194      * Send a response when a login attempt exception occurs.
195      */
196     protected function sendLoginAttemptExceptionResponse(LoginAttemptException $exception, Request $request)
197     {
198         if ($exception instanceof LoginAttemptEmailNeededException) {
199             $request->flash();
200             session()->flash('request-email', true);
201         }
202
203         if ($message = $exception->getMessage()) {
204             $this->showWarningNotification($message);
205         }
206
207         return redirect('/login');
208     }
209
210     /**
211      * Get the failed login response instance.
212      *
213      * @param \Illuminate\Http\Request $request
214      *
215      * @throws \Illuminate\Validation\ValidationException
216      *
217      * @return \Symfony\Component\HttpFoundation\Response
218      */
219     protected function sendFailedLoginResponse(Request $request)
220     {
221         throw ValidationException::withMessages([
222             $this->username() => [trans('auth.failed')],
223         ])->redirectTo('/login');
224     }
225 }