]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/LoginController.php
16f7fc010adeedfe754269d93492209894d85706
[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      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
102      *
103      * @throws \Illuminate\Validation\ValidationException
104      */
105     public function login(Request $request)
106     {
107         $this->validateLogin($request);
108         $username = $request->get($this->username());
109
110         // If the class is using the ThrottlesLogins trait, we can automatically throttle
111         // the login attempts for this application. We'll key this by the username and
112         // the IP address of the client making these requests into this application.
113         if (method_exists($this, 'hasTooManyLoginAttempts') &&
114             $this->hasTooManyLoginAttempts($request)) {
115             $this->fireLockoutEvent($request);
116
117             Activity::logFailedLogin($username);
118             return $this->sendLockoutResponse($request);
119         }
120
121         try {
122             if ($this->attemptLogin($request)) {
123                 return $this->sendLoginResponse($request);
124             }
125         } catch (LoginAttemptException $exception) {
126             Activity::logFailedLogin($username);
127             return $this->sendLoginAttemptExceptionResponse($exception, $request);
128         }
129
130         // If the login attempt was unsuccessful we will increment the number of attempts
131         // to login and redirect the user back to the login form. Of course, when this
132         // user surpasses their maximum number of attempts they will get locked out.
133         $this->incrementLoginAttempts($request);
134
135         Activity::logFailedLogin($username);
136         return $this->sendFailedLoginResponse($request);
137     }
138
139     /**
140      * The user has been authenticated.
141      *
142      * @param  \Illuminate\Http\Request  $request
143      * @param  mixed  $user
144      * @return mixed
145      */
146     protected function authenticated(Request $request, $user)
147     {
148         // Authenticate on all session guards if a likely admin
149         if ($user->can('users-manage') && $user->can('user-roles-manage')) {
150             $guards = ['standard', 'ldap', 'saml2'];
151             foreach ($guards as $guard) {
152                 auth($guard)->login($user);
153             }
154         }
155
156         Theme::dispatch(ThemeEvents::AUTH_LOGIN, auth()->getDefaultDriver(), $user);
157         $this->logActivity(ActivityType::AUTH_LOGIN, $user);
158         return redirect()->intended($this->redirectPath());
159     }
160
161     /**
162      * Validate the user login request.
163      *
164      * @param  \Illuminate\Http\Request  $request
165      * @return void
166      *
167      * @throws \Illuminate\Validation\ValidationException
168      */
169     protected function validateLogin(Request $request)
170     {
171         $rules = ['password' => 'required|string'];
172         $authMethod = config('auth.method');
173
174         if ($authMethod === 'standard') {
175             $rules['email'] = 'required|email';
176         }
177
178         if ($authMethod === 'ldap') {
179             $rules['username'] = 'required|string';
180             $rules['email'] = 'email';
181         }
182
183         $request->validate($rules);
184     }
185
186     /**
187      * Send a response when a login attempt exception occurs.
188      */
189     protected function sendLoginAttemptExceptionResponse(LoginAttemptException $exception, Request $request)
190     {
191         if ($exception instanceof LoginAttemptEmailNeededException) {
192             $request->flash();
193             session()->flash('request-email', true);
194         }
195
196         if ($message = $exception->getMessage()) {
197             $this->showWarningNotification($message);
198         }
199
200         return redirect('/login');
201     }
202
203     /**
204      * Get the failed login response instance.
205      *
206      * @param  \Illuminate\Http\Request  $request
207      * @return \Symfony\Component\HttpFoundation\Response
208      *
209      * @throws \Illuminate\Validation\ValidationException
210      */
211     protected function sendFailedLoginResponse(Request $request)
212     {
213         throw ValidationException::withMessages([
214             $this->username() => [trans('auth.failed')],
215         ])->redirectTo('/login');
216     }
217 }