forked from in2code-de/femanager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNewController.php
More file actions
524 lines (478 loc) · 19.3 KB
/
NewController.php
File metadata and controls
524 lines (478 loc) · 19.3 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
<?php
declare(strict_types=1);
namespace In2code\Femanager\Controller;
use In2code\Femanager\Domain\Model\Log;
use In2code\Femanager\Domain\Model\User;
use In2code\Femanager\Domain\Service\AutoAdminConfirmationService;
use In2code\Femanager\Domain\Validator\CaptchaValidator;
use In2code\Femanager\Domain\Validator\PasswordValidator;
use In2code\Femanager\Domain\Validator\ServersideValidator;
use In2code\Femanager\Event\BeforeUserConfirmEvent;
use In2code\Femanager\Event\BeforeUserCreateEvent;
use In2code\Femanager\Event\CreateConfirmationRequestEvent;
use In2code\Femanager\Event\UserWasConfirmedByAdminEvent;
use In2code\Femanager\Utility\ConfigurationUtility;
use In2code\Femanager\Utility\FrontendUtility;
use In2code\Femanager\Utility\HashUtility;
use In2code\Femanager\Utility\LocalizationUtility;
use In2code\Femanager\Utility\StringUtility;
use In2code\Femanager\Utility\UserUtility;
use JsonException;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException;
use TYPO3\CMS\Core\Http\PropagateResponseException;
use TYPO3\CMS\Core\Http\ServerRequestFactory;
use TYPO3\CMS\Core\Type\ContextualFeedbackSeverity;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Annotation\Validate;
use TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException;
use TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException;
/**
* Class NewController
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class NewController extends AbstractFrontendController
{
/**
* Render registration form
*
* @throws JsonException
*/
public function newAction(): ResponseInterface
{
$this->view->assignMultiple(
[
'allUserGroups' => $this->allUserGroups,
]
);
$this->assignForAll();
return $this->htmlResponse();
}
/**
* action create
*
* @throws IllegalObjectTypeException
* @throws InvalidPasswordHashException
*/
#[Validate(['validator' => ServersideValidator::class, 'param' => 'user'])]
#[Validate(['validator' => PasswordValidator::class, 'param' => 'user'])]
#[Validate(['validator' => CaptchaValidator::class, 'param' => 'captcha'])]
public function createAction(User $user, string $captcha = null): ResponseInterface
{
if ($this->ratelimiterService->isLimited()) {
$this->addFlashMessage(
LocalizationUtility::translate('ratelimiter_too_many_attempts'),
'',
ContextualFeedbackSeverity::ERROR
);
throw new PropagateResponseException($this->redirect('createStatus'));
}
$user = UserUtility::overrideUserGroup($user, $this->settings);
$configuration = ConfigurationUtility::getValue('new./forceValues./beforeAnyConfirmation.', $this->config);
$user = FrontendUtility::forceValues($user, $configuration);
$user = UserUtility::fallbackUsernameAndPassword($user);
$user = UserUtility::takeEmailAsUsername($user, $this->settings);
UserUtility::hashPassword($user, ConfigurationUtility::getValue('new/misc/passwordSave', $this->settings));
$this->eventDispatcher->dispatch(new BeforeUserCreateEvent($user));
$this->ratelimiterService->consumeSlot();
if ($this->isAllConfirmed()) {
$response = $this->createAllConfirmed($user);
} else {
$response = $this->createRequest($user);
}
if ($response !== null) {
return $response;
}
return $this->redirect('createStatus');
}
/**
* Dispatcher action for every confirmation request
*
* @param int $user User UID (user could be hidden)
* @param string $hash Given hash
* @param string $status
* "userConfirmation", "userConfirmationRefused", "adminConfirmation",
* "adminConfirmationRefused", "adminConfirmationRefusedSilent"
* @throws IllegalObjectTypeException
* @throws UnknownObjectException
*/
/**
* @return ResponseInterface|void
* @throws IllegalObjectTypeException
* @throws UnknownObjectException
*
* @SuppressWarnings(PHPMD.ExitExpression)
*/
public function confirmCreateRequestAction(int $user, string $hash, string $status = 'adminConfirmation', ?string $adminHash = null)
{
$backend = false;
$user = $this->userRepository->findByUid($user);
$this->eventDispatcher->dispatch(new BeforeUserConfirmEvent($user, $hash, $status));
if ($user === null) {
$this->addFlashMessage(
LocalizationUtility::translate('missingUserInDatabase'),
'',
ContextualFeedbackSeverity::ERROR
);
throw new PropagateResponseException($this->redirect('new'));
}
$request = ServerRequestFactory::fromGlobals();
// check if the the request was triggered via Backend
if ($request->hasHeader('Accept')) {
$accept = $request->getHeader('Accept')[0];
if (str_contains((string)$accept, 'application/json')) {
$backend = true;
}
}
if ($status === 'userConfirmation' && ConfigurationUtility::getValue(
'new./email./createUserConfirmation./confirmUserConfirmation',
$this->config
) == '1') {
$this->view->assignMultiple(
[
'user' => $user,
'status' => 'confirmUser',
'hash' => $hash,
]
);
$this->assignForAll();
return $this->htmlResponse();
}
if ($status === 'adminConfirmation' && ConfigurationUtility::getValue(
'new./email./createUserConfirmation./confirmAdminConfirmation',
$this->config
) == '1') {
if (!HashUtility::validHash($adminHash, $user, 'admin')) {
$this->addFlashMessage(
LocalizationUtility::translate('error_not_authorized'),
'',
ContextualFeedbackSeverity::ERROR
);
throw new PropagateResponseException($this->redirect('new'), 1743766811);
}
$this->view->assignMultiple(
[
'user' => $user,
'status' => 'confirmAdmin',
'hash' => $hash,
]
);
$this->assignForAll();
return $this->htmlResponse();
}
if (($status === 'adminConfirmationRefused' || $status === 'adminConfirmationRefusedSilent') &&
ConfigurationUtility::getValue(
'new./email./createUserConfirmation./confirmAdminConfirmation',
$this->config
) == '1') {
if (!HashUtility::validHash($adminHash, $user, 'admin')) {
$this->addFlashMessage(
LocalizationUtility::translate('error_not_authorized'),
'',
ContextualFeedbackSeverity::ERROR
);
throw new PropagateResponseException($this->redirect('new'), 1743766811);
}
$this->view->assignMultiple(
[
'user' => $user,
'status' => 'confirmAdminRefused',
'silent' => $status === 'adminConfirmationRefusedSilent',
'hash' => $hash,
]
);
$this->assignForAll();
return $this->htmlResponse();
}
$furtherFunctions = match ($status) {
'userConfirmation', 'confirmUser' => $this->statusUserConfirmation($user, $hash, $status),
'userConfirmationRefused', 'confirmDeletion' => $this->statusUserConfirmationRefused($user, $hash),
'adminConfirmation', 'confirmAdmin' => $this->statusAdminConfirmation($user, $hash, $status, $backend),
'adminConfirmationRefused', 'adminConfirmationRefusedSilent', 'confirmAdminDeletion', 'confirmAdminRefused', 'confirmAdminRefusedSilent' =>
$this->statusAdminConfirmationRefused($user, $hash, $status),
default => false,
};
if ($backend) {
$this->persistenceManager->persistAll();
$event = new UserWasConfirmedByAdminEvent($request, $user);
$this->eventDispatcher->dispatch($event);
/**
* this request was triggered via Backend Module "Frontend users",
* so we stop here and provide a feedback to the BE
*/
echo json_encode(['status' => 'okay']) . PHP_EOL;
die();
}
if ($furtherFunctions) {
return $this->redirectByAction('new', $status . 'Redirect');
}
return $this->redirect('new');
}
/**
* Status action: User confirmation
*
* @return bool allow further functions
* @throws IllegalObjectTypeException
* @throws UnknownObjectException
*/
protected function statusUserConfirmation(User $user, string $hash, string $status): bool
{
if (HashUtility::validHash($hash, $user)) {
if ($user->getTxFemanagerConfirmedbyuser()) {
$this->addFlashMessage(
LocalizationUtility::translate('userAlreadyConfirmed'),
'',
ContextualFeedbackSeverity::ERROR
);
throw new PropagateResponseException($this->redirect('new'));
}
$user = FrontendUtility::forceValues(
$user,
ConfigurationUtility::getValue('new./forceValues./onUserConfirmation.', $this->config)
);
$user->setTxFemanagerConfirmedbyuser(true);
$this->userRepository->update($user);
$this->persistenceManager->persistAll();
$this->logUtility->log(Log::STATUS_REGISTRATIONCONFIRMEDUSER, $user);
if ($this->isAdminConfirmationMissing($user)) {
$this->createAdminConfirmationRequest($user);
} else {
$user->setDisable(false);
$this->logUtility->log(Log::STATUS_NEWREGISTRATION, $user);
$this->finalCreate($user, 'new', 'createStatus', true, $status);
}
} else {
$this->addFlashMessage(
LocalizationUtility::translate('createFailedProfile'),
'',
ContextualFeedbackSeverity::ERROR
);
return false;
}
return true;
}
/**
* Status action: User confirmation refused
*
* @return bool allow further functions
* @throws IllegalObjectTypeException
*/
protected function statusUserConfirmationRefused(User $user, string $hash): bool
{
if (HashUtility::validHash($hash, $user)) {
$this->logUtility->log(Log::STATUS_REGISTRATIONREFUSEDUSER, $user);
$this->addFlashMessage(LocalizationUtility::translate('createProfileDeleted'));
$this->userRepository->remove($user);
} else {
$this->addFlashMessage(
LocalizationUtility::translate('createFailedProfile'),
'',
ContextualFeedbackSeverity::ERROR
);
return false;
}
return true;
}
/**
* Status action: Admin confirmation
*
* @param $hash
* @param $status
* @return bool allow further functions
* @throws IllegalObjectTypeException
* @throws UnknownObjectException
*
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
*/
protected function statusAdminConfirmation(User $user, $hash, $status, bool $backend = false): bool
{
if (HashUtility::validHash($hash, $user)) {
if ($user->getTxFemanagerConfirmedbyadmin()) {
$this->addFlashMessage(
LocalizationUtility::translate('userAlreadyConfirmed'),
'',
ContextualFeedbackSeverity::ERROR
);
throw new PropagateResponseException($this->redirect('new'));
}
$user = FrontendUtility::forceValues(
$user,
ConfigurationUtility::getValue('new./forceValues./onAdminConfirmation.', $this->config)
);
$user->setTxFemanagerConfirmedbyadmin(true);
$user->setDisable(false);
$this->userRepository->update($user);
$this->logUtility->log(Log::STATUS_REGISTRATIONCONFIRMEDADMIN, $user);
$this->finalCreate($user, 'new', 'createStatus', false, $status, $backend);
} else {
$this->addFlashMessage(
LocalizationUtility::translate('createFailedProfile'),
'',
ContextualFeedbackSeverity::ERROR
);
return false;
}
return true;
}
/**
* Status action: Admin refused profile creation (normal or silent)
*
* @param $hash
* @param $status
* @return bool allow further functions
* @throws IllegalObjectTypeException
*/
protected function statusAdminConfirmationRefused(User $user, $hash, $status): bool
{
if (HashUtility::validHash($hash, $user)) {
$this->logUtility->log(Log::STATUS_REGISTRATIONREFUSEDADMIN, $user);
$this->addFlashMessage(LocalizationUtility::translate('createProfileDeleted'));
if ($status !== 'adminConfirmationRefusedSilent' && $status !== 'confirmAdminRefusedSilent') {
$this->sendMailService->send(
'CreateUserNotifyRefused',
StringUtility::makeEmailArray(
$user->getEmail(),
$user->getFirstName() . ' ' . $user->getLastName()
),
['sender@femanager.org' => 'Sender Name'],
'Your profile was refused',
['user' => $user],
ConfigurationUtility::getValue('new./email./createUserNotifyRefused.', $this->config),
$this->request
);
}
$this->userRepository->remove($user);
} else {
$this->addFlashMessage(
LocalizationUtility::translate('createFailedProfile'),
'',
ContextualFeedbackSeverity::ERROR
);
return false;
}
return true;
}
/**
* Just for showing information after user creation
*/
public function createStatusAction(): ResponseInterface
{
$this->assignForAll();
return $this->htmlResponse();
}
/**
* Postfix method to createAction(): Create must be confirmed by Admin or User
*
* @throws IllegalObjectTypeException
*/
protected function createRequest(User $user): ResponseInterface|null
{
$user->setDisable(true);
$this->userRepository->add($user);
$this->persistenceManager->persistAll();
$this->logUtility->log(Log::STATUS_PROFILECREATIONREQUEST, $user);
if (!empty($this->settings['new']['confirmByUser'])) {
$this->createUserConfirmationRequest($user);
return $this->redirectByAction('new', 'requestRedirect');
}
if (!empty($this->settings['new']['confirmByAdmin'])) {
$this->createAdminConfirmationRequest($user);
return $this->redirectByAction('new', 'requestRedirect');
}
return null;
}
/**
* Send email to user for confirmation
*/
protected function createUserConfirmationRequest(User $user)
{
$this->sendCreateUserConfirmationMail($user);
$this->addFlashMessage(LocalizationUtility::translate('createRequestWaitingForUserConfirm'));
return $this->redirectByAction('new', 'requestRedirect');
}
/**
* Send email to admin for confirmation
*/
protected function createAdminConfirmationRequest(User $user)
{
$aacService = GeneralUtility::makeInstance(
AutoAdminConfirmationService::class,
$user,
$this->settings,
$this->contentObject
);
if ($aacService->isAutoAdminConfirmationFullfilled()) {
$user->setDisable(false);
$this->eventDispatcher->dispatch(
new CreateConfirmationRequestEvent($user, CreateConfirmationRequestEvent::MODE_AUTOMATIC)
);
$this->createAllConfirmed($user);
} else {
$this->eventDispatcher->dispatch(
new CreateConfirmationRequestEvent($user, CreateConfirmationRequestEvent::MODE_MANUAL)
);
$this->sendMailService->send(
'createAdminConfirmation',
StringUtility::makeEmailArray(
$this->settings['new']['confirmByAdmin'] ?? '',
$this->settings['new']['email']['createAdminConfirmation']['receiver']['name']['value'] ?? ''
),
['sender@femanager.org' => 'Sender Name'],
'New Registration request',
[
'user' => $user,
'hash' => HashUtility::createHashForUser($user),
'adminHash' => HashUtility::createHashForUser($user, 'admin'),
],
ConfigurationUtility::getValue('new./email./createAdminConfirmation.', $this->config),
$this->request
);
$this->addFlashMessage(LocalizationUtility::translate('createRequestWaitingForAdminConfirm'));
}
}
protected function isAllConfirmed(): bool
{
return empty($this->settings['new']['confirmByUser']) && empty($this->settings['new']['confirmByAdmin']);
}
protected function isAdminConfirmationMissing(User $user): bool
{
return !empty($this->settings['new']['confirmByAdmin']) && !$user->getTxFemanagerConfirmedbyadmin();
}
/**
* Just for showing empty dialogue to resend confirmation mail
*/
public function resendConfirmationDialogueAction(): ResponseInterface
{
return $this->htmlResponse();
}
/**
* re-sends a confirmation email if given mail is valid
*/
public function resendConfirmationMailAction(): ResponseInterface
{
// @todo find a better way to fetch the data
$result = GeneralUtility::_GP('tx_femanager_registration');
if (is_array($result)) {
$mail = $result['user']['email'] ?? '';
if ($mail && GeneralUtility::validEmail($mail)) {
$user = $this->userRepository->findFirstByEmail($mail);
if (is_a($user, User::class)) {
$this->sendCreateUserConfirmationMail($user);
$this->addFlashMessage(
LocalizationUtility::translate('resendConfirmationMailSend'),
'',
ContextualFeedbackSeverity::INFO
);
return $this->redirect('resendConfirmationDialogue');
}
}
}
$this->addFlashMessage(
LocalizationUtility::translate('resendConfirmationMailFail'),
LocalizationUtility::translate('validationError'),
ContextualFeedbackSeverity::ERROR
);
return $this->redirect('resendConfirmationDialogue');
}
}