Repository navigation
Expand file tree
/
Copy pathCreate.php
More file actions
338 lines (291 loc) · 12.3 KB
/
Copy pathCreate.php
File metadata and controls
338 lines (291 loc) · 12.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
<?php
declare(strict_types=1);
namespace BigGive\Identity\Application\Actions\Person;
use Assert\Assertion;
use BigGive\Identity\Application\Actions\Action;
use BigGive\Identity\Application\Actions\ActionError;
use BigGive\Identity\Application\Auth\TokenService;
use BigGive\Identity\Application\Middleware\FriendlyCaptchaVerifier;
use BigGive\Identity\Application\Settings\SettingsInterface;
use BigGive\Identity\Client\Mailer;
use BigGive\Identity\Client\Stripe;
use BigGive\Identity\Domain\DomainException\DuplicateEmailAddressWithPasswordException;
use BigGive\Identity\Domain\EmailVerificationToken;
use BigGive\Identity\Domain\Person;
use BigGive\Identity\Repository\EmailVerificationTokenRepository;
use BigGive\Identity\Repository\PersonRepository;
use Laminas\Diactoros\Response\TextResponse;
use OpenApi\Attributes as OA;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Slim\Exception\HttpBadRequestException;
use Slim\Exception\HttpUnauthorizedException;
use Stripe\Exception\ApiErrorException;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use TypeError;
/**
* @see Person
*/
#[OA\Post(
path: '/v1/people',
summary: 'Create a new Person record, initially with no password. ' .
'If they want to login again they will need to set a password later.',
operationId: 'person_create',
requestBody: new OA\RequestBody(
description: 'All details needed to register a Person, including valid captcha_code or secretNumber ' .
'(email verification code)',
required: true,
content: new OA\JsonContent(ref: '#/components/schemas/Person'),
),
responses: [
new OA\Response(
response: 200,
description: 'Registered',
content: new OA\JsonContent(ref: '#/components/schemas/Person'),
),
new OA\Response(
response: 400,
description: 'Invalid or missing data',
content: new OA\JsonContent(format: 'object', example: ['error' => ['description' => 'The error details']]),
),
new OA\Response(response: 401, description: 'Captcha verification failed'),
],
)]
class Create extends Action
{
public function __construct(
LoggerInterface $logger,
private readonly PersonRepository $personRepository,
private readonly FriendlyCaptchaVerifier $friendlyCaptchaVerifier,
private readonly SerializerInterface $serializer,
private readonly SettingsInterface $settings,
private readonly Stripe $stripeClient,
private readonly ValidatorInterface $validator,
private readonly EmailVerificationTokenRepository $emailVerificationTokenRepository,
private readonly \DateTimeImmutable $now,
private Mailer $mailerClient,
private readonly TokenService $tokenService,
) {
parent::__construct($logger);
}
/**
* Require that one of the 2 tokens is provided, except in Staging load tests where in the absence of an email
* token, Friendly Captcha may be bypassed.
*/
private function checkEmailTokenOrCaptchaValid(
bool $hasPassword,
?string $email_address,
Person $person,
string $tokenSecretSupplied,
Request $request,
string $rawPassword,
bool $permitCaptchaBypass,
): void {
if ($hasPassword) {
Assertion::allNotEmpty([$email_address, $person->last_name]);
if (!$person->is_organisation) {
Assertion::notEmpty($person->first_name);
}
\assert($email_address !== null); // Psalm can't understand previous line.
$this->assertValidEmailVerificationTokenSupplied(
email_address: $email_address,
tokenSecretSupplied: $tokenSecretSupplied,
request: $request
);
$person->email_address_verified = $this->now;
$person->raw_password = $rawPassword;
// Ensure that e.g. the password meets minimum standards.
$violations = $this->validator->validate($person, null, [Person::VALIDATION_COMPLETE]);
if (count($violations) > 0) {
$message = "";
foreach ($violations as $violation) {
// only message we're currently expecting to see is from the NotCompromisedPassword validator as
// using our copy given in Person::validatePasswordIfNotBlank
$message .= $violation->getMessage();
$message .= " ";
}
throw new HttpBadRequestException(
$request,
$message,
);
}
} elseif ($permitCaptchaBypass) {
return;
} else {
// as we didn't require them to supply an email verification token here we must verify a captcha code
// instead.
if ($person->captcha_code === null) {
$this->logger->log(LogLevel::WARNING, 'Security: Person Create captcha code not sent');
throw new HttpUnauthorizedException($request, 'Unauthorised');
}
if (!$this->friendlyCaptchaVerifier->verify($person->captcha_code)) {
throw new HttpBadRequestException($request, 'CAPTCHA verification error');
}
Assertion::null($person->raw_password);
}
}
public function assertValidEmailVerificationTokenSupplied(
string $email_address,
string $tokenSecretSupplied,
Request $request
): void {
$oldestAllowedTokenCreationDate = EmailVerificationToken::oldestCreationDateForSettingPassword($this->now);
$token = $this->emailVerificationTokenRepository->findToken(
email_address: $email_address,
tokenSecret: $tokenSecretSupplied,
createdSince: $oldestAllowedTokenCreationDate
);
if ($token === null) {
throw new HttpBadRequestException($request, 'Email verification token error');
}
}
/**
* @param Request $request
* @return array{person: Person, error: null}|array{error: Response, person: null}
*/
public function deserializePerson(Request $request, SerializerInterface $serializer): array
{
$body = ((string)$request->getBody());
try {
$person = $serializer->deserialize(
$body,
Person::class,
'json'
);
} catch (UnexpectedValueException | TypeError $exception) {
// UnexpectedValueException is the Serializer one, not the global one
$this->logger->info(sprintf('%s non-serialisable payload was: %s', __CLASS__, $body));
$message = 'Person Create data deserialise error';
$exceptionType = get_class($exception);
$validationError = $this->validationError(
"$message: $exceptionType - {$exception->getMessage()}",
$message,
empty($body), // Suspected bot / junk traffic sometimes sends blank payload.
);
return ['error' => $validationError, 'person' => null];
}
return ['person' => $person, 'error' => null];
}
/**
* @param array $args
* @return Response
* @throws HttpBadRequestException
*/
protected function action(Request $request, array $args): Response
{
try {
$requestBody = json_decode(
(string)$request->getBody(),
true,
512,
JSON_THROW_ON_ERROR
);
\assert(is_array($requestBody));
} catch (\JsonException $exception) {
return $this->validationError(
'Person Create data deserialise error',
);
}
['person' => $person, 'error' => $validationError] = $this->deserializePerson($request, $this->serializer);
$person->trimNames();
$tokenSecretSupplied = (string)($requestBody["secretNumber"] ?? null);
if ($validationError) {
return $validationError;
}
\assert($person !== null);
$email_address = $person->email_address;
$rawPassword = (string) ($requestBody['raw_password'] ?? null);
$hasPassword = $rawPassword !== '';
$bypassFriendlyCaptcha = $this->settings->get('friendly_captcha')['bypass'];
if ($bypassFriendlyCaptcha) {
$person->skipCaptchaPresenceValidation();
}
$violations = $this->validator->validate($person, null, [Person::VALIDATION_NEW]);
if (count($violations) > 0) {
$message = 'Validation error: ';
$violationDetails = [];
foreach ($violations as $violation) {
$violationDetails[] = $this->summariseConstraintViolation($violation);
}
$message .= implode('; ', $violationDetails);
return $this->validationError(
$message,
null,
true,
);
}
$this->checkEmailTokenOrCaptchaValid(
hasPassword: $hasPassword,
email_address: $email_address,
person: $person,
tokenSecretSupplied: $tokenSecretSupplied,
request: $request,
rawPassword: $rawPassword,
permitCaptchaBypass: $bypassFriendlyCaptcha,
);
try {
// We can't send the person record to matchbot just yet, as we need to give them a stripe ID first.
// But we have to persist the person before obtaining a stripe ID because persistance is where we generate
// their UUID that we need to pass to stripe. So persist, set stripe customer ID, then persist again to
// send to MB.
$this->personRepository->persist($person, true);
} catch (DuplicateEmailAddressWithPasswordException $duplicateException) {
$this->logger->warning(sprintf(
'%s failed to persist Person: %s',
__CLASS__,
$duplicateException->getMessage(),
));
return $this->validationError(
logMessage: "Update not valid: {$duplicateException->getMessage()}",
publicMessage: 'Your password could not be set. There is already a password set for ' .
'your email address.',
errorType: ActionError::DUPLICATE_EMAIL_ADDRESS_WITH_PASSWORD,
);
}
try {
$customer = $this->stripeClient->customers->create($person->getStripeCustomerParams());
} catch (ApiErrorException $exception) {
$logMessage = sprintf('%s Stripe API error: %s', __CLASS__, $exception->getMessage());
$this->logger->error($logMessage);
return $this->validationError($logMessage, 'Stripe Customer create API error');
}
$person->setStripeCustomerId($customer->id);
$this->personRepository->persist($person, false);
// I think $complete will now always be true, but not 100% sure.
// Could add logging to check but I don't think it's essential now.
$complete = $tokenSecretSupplied !== '';
$token = $this->tokenService->create(
new \DateTimeImmutable(),
(string)$person->getId(),
$complete,
$person->stripe_customer_id
);
$person->addCompletionJWT($token);
if ($hasPassword) {
$this->sendRegisteredEmail($person);
}
return new TextResponse(
$this->serializer->serialize(
$person,
'json',
[
AbstractNormalizer::IGNORED_ATTRIBUTES => Person::NON_SERIALISED_ATTRIBUTES,
JsonEncode::OPTIONS => JSON_FORCE_OBJECT,
],
),
200,
['content-type' => 'application/json']
);
}
private function sendRegisteredEmail(Person $person): void
{
$this->mailerClient->sendEmail($person->toMailerPayload());
}
}