-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathUserUtility.php
More file actions
342 lines (304 loc) · 12.6 KB
/
UserUtility.php
File metadata and controls
342 lines (304 loc) · 12.6 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
<?php
declare(strict_types=1);
namespace In2code\Femanager\Utility;
use In2code\Femanager\Domain\Model\User;
use In2code\Femanager\Domain\Model\UserGroup;
use In2code\Femanager\Domain\Repository\UserRepository;
use Psr\Http\Message\RequestInterface;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Context\Exception\AspectNotFoundException;
use TYPO3\CMS\Core\Crypto\PasswordHashing\Argon2iPasswordHash;
use TYPO3\CMS\Core\Crypto\PasswordHashing\BcryptPasswordHash;
use TYPO3\CMS\Core\Crypto\PasswordHashing\BlowfishPasswordHash;
use TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException;
use TYPO3\CMS\Core\Crypto\PasswordHashing\Md5PasswordHash;
use TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory;
use TYPO3\CMS\Core\Crypto\PasswordHashing\Pbkdf2PasswordHash;
use TYPO3\CMS\Core\Crypto\PasswordHashing\PhpassPasswordHash;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Extbase\Persistence\ObjectStorage;
use TYPO3\CMS\Extbase\Reflection\ObjectAccess;
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
/**
* Class UserUtility
* @codeCoverageIgnore
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class UserUtility extends AbstractUtility
{
/**
* Return current logged in fe_user
*/
public static function getCurrentUser(): ?User
{
$context = GeneralUtility::makeInstance(Context::class);
try {
$userId = $context->getPropertyFromAspect('frontend.user', 'id', 0);
if ($userId > 0) {
$userRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(UserRepository::class);
return $userRepository->findByUid($userId);
}
} catch (AspectNotFoundException) {
return null;
}
return null;
}
/**
* Get Usergroups from current logged in user
*
* array(
* 1,
* 5,
* 7
* )
*/
public static function getCurrentUsergroupUids(): array
{
$currentLoggedInUser = self::getCurrentUser();
$usergroupUids = [];
if ($currentLoggedInUser instanceof \In2code\Femanager\Domain\Model\User) {
foreach ($currentLoggedInUser->getUsergroup() as $usergroup) {
$usergroupUids[] = $usergroup->getUid();
}
}
return $usergroupUids;
}
/**
* Autogenerate username and password if it's empty
*
* @return User $user
*/
public static function fallbackUsernameAndPassword(User $user, string $pluginName = 'Pi1'): User
{
$settings = self::getConfigurationManager()->getConfiguration(
ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS,
'Femanager',
$pluginName
);
if (isset($settings['new']['misc']['autogenerate'])) {
$autogenerateSettings = $settings['new']['misc']['autogenerate'];
if ($user->getUsername() === '' || $user->getUsername() === '0') {
$user->setUsername(
StringUtility::getRandomString(
$autogenerateSettings['username']['length'],
$autogenerateSettings['username']['addUpperCase'],
$autogenerateSettings['username']['addSpecialCharacters']
)
);
if ($user->getEmail() !== '' && $user->getEmail() !== '0') {
$user->setUsername($user->getEmail());
}
}
if ($user->getPassword() === '' || $user->getPassword() === '0') {
$password = StringUtility::getRandomString(
$autogenerateSettings['password']['length'],
$autogenerateSettings['password']['addUpperCase'],
$autogenerateSettings['password']['addSpecialCharacters']
);
$user->setPassword($password);
$user->setPasswordAutoGenerated($password);
}
}
return $user;
}
public static function takeEmailAsUsername(User $user, array $settings): User
{
if (ConfigurationUtility::getValue('new/fillEmailWithUsername', $settings) === '1') {
$user->setEmail($user->getUsername());
}
return $user;
}
/**
* Overwrite usergroups from user by flexform settings
*
* @param string $controllerName
* @return User $object
*/
public static function overrideUserGroup(User $user, array $settings, $controllerName = 'new'): User
{
if (!empty($settings[$controllerName]['overrideUserGroup'])) {
$user->removeAllUsergroups();
$usergroupUids = GeneralUtility::trimExplode(',', $settings[$controllerName]['overrideUserGroup'], true);
foreach ($usergroupUids as $usergroupUid) {
/** @var UserGroup $usergroup */
$usergroup = self::getUserGroupRepository()->findByUid((int)$usergroupUid);
$user->addUsergroup($usergroup);
}
}
return $user;
}
/**
* Convert password to Argon2i, Bcrypt, Pbkdf2, Phpass, Blowfish or Md5 hash
*
* @param string $method
* @throws InvalidPasswordHashException
*/
public static function convertPassword(User $user, $method): void
{
if (array_key_exists('password', UserUtility::getDirtyPropertiesFromUser($user))) {
self::hashPassword($user, $method);
}
}
/**
* Hash a password from $user->getPassword()
*
* @param string $method "Argon2i", "Bcrypt", "Pbkdf2", "Phpass", "Blowfish", "md5" or "none" ("sha1" for TYPO3 V8)
* @throws InvalidPasswordHashException
*/
public static function hashPassword(User &$user, $method): void
{
$hashInstance = false;
$saltedHashPassword = $user->getPassword();
/** @var PasswordHashFactory $passwordHashFactory */
$passwordHashFactory = GeneralUtility::makeInstance(PasswordHashFactory::class);
switch ((string)$method) {
case 'Argon2i':
$hashInstance = GeneralUtility::makeInstance(Argon2iPasswordHash::class);
break;
case 'Bcrypt':
$hashInstance = GeneralUtility::makeInstance(BcryptPasswordHash::class);
break;
case 'Pbkdf2':
$hashInstance = GeneralUtility::makeInstance(Pbkdf2PasswordHash::class);
break;
case 'Phpass':
$hashInstance = GeneralUtility::makeInstance(PhpassPasswordHash::class);
break;
case 'Blowfish':
$hashInstance = GeneralUtility::makeInstance(BlowfishPasswordHash::class);
break;
case 'md5':
$hashInstance = GeneralUtility::makeInstance(Md5PasswordHash::class);
break;
case 'none':
break;
default:
$hashInstance = $passwordHashFactory->getDefaultHashInstance('FE');
}
if ($hashInstance === false) {
$user->setPassword($saltedHashPassword);
} else {
$user->setPassword($hashInstance->getHashedPassword($saltedHashPassword));
}
}
/**
* Get changed properties (compare two objects with same getter methods)
*
* @return array
* [firstName][old] = Alex
* [firstName][new] = Alexander
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public static function getDirtyPropertiesFromUser(User $changedObject): array
{
$dirtyProperties = [];
$ignoreProperties = [
'txFemanagerChangerequest',
'ignoreDirty',
'isOnline',
'lastlogin',
];
foreach ($changedObject->_getCleanProperties() as $propertyName => $oldPropertyValue) {
if (method_exists($changedObject, 'get' . ucfirst((string)$propertyName))
&& !in_array($propertyName, $ignoreProperties)
) {
$newPropertyValue = $changedObject->{'get' . ucfirst((string)$propertyName)}();
if (!is_object($oldPropertyValue) || !is_object($newPropertyValue)) {
if ($oldPropertyValue !== $newPropertyValue) {
$dirtyProperties[$propertyName]['old'] = $oldPropertyValue;
$dirtyProperties[$propertyName]['new'] = $newPropertyValue;
}
} elseif ($oldPropertyValue::class === 'DateTime') {
/** @var $oldPropertyValue \DateTime */
/** @var $newPropertyValue \DateTime */
if ($oldPropertyValue->getTimestamp() !== $newPropertyValue->getTimestamp()) {
$dirtyProperties[$propertyName]['old'] = $oldPropertyValue->getTimestamp();
$dirtyProperties[$propertyName]['new'] = $newPropertyValue->getTimestamp();
}
} elseif ($oldPropertyValue::class === ObjectStorage::class) {
$titlesOld = ObjectUtility::implodeObjectStorageOnProperty($oldPropertyValue);
$titlesNew = ObjectUtility::implodeObjectStorageOnProperty($newPropertyValue);
if ($titlesOld !== $titlesNew) {
$dirtyProperties[$propertyName]['old'] = $titlesOld;
$dirtyProperties[$propertyName]['new'] = $titlesNew;
}
} else {
$uidOld = ObjectAccess::getProperty($oldPropertyValue, 'uid');
$uidNew = ObjectAccess::getProperty($newPropertyValue, 'uid');
if ($uidOld !== $uidNew) {
$dirtyProperties[$propertyName]['old'] = $uidOld;
$dirtyProperties[$propertyName]['new'] = $uidNew;
}
}
}
}
return $dirtyProperties;
}
/**
* overwrite user with old values and xml with new values
*
* @param User $user
* @return User $user
*/
public static function rollbackUserWithChangeRequest($user, array $dirtyProperties)
{
$existingProperties = $user->_getCleanProperties();
// reset old values
$user->setUserGroup($existingProperties['usergroup']);
foreach ($dirtyProperties as $propertyName => $propertyValue) {
$propertyValue = null;
$user->{'set' . ucfirst($propertyName)}($existingProperties[$propertyName]);
}
// store changes as xml in field fe_users.tx_femanager_changerequest
$user->setTxFemanagerChangerequest(GeneralUtility::array2xml($dirtyProperties, '', 0, 'changes'));
return $user;
}
/**
* Remove FE Session to a given user
*/
public static function removeFrontendSessionToUser(User $user): void
{
self::getConnectionPool()->getConnectionForTable('fe_sessions')->delete(
'fe_sessions',
['ses_userid' => (int)$user->getUid()]
);
}
/**
* Check if FE Session exists
*/
public static function checkFrontendSessionToUser(User $user): bool
{
$queryBuilder = self::getConnectionPool()->getQueryBuilderForTable('fe_sessions');
$row = $queryBuilder->select('ses_id')
->from('fe_sessions')->where($queryBuilder->expr()->eq('ses_userid', (int)$user->getUid()))->executeQuery()->fetchAssociative();
return !empty($row['ses_id']);
}
/**
* Login FE-User
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @SuppressWarnings(PHPMD.Superglobals)
*/
public static function login(User $user): void
{
/** @var RequestInterface $request */
$request = $GLOBALS['TYPO3_REQUEST'];
/** @var FrontendUserAuthentication $feUser */
$feUser = $request->getAttribute('frontend.user');
$feUser->createUserSession($user->getTempUserArray());
// @todo refactor to possibly get rid of the internal "enforceNewSessionId" call
//
// this call is required for now because at this point in time the FrontendUserAuthentication does not contain
// the Session data of the newly created user.
// "enforceNewSessionId" forces TYPO3 to recreate and update the UserSession with the current user data.
//
// see: https://projekte.in2code.de/issues/72860#note-5 and https://projekte.in2code.de/issues/57055
//
// This should be refactored to not use an TYPO3 @internal function.
$feUser->enforceNewSessionId();
}
}