Repository navigation
Expand file tree
/
Copy pathEmailVerificationValidationAction.php
More file actions
222 lines (199 loc) · 8 KB
/
Copy pathEmailVerificationValidationAction.php
File metadata and controls
222 lines (199 loc) · 8 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
<?php
declare(strict_types=1);
/*
* UserFrosting Account Sprinkle (http://www.userfrosting.com)
*
* @link https://github.com/userfrosting/sprinkle-account
* @copyright Copyright (c) 2013-2024 Alexander Weissman & Louis Charette
* @license https://github.com/userfrosting/sprinkle-account/blob/master/LICENSE.md (MIT License)
*/
namespace UserFrosting\Sprinkle\Account\Controller;
use Illuminate\Database\Connection;
use Illuminate\Database\Eloquent\Model;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use UserFrosting\Config\Config;
use UserFrosting\Fortress\RequestSchema;
use UserFrosting\Fortress\RequestSchema\RequestSchemaInterface;
use UserFrosting\Fortress\Transformer\RequestDataTransformer;
use UserFrosting\Fortress\Validator\ServerSideValidator;
use UserFrosting\I18n\Translator;
use UserFrosting\Sprinkle\Account\Authenticate\Interfaces\EmailVerificationProvider;
use UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface;
use UserFrosting\Sprinkle\Account\Exceptions\FailedVerificationException;
use UserFrosting\Sprinkle\Account\Exceptions\VerificationDisabledException;
use UserFrosting\Sprinkle\Account\Log\ActivityRecorderInterface;
use UserFrosting\Sprinkle\Account\Log\UserActivityTypes;
use UserFrosting\Sprinkle\Core\Exceptions\ValidationException;
use UserFrosting\Sprinkle\Core\Throttle\Throttler;
use UserFrosting\Sprinkle\Core\Throttle\ThrottlerDelayException;
use UserFrosting\Sprinkle\Core\Util\ApiResponse;
/**
* Handles a request from a guest user to verify an email using a verification
* code sent to the specified email address. This route is publicly accessible.
*
* This action enforces the following checks:
* 1. Ensures the rate limit for this type of request is respected.
* 2. Verifies that the provided email is linked to an existing user account.
* 3. Confirms the user account is not already verified.
* 4. Validates the submitted data against the defined schema.
* 5. Validates the verification code against the Email Verification Provider.
*
* Middleware: GuestGuard + NoCache
* Route: /account/verify/email
* Route Name: account.verify.email
* Request type: POST
*/
class EmailVerificationValidationAction
{
/**
* @var string Request schema to use to validate data.
*/
protected string $schema = 'schema://requests/account-verify.yaml';
/**
* @var string Throttler key slug. This slug is distinct from the one
* used for requesting a verification code, ensuring that the two
* actions do not interfere with each other's throttling limits.
*/
protected string $throttlerSlug = 'account.verify.email';
/**
* Inject dependencies.
*
* @param Translator $translator
* @param \UserFrosting\Event\EventDispatcher $eventDispatcher
* @param EmailVerificationProvider $emailVerification
* @param RequestDataTransformer $transformer
* @param ServerSideValidator $validator
* @param UserInterface $userModel
* @param ActivityRecorderInterface $logger
* @param Connection $db
* @param Throttler $throttler
*/
public function __construct(
protected Translator $translator,
protected EventDispatcherInterface $eventDispatcher,
protected EmailVerificationProvider $emailVerification,
protected RequestDataTransformer $transformer,
protected ServerSideValidator $validator,
protected UserInterface $userModel,
protected ActivityRecorderInterface $logger,
protected Connection $db,
protected Throttler $throttler,
protected Config $config,
) {
}
/**
* Receive the request, dispatch to the handler, and return the payload to
* the response.
*
* @param Request $request
* @param Response $response
*/
public function __invoke(Request $request, Response $response): Response
{
// Make sure verification is enabled
if (!$this->config->getBool('site.registration.require_email_verification', false)) {
throw new VerificationDisabledException();
}
// Handle the request and perform the verification
$this->handle($request);
// Write response
$message = $this->translator->translate('ACCOUNT.VERIFICATION.COMPLETE');
$payload = new ApiResponse($message);
$response->getBody()->write((string) $payload);
return $response->withHeader('Content-Type', 'application/json');
}
/**
* Handle the request and return the payload.
*
* @param Request $request
*/
protected function handle(Request $request): void
{
// Get POST parameters
$params = (array) $request->getParsedBody();
// Load the request schema, apply parameter defaults, whitelist fields,
// and validate the request data. Throttle requests to prevent abuse.
$schema = $this->getSchema();
$data = $this->transformer->transform($schema, $params);
$this->validateData($schema, $data);
$this->throttle($data['email']);
// Basic checks passed. Begin transaction - DB will be rolled back if
// an exception occurs.
$this->db->transaction(function () use ($data) {
// Log throttle-able event
$this->throttler->logEvent($this->throttlerSlug, [
'email' => $data['email'],
]);
// Load the user, by email address
/** @var (UserInterface&Model)|null $user */
$user = $this->userModel->firstWhere('email', $data['email']);
// Verify that the user exists and is not already verified.
// If no user is found with the provided email, or if the user
// exists but is already verified, we act as if the token
// was invalid. This way, we don't leak information about whether
// the email address exists in the system or not, or whether
// the user is already verified. This is a security measure to
// prevent account enumeration attacks.
if ($user === null ||
$user->flag_verified ||
!$this->emailVerification->validate($user, $data['code'])) {
throw new FailedVerificationException();
}
// Verification was successful, update the user account.
$user->flag_verified = true;
$user->save();
// Create activity record
$this->logger->record(
user: $user,
type: UserActivityTypes::VERIFIED,
subject: $user
);
});
}
/**
* Load the request schema.
*
* @return RequestSchemaInterface
*/
protected function getSchema(): RequestSchemaInterface
{
return new RequestSchema($this->schema);
}
/**
* Validate request POST data.
*
* @param RequestSchemaInterface $schema
* @param mixed[] $data
*
* @throws ValidationException If the data is invalid
*/
protected function validateData(RequestSchemaInterface $schema, array $data): void
{
$errors = $this->validator->validate($schema, $data);
if (count($errors) !== 0) {
$e = new ValidationException();
$e->addErrors($errors);
throw $e;
}
}
/**
* Enforce rate limiting for requests to prevent abuse.
*
* @param string $email
*
* @throws ThrottlerDelayException If the throttle limit is reached
*/
protected function throttle(string $email): void
{
$delay = $this->throttler->getDelay($this->throttlerSlug, [
'email' => $email,
]);
if ($delay > 0) {
$e = new ThrottlerDelayException();
$e->setDelay($delay);
throw $e;
}
}
}