-
Notifications
You must be signed in to change notification settings - Fork 290
Expand file tree
/
Copy pathLoginComponent.php
More file actions
311 lines (277 loc) · 10.9 KB
/
LoginComponent.php
File metadata and controls
311 lines (277 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
<?php
declare(strict_types=1);
/**
* Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2010 - 2026, Cake Development Corporation (https://www.cakedc.com)
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace CakeDC\Users\Controller\Component;
use Authentication\Authenticator\ResultInterface;
use Cake\Controller\Component;
use Cake\Core\Configure;
use Cake\Datasource\EntityInterface;
use Cake\Http\ServerRequest;
use Cake\Log\Log;
use CakeDC\Auth\Authentication\AuthenticationService;
use CakeDC\Auth\Traits\IsAuthorizedTrait;
use CakeDC\Users\UsersPlugin;
use CakeDC\Users\Utility\UsersUrl;
use Laminas\Diactoros\Uri;
/**
* LoginFailure component
*/
class LoginComponent extends Component
{
use IsAuthorizedTrait;
/**
* @inheritDoc
*/
protected array $_defaultConfig = [
'defaultMessage' => null,
'messages' => [],
'targetAuthenticator' => null,
];
/**
* Gets the request instance.
*
* @return \Cake\Http\ServerRequest
*/
public function getRequest(): ServerRequest
{
return $this->getController()->getRequest();
}
/**
* Handle login, if success redirect to 'AuthenticationComponent.loginRedirect' or show error
*
* @param bool $errorOnlyPost should handle failure only on post request
* @param bool $redirectFailure should redirect on failure?
* @return \Cake\Http\Response|null
*/
public function handleLogin($errorOnlyPost, $redirectFailure)
{
$request = $this->getController()->getRequest();
$service = $request->getAttribute('authentication');
if (!$service) {
throw new \UnexpectedValueException('Authentication service not found in this request');
}
$eventBefore = $this->getController()->dispatchEvent(UsersPlugin::EVENT_BEFORE_LOGIN, []);
if (is_array($eventBefore->getResult())) {
return $this->getController()->redirect($eventBefore->getResult());
}
$result = $service->getResult();
if ($result->isValid()) {
$user = $request->getAttribute('identity')->getOriginalData();
$this->handlePasswordRehash($service, $user, $request);
$this->updateLastLogin($user);
$this->addFlashMessage($user);
return $this->afterIdentifyUser($user);
}
if ($request->is('post') || $errorOnlyPost === false) {
$this->getController()->dispatchEvent(UsersPlugin::EVENT_AFTER_LOGIN_FAILURE, ['result' => $result]);
return $this->handleFailure($redirectFailure);
}
return null;
}
/**
* Handle login failure
*
* @param bool $redirect should redirect?
* @return \Cake\Http\Response|null
*/
public function handleFailure($redirect = true)
{
$controller = $this->getController();
$request = $controller->getRequest();
$service = $request->getAttribute('authentication');
$result = $this->getTargetAuthenticatorResult($service);
$controller->Flash->error($this->getErrorMessage($result), ['element' => 'default', 'key' => 'auth']);
if (!$redirect) {
return null;
}
return $controller->redirect(UsersUrl::actionUrl('login'));
}
/**
* Get the target authenticator result for current login action
*
* @param \CakeDC\Auth\Authentication\AuthenticationService $service authentication service.
* @return \Authentication\Authenticator\ResultInterface|null
*/
public function getTargetAuthenticatorResult(AuthenticationService $service)
{
$target = $this->getConfig('targetAuthenticator');
$failures = $service->getFailures();
foreach ($failures as $failure) {
if ($failure->getAuthenticator() instanceof $target) {
return $failure->getResult();
}
}
return null;
}
/**
* Get the error message for result status
*
* @param \Authentication\Authenticator\ResultInterface|null $result Result object;
* @return string
*/
public function getErrorMessage(?ResultInterface $result = null)
{
$messagesMap = $this->getConfig('messages');
if ($result === null || !isset($messagesMap[$result->getStatus()])) {
return $this->getConfig('defaultMessage');
}
return $messagesMap[$result->getStatus()];
}
/**
* Determine redirect url after user identified
*
* @param array $user user data after identified
* @return \Cake\Http\Response|null
*/
protected function afterIdentifyUser($user)
{
$event = $this->getController()->dispatchEvent(UsersPlugin::EVENT_AFTER_LOGIN, ['user' => $user]);
if (is_array($event->getResult())) {
// in this case we don't checkSafeHost the url as the url params are generated by an event
return $this->getController()->redirect($event->getResult());
}
$queryRedirect = $this->getController()->getRequest()->getQuery('redirect');
$redirectUrl = $this->getController()->Authentication->getConfig('loginRedirect');
if (!$this->checkSafeHost($queryRedirect)) {
$userId = $user['id'] ?? null;
Log::info(
"Unsafe redirect `$queryRedirect` ignored, user id `{$userId}` " .
"redirected to `$redirectUrl` after successful login",
);
$queryRedirect = $redirectUrl;
}
// even if the host is safe, we need to check if the url is authorized for the given user
// this check ignores the host
if ($this->isAuthorized($queryRedirect ?? null)) {
$redirectUrl = $queryRedirect;
}
return $this->getController()->redirect($redirectUrl);
}
/**
* Handle password rehash logic
*
* @param \CakeDC\Auth\Authentication\AuthenticationService $service Authentication service
* @param \CakeDC\Users\Model\Entity\User $user User entity.
* @param \Cake\Http\ServerRequest $request The http request.
* @return void
*/
protected function handlePasswordRehash($service, $user, \Cake\Http\ServerRequest $request)
{
// deprecated way to define identifiers
$identifiersNames = (array)Configure::read('Auth.PasswordRehash.identifiers');
foreach ($identifiersNames as $identifierName) {
if (!$service->identifiers()->has($identifierName)) {
Log::warning("Error saving user id $user->id password after rehashing: identifier $identifierName not found. Check your Auth.PasswordRehash.identifiers configuration.");
continue;
}
/**
* @var \Authentication\Identifier\AbstractIdentifier|null $checker
*/
$checker = $service->identifiers()->get($identifierName);
$this->saveRehashedPassword($checker, $request, $user);
}
// new way to define identifiers, inside the authenticators
$authenticatorNames = (array)Configure::read('Auth.PasswordRehash.authenticators');
foreach ($authenticatorNames as $authenticatorName => $identifierName) {
if (!$service->authenticators()->has($authenticatorName)) {
Log::warning("Error saving user id $user->id password after rehashing: authenticator $authenticatorName not found. Check your Auth.PasswordRehash.authenticators configuration.");
continue;
}
/**
* @var \Authentication\Identifier\IdentifierCollection $identifierCollection
*/
$identifierCollection = $service->authenticators()->get($authenticatorName)->getIdentifier();
if (!$identifierCollection->has($identifierName)) {
Log::warning("Error saving user id $user->id password after rehashing: identifier $identifierName not found. Check your Auth.PasswordRehash.authenticators configuration.");
continue;
}
/**
* @var \Authentication\Identifier\AbstractIdentifier|null $checker
*/
$checker = $identifierCollection->get($identifierName);
$this->saveRehashedPassword($checker, $request, $user);
}
}
/**
* @param mixed $checker
* @param \Cake\Http\ServerRequest $request
* @param \Cake\Datasource\EntityInterface $user
* @return void
*/
protected function saveRehashedPassword($checker, ServerRequest $request, EntityInterface $user): void
{
if (!$checker || method_exists($checker, 'needsPasswordRehash') && !$checker->needsPasswordRehash()) {
return;
}
$passwordField = $checker->getConfig('fields.password', 'password');
$password = $request->getData($passwordField);
$user->set($passwordField, $password);
$user->setDirty('modified');
$userId = $user->get('id');
if (!method_exists($this->getController(), 'getUsersTable')) {
Log::warning("Error saving user id $userId password after rehashing: getUsersTable method not found");
return;
}
if (!$this->getController()->getUsersTable()->save($user)) {
Log::warning("Error saving user id $userId password after rehashing: " . implode(', ', $user->getErrors()));
}
}
/**
* Check if there is a host defined in the $queryRedirect and it's in the allowed list of hosts
*
* @param string|null $queryRedirect redirect url
* @return bool
*/
protected function checkSafeHost(?string $queryRedirect = null): bool
{
if ($queryRedirect === null) {
return true;
}
$uri = new Uri($queryRedirect);
$host = $uri->getHost();
if (!$host) {
return true;
}
return in_array($host, Configure::read('Users.AllowedRedirectHosts'));
}
/**
* Update last loging date
*
* @param \CakeDC\Users\Model\Entity\User $user User entity.
* @return void
*/
protected function updateLastLogin($user)
{
if (!Configure::read('Users.Login.updateLastLogin', true)) {
return;
}
$field = Configure::read('Users.Login.lastLoginField', 'last_login');
$now = \Cake\I18n\DateTime::now();
$user->set($field, $now);
$this->getController()->getUsersTable()->updateAll(
[$field => $now->format('Y-m-d H:i:s')],
['id' => $user->id],
);
}
/**
* Add a flash message informing user is logged in
*
* @param array $user user data
* @return void
*/
protected function addFlashMessage($user)
{
if (!Configure::read('Users.Login.flashMessage')) {
return;
}
$this->getController()->Flash->success(__d('cake_d_c/users', 'Welcome, {0}', $user['username']));
}
}