]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/LoginController.php
Fixed misalignment of page and chapter parent book
[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\Http\Controllers\Controller;
11 use Illuminate\Foundation\Auth\AuthenticatesUsers;
12 use Illuminate\Http\Request;
13
14 class LoginController extends Controller
15 {
16     /*
17     |--------------------------------------------------------------------------
18     | Login Controller
19     |--------------------------------------------------------------------------
20     |
21     | This controller handles authenticating users for the application and
22     | redirecting them to your home screen. The controller uses a trait
23     | to conveniently provide its functionality to your applications.
24     |
25     */
26
27     use AuthenticatesUsers;
28
29     /**
30      * Redirection paths
31      */
32     protected $redirectTo = '/';
33     protected $redirectPath = '/';
34     protected $redirectAfterLogout = '/login';
35
36     protected $socialAuthService;
37
38     /**
39      * Create a new controller instance.
40      */
41     public function __construct(SocialAuthService $socialAuthService)
42     {
43         $this->middleware('guest', ['only' => ['getLogin', 'login']]);
44         $this->middleware('guard:standard,ldap', ['only' => ['login', 'logout']]);
45
46         $this->socialAuthService = $socialAuthService;
47         $this->redirectPath = url('/');
48         $this->redirectAfterLogout = url('/login');
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         // Store the previous location for redirect after login
80         $previous = url()->previous('');
81         if ($previous && $previous !== url('/login') && setting('app-public')) {
82             $isPreviousFromInstance = (strpos($previous, url('/')) === 0);
83             if ($isPreviousFromInstance) {
84                 redirect()->setIntendedUrl($previous);
85             }
86         }
87
88         return view('auth.login', [
89           'socialDrivers' => $socialDrivers,
90           'authMethod' => $authMethod,
91         ]);
92     }
93
94     /**
95      * Handle a login request to the application.
96      *
97      * @param  \Illuminate\Http\Request  $request
98      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
99      *
100      * @throws \Illuminate\Validation\ValidationException
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             return $this->sendLockoutResponse($request);
116         }
117
118         try {
119             if ($this->attemptLogin($request)) {
120                 return $this->sendLoginResponse($request);
121             }
122         } catch (LoginAttemptException $exception) {
123             Activity::logFailedLogin($username);
124             return $this->sendLoginAttemptExceptionResponse($exception, $request);
125         }
126
127         // If the login attempt was unsuccessful we will increment the number of attempts
128         // to login and redirect the user back to the login form. Of course, when this
129         // user surpasses their maximum number of attempts they will get locked out.
130         $this->incrementLoginAttempts($request);
131
132         Activity::logFailedLogin($username);
133         return $this->sendFailedLoginResponse($request);
134     }
135
136     /**
137      * The user has been authenticated.
138      *
139      * @param  \Illuminate\Http\Request  $request
140      * @param  mixed  $user
141      * @return mixed
142      */
143     protected function authenticated(Request $request, $user)
144     {
145         // Authenticate on all session guards if a likely admin
146         if ($user->can('users-manage') && $user->can('user-roles-manage')) {
147             $guards = ['standard', 'ldap', 'saml2'];
148             foreach ($guards as $guard) {
149                 auth($guard)->login($user);
150             }
151         }
152
153         $this->logActivity(ActivityType::AUTH_LOGIN, $user);
154         return redirect()->intended($this->redirectPath());
155     }
156
157     /**
158      * Validate the user login request.
159      *
160      * @param  \Illuminate\Http\Request  $request
161      * @return void
162      *
163      * @throws \Illuminate\Validation\ValidationException
164      */
165     protected function validateLogin(Request $request)
166     {
167         $rules = ['password' => 'required|string'];
168         $authMethod = config('auth.method');
169
170         if ($authMethod === 'standard') {
171             $rules['email'] = 'required|email';
172         }
173
174         if ($authMethod === 'ldap') {
175             $rules['username'] = 'required|string';
176             $rules['email'] = 'email';
177         }
178
179         $request->validate($rules);
180     }
181
182     /**
183      * Send a response when a login attempt exception occurs.
184      */
185     protected function sendLoginAttemptExceptionResponse(LoginAttemptException $exception, Request $request)
186     {
187         if ($exception instanceof LoginAttemptEmailNeededException) {
188             $request->flash();
189             session()->flash('request-email', true);
190         }
191
192         if ($message = $exception->getMessage()) {
193             $this->showWarningNotification($message);
194         }
195
196         return redirect('/login');
197     }
198
199 }