-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCreate.php
More file actions
270 lines (232 loc) · 9.62 KB
/
Create.php
File metadata and controls
270 lines (232 loc) · 9.62 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
<?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\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 Slim\Exception\HttpBadRequestException;
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\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',
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 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);
}
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);
$tokenSecretSupplied = (string)($requestBody["secretNumber"] ?? null);
if ($validationError) {
return $validationError;
}
\assert($person !== null);
$email_address = $person->email_address;
$rawPassword = (string) ($requestBody['raw_password'] ?? null);
if ($rawPassword !== '') {
$hasPassword = true;
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;
} else {
$hasPassword = false;
Assertion::null($person->raw_password);
}
if ($this->settings->get('friendly_captcha')['bypass']) {
$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,
);
}
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);
$token = $this->tokenService->create(
new \DateTimeImmutable(),
(string)$person->getId(),
false,
$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());
}
}