]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/LoginController.php
[Fix] app_footer_links_desc
[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
16 class LoginController extends Controller
17 {
18     /*
19     |--------------------------------------------------------------------------
20     | Login Controller
21     |--------------------------------------------------------------------------
22     |
23     | This controller handles authenticating users for the application and
24     | redirecting them to your home screen. The controller uses a trait
25     | to conveniently provide its functionality to your applications.
26     |
27     */
28
29     use AuthenticatesUsers;
30
31     /**
32      * Redirection paths
33      */
34     protected $redirectTo = '/';
35     protected $redirectPath = '/';
36     protected $redirectAfterLogout = '/login';
37
38     protected $socialAuthService;
39
40     /**
41      * Create a new controller instance.
42      */
43     public function __construct(SocialAuthService $socialAuthService)
44     {
45         $this->middleware('guest', ['only' => ['getLogin', 'login']]);
46         $this->middleware('guard:standard,ldap', ['only' => ['login', 'logout']]);
47
48         $this->socialAuthService = $socialAuthService;
49         $this->redirectPath = url('/');
50         $this->redirectAfterLogout = url('/login');
51     }
52
53     public function username()
54     {
55         return config('auth.method') === 'standard' ? 'email' : 'username';
56     }
57
58     /**
59      * Get the needed authorization credentials from the request.
60      */
61     protected function credentials(Request $request)
62     {
63         return $request->only('username', 'email', 'password');
64     }
65
66     /**
67      * Show the application login form.
68      */
69     public function getLogin(Request $request)
70     {
71         $socialDrivers = $this->socialAuthService->getActiveDrivers();
72         $authMethod = config('auth.method');
73
74         if ($request->has('email')) {
75             session()->flashInput([
76                 'email' => $request->get('email'),
77                 'password' => (config('app.env') === 'demo') ? $request->get('password', '') : ''
78             ]);
79         }
80
81         // Store the previous location for redirect after login
82         $previous = url()->previous('');
83         if ($previous && $previous !== url('/login') && setting('app-public')) {
84             $isPreviousFromInstance = (strpos($previous, url('/')) === 0);
85             if ($isPreviousFromInstance) {
86                 redirect()->setIntendedUrl($previous);
87             }
88         }
89
90         return view('auth.login', [
91           'socialDrivers' => $socialDrivers,
92           'authMethod' => $authMethod,
93         ]);
94     }
95
96     /**
97      * Handle a login request to the application.
98      *
99      * @param  \Illuminate\Http\Request  $request
100      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
101      *
102      * @throws \Illuminate\Validation\ValidationException
103      */
104     public function login(Request $request)
105     {
106         $this->validateLogin($request);
107         $username = $request->get($this->username());
108
109         // If the class is using the ThrottlesLogins trait, we can automatically throttle
110         // the login attempts for this application. We'll key this by the username and
111         // the IP address of the client making these requests into this application.
112         if (method_exists($this, 'hasTooManyLoginAttempts') &&
113             $this->hasTooManyLoginAttempts($request)) {
114             $this->fireLockoutEvent($request);
115
116             Activity::logFailedLogin($username);
117             return $this->sendLockoutResponse($request);
118         }
119
120         try {
121             if ($this->attemptLogin($request)) {
122                 return $this->sendLoginResponse($request);
123             }
124         } catch (LoginAttemptException $exception) {
125             Activity::logFailedLogin($username);
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         return $this->sendFailedLoginResponse($request);
136     }
137
138     /**
139      * The user has been authenticated.
140      *
141      * @param  \Illuminate\Http\Request  $request
142      * @param  mixed  $user
143      * @return mixed
144      */
145     protected function authenticated(Request $request, $user)
146     {
147         // Authenticate on all session guards if a likely admin
148         if ($user->can('users-manage') && $user->can('user-roles-manage')) {
149             $guards = ['standard', 'ldap', 'saml2'];
150             foreach ($guards as $guard) {
151                 auth($guard)->login($user);
152             }
153         }
154
155         Theme::dispatch(ThemeEvents::AUTH_LOGIN, auth()->getDefaultDriver(), $user);
156         $this->logActivity(ActivityType::AUTH_LOGIN, $user);
157         return redirect()->intended($this->redirectPath());
158     }
159
160     /**
161      * Validate the user login request.
162      *
163      * @param  \Illuminate\Http\Request  $request
164      * @return void
165      *
166      * @throws \Illuminate\Validation\ValidationException
167      */
168     protected function validateLogin(Request $request)
169     {
170         $rules = ['password' => 'required|string'];
171         $authMethod = config('auth.method');
172
173         if ($authMethod === 'standard') {
174             $rules['email'] = 'required|email';
175         }
176
177         if ($authMethod === 'ldap') {
178             $rules['username'] = 'required|string';
179             $rules['email'] = 'email';
180         }
181
182         $request->validate($rules);
183     }
184
185     /**
186      * Send a response when a login attempt exception occurs.
187      */
188     protected function sendLoginAttemptExceptionResponse(LoginAttemptException $exception, Request $request)
189     {
190         if ($exception instanceof LoginAttemptEmailNeededException) {
191             $request->flash();
192             session()->flash('request-email', true);
193         }
194
195         if ($message = $exception->getMessage()) {
196             $this->showWarningNotification($message);
197         }
198
199         return redirect('/login');
200     }
201 }