]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/LoginController.php
Merge branch 'auth' of git://github.com/benrubson/BookStack into benrubson-auth
[bookstack] / app / Http / Controllers / Auth / LoginController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Auth;
4
5 use Activity;
6 use BookStack\Auth\Access\SocialAuthService;
7 use BookStack\Exceptions\LoginAttemptEmailNeededException;
8 use BookStack\Exceptions\LoginAttemptException;
9 use BookStack\Exceptions\UserRegistrationException;
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         parent::__construct();
50     }
51
52     public function username()
53     {
54         return config('auth.method') === 'standard' ? 'email' : 'username';
55     }
56
57     /**
58      * Get the needed authorization credentials from the request.
59      */
60     protected function credentials(Request $request)
61     {
62         return $request->only('username', 'email', 'password');
63     }
64
65     /**
66      * Show the application login form.
67      */
68     public function getLogin(Request $request)
69     {
70         $socialDrivers = $this->socialAuthService->getActiveDrivers();
71         $authMethod = config('auth.method');
72
73         if ($request->has('email')) {
74             session()->flashInput([
75                 'email' => $request->get('email'),
76                 'password' => (config('app.env') === 'demo') ? $request->get('password', '') : ''
77             ]);
78         }
79
80         $previous = url()->previous('');
81         if (setting('app-public') && $previous && $previous !== url('/login')) {
82             redirect()->setIntendedUrl($previous);
83         }
84
85         return view('auth.login', [
86           'socialDrivers' => $socialDrivers,
87           'authMethod' => $authMethod,
88         ]);
89     }
90
91     /**
92      * Handle a login request to the application.
93      *
94      * @param  \Illuminate\Http\Request  $request
95      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
96      *
97      * @throws \Illuminate\Validation\ValidationException
98      */
99     public function login(Request $request)
100     {
101         $this->validateLogin($request);
102
103         // If the class is using the ThrottlesLogins trait, we can automatically throttle
104         // the login attempts for this application. We'll key this by the username and
105         // the IP address of the client making these requests into this application.
106         if (method_exists($this, 'hasTooManyLoginAttempts') &&
107             $this->hasTooManyLoginAttempts($request)) {
108             $this->fireLockoutEvent($request);
109
110             // Also log some error message
111             Activity::logFailedAccess($request->get($this->username()));
112
113             return $this->sendLockoutResponse($request);
114         }
115
116         try {
117             if ($this->attemptLogin($request)) {
118                 return $this->sendLoginResponse($request);
119             }
120         } catch (LoginAttemptException $exception) {
121             return $this->sendLoginAttemptExceptionResponse($exception, $request);
122         }
123
124         // If the login attempt was unsuccessful we will increment the number of attempts
125         // to login and redirect the user back to the login form. Of course, when this
126         // user surpasses their maximum number of attempts they will get locked out.
127         $this->incrementLoginAttempts($request);
128
129         // Also log some error message
130         Activity::logFailedAccess($request->get($this->username()));
131
132         return $this->sendFailedLoginResponse($request);
133     }
134
135     /**
136      * The user has been authenticated.
137      *
138      * @param  \Illuminate\Http\Request  $request
139      * @param  mixed  $user
140      * @return mixed
141      */
142     protected function authenticated(Request $request, $user)
143     {
144         // Authenticate on all session guards if a likely admin
145         if ($user->can('users-manage') && $user->can('user-roles-manage')) {
146             $guards = ['standard', 'ldap', 'saml2'];
147             foreach ($guards as $guard) {
148                 auth($guard)->login($user);
149             }
150         }
151
152         return redirect()->intended($this->redirectPath());
153     }
154
155     /**
156      * Validate the user login request.
157      *
158      * @param  \Illuminate\Http\Request  $request
159      * @return void
160      *
161      * @throws \Illuminate\Validation\ValidationException
162      */
163     protected function validateLogin(Request $request)
164     {
165         $rules = ['password' => 'required|string'];
166         $authMethod = config('auth.method');
167
168         if ($authMethod === 'standard') {
169             $rules['email'] = 'required|email';
170         }
171
172         if ($authMethod === 'ldap') {
173             $rules['username'] = 'required|string';
174             $rules['email'] = 'email';
175         }
176
177         $request->validate($rules);
178     }
179
180     /**
181      * Send a response when a login attempt exception occurs.
182      */
183     protected function sendLoginAttemptExceptionResponse(LoginAttemptException $exception, Request $request)
184     {
185         if ($exception instanceof LoginAttemptEmailNeededException) {
186             $request->flash();
187             session()->flash('request-email', true);
188         }
189
190         if ($message = $exception->getMessage()) {
191             $this->showWarningNotification($message);
192         }
193
194         return redirect('/login');
195     }
196
197 }