-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBasePresenter.php
More file actions
518 lines (459 loc) · 18.1 KB
/
BasePresenter.php
File metadata and controls
518 lines (459 loc) · 18.1 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
<?php
namespace App\V1Module\Presenters;
use App\Helpers\MetaFormats\MetaFormatHelper;
use App\Helpers\MetaFormats\Validators\VArray;
use App\Helpers\MetaFormats\Validators\VObject;
use App\Helpers\Pagination;
use App\Model\Entity\User;
use App\Security\AccessToken;
use App\Security\Identity;
use App\Exceptions\BadRequestException;
use App\Exceptions\ForbiddenRequestException;
use App\Exceptions\WrongHttpMethodException;
use App\Exceptions\NotImplementedException;
use App\Exceptions\InternalServerException;
use App\Exceptions\FrontendErrorMappings;
use App\Security\AccessManager;
use App\Security\Authorizator;
use App\Model\Repository\Users;
use App\Helpers\UserActions;
use App\Helpers\Validators;
use App\Helpers\FileStorage\IImmutableFile;
use App\Helpers\MetaFormats\FormatCache;
use App\Helpers\MetaFormats\MetaFormat;
use App\Helpers\MetaFormats\RequestParamData;
use App\Helpers\MetaFormats\Type;
use App\Responses\StorageFileResponse;
use App\Responses\ZipFilesResponse;
use Nette\Application\Application;
use Nette\Http\FileUpload;
use Nette\Http\IResponse;
use Tracy\ILogger;
use ReflectionClass;
use ReflectionMethod;
use ReflectionException;
class BasePresenter extends \App\Presenters\BasePresenter
{
/**
* @var Users
* @inject
*/
public $users;
/**
* @var UserActions
* @inject
*/
public $userActions;
/**
* @var AccessManager
* @inject
*/
public $accessManager;
/**
* @var Application
* @inject
*/
public $application;
/**
* @var Authorizator
* @inject
*/
public $authorizator;
/**
* @var ILogger
* @inject
*/
public $logger;
/** @var MetaFormat Instance of the meta format used by the endpoint (null if no format used) */
private MetaFormat $requestFormatInstance;
protected function formatPermissionCheckMethod($action)
{
return "check" . $action;
}
/**
* Verify IP lock of given user.
* @param User $user to be tested
*/
protected function verifyUserIpLock(User $user)
{
if ($user->isIpLocked()) {
// the user is bound to access ReCodEx from one IP only, at the moment
$remoteAddr = $this->getHttpRequest()->getRemoteAddress();
if (!$remoteAddr || !$user->verifyIpLock($remoteAddr)) {
throw new ForbiddenRequestException(
"Forbidden Request - User is not allowed access from IP '$remoteAddr'.",
IResponse::S403_Forbidden,
FrontendErrorMappings::E403_003__USER_IP_LOCKED,
[
'remoteAddress' => $remoteAddr,
'lockedAddress' => $user->getIpLockRaw(),
'expires' => $user->getIpLockExpiration(),
]
);
}
}
}
public function startup()
{
parent::startup();
$this->application->errorPresenter = "V1:ApiError";
try {
$presenterReflection = new ReflectionClass($this);
$actionMethodName = $this->formatActionMethod($this->getAction());
$actionReflection = $presenterReflection->getMethod($actionMethodName);
} catch (ReflectionException $e) {
throw new NotImplementedException();
}
// client IP address checking
/** @var ?Identity $identity */
$identity = $this->getUser()->getIdentity();
$user = $identity?->getUserData();
if ($user) {
$this->verifyUserIpLock($user);
}
Validators::init();
$this->processParams($actionReflection);
// ACL-checking method
$this->tryCall($this->formatPermissionCheckMethod($this->getAction()), $this->params);
}
protected function isRequestJson(): bool
{
return $this->getHttpRequest()->getHeader("content-type") === "application/json";
}
/**
* @return User|null (null if no user is authenticated)
*/
protected function getCurrentUserOrNull(): ?User
{
/** @var ?Identity $identity */
$identity = $this->getUser()->getIdentity();
return $identity?->getUserData();
}
/**
* @return User
* @throws ForbiddenRequestException
*/
protected function getCurrentUser(): User
{
$user = $this->getCurrentUserOrNull();
if ($user === null) {
throw new ForbiddenRequestException();
}
return $user;
}
/**
* @throws ForbiddenRequestException
*/
protected function getAccessToken(): AccessToken
{
/** @var ?Identity $identity */
$identity = $this->getUser()->getIdentity();
if ($identity === null || $identity->getToken() === null) {
throw new ForbiddenRequestException();
}
return $identity->getToken();
}
/**
* @throws ForbiddenRequestException
*/
protected function getCurrentUserLocale(): string
{
return $this->getCurrentUser()->getSettings()->getDefaultLanguage();
}
/**
* Is current user in the given scope?
* @param string $scope Scope ID
* @return bool
*/
protected function isInScope(string $scope): bool
{
/** @var ?Identity $identity */
$identity = $this->getUser()->getIdentity();
if (!$identity) {
return false;
}
return $identity->isInScope($scope);
}
public function getFormatInstance(): MetaFormat
{
return $this->requestFormatInstance;
}
private function processParams(ReflectionMethod $reflection)
{
$actionPath = get_class($this) . $reflection->name;
// cache whether the action has a Format attribute
if (!FormatCache::formatAttributeStringCached($actionPath)) {
$extractedFormat = MetaFormatHelper::extractFormatFromAttribute($reflection);
FormatCache::cacheFormatAttributeString($actionPath, $extractedFormat);
}
// use a method specialized for formats if there is a format available
$format = FormatCache::getFormatAttributeString($actionPath);
if ($format !== null) {
$this->requestFormatInstance = $this->processParamsFormat($format, null);
}
// handle loose parameters
// cache the data from the loose attributes to improve performance
if (!FormatCache::looseParametersCached($actionPath)) {
$newParamData = MetaFormatHelper::extractRequestParamData($reflection);
FormatCache::cacheLooseParameters($actionPath, $newParamData);
}
$paramData = FormatCache::getLooseParameters($actionPath);
$this->processParamsLoose($paramData);
}
/**
* Processes loose parameters. Request parameters are validated, no new data is created.
* @param array $paramData Parameter data to be validated.
*/
private function processParamsLoose(array $paramData)
{
// validate each param
foreach ($paramData as $param) {
$paramValue = $this->getValueFromParamData($param);
// special case when the request parameter is an object (the raw request data is an array that needs to
// be mapped to the Format definition)
$mainValidator = $param->validators[0];
if ($mainValidator instanceof VObject) {
// first check whether the raw request data is an array
$param->conformsToDefinition($paramValue, [new VArray(strict: false)]);
// map the content of the array to the format
// (the created format instance is not used, because that feature is reserved for POST bodies)
$format = $mainValidator->format;
$this->processParamsFormat($format, $paramValue);
} else {
$param->conformsToDefinition($paramValue);
}
// Path and query parameter might need patching, so they have correct type for
// being injected into the presenter method.
if (
$param->type === Type::Path || $param->type === Type::Query
&& array_key_exists($param->name, $this->params)
) {
foreach ($param->validators as $validator) {
$validator->patchQueryParameter($this->params[$param->name]);
}
}
}
}
/**
* Processes parameters defined by a format. Request parameters are validated and a format instance with
* parameter values created.
* @param string $format The format defining the parameters.
* @param ?array $valueDictionary If not null, a nested format instance will be created. The values will be taken
* from here instead of the request object. Format validation ignores parameter type (path, query or post).
* A top-level format will be created if null.
* @throws InternalServerException Thrown when the format definition is corrupted/absent.
* @throws BadRequestException Thrown when the request parameter values do not conform to the definition.
* @return MetaFormat Returns a format instance with values filled from the request object.
*/
private function processParamsFormat(string $format, ?array $valueDictionary): MetaFormat
{
// get the parsed attribute data from the format fields
$formatToFieldDefinitionsMap = FormatCache::getFormatToFieldDefinitionsMap();
if (!array_key_exists($format, $formatToFieldDefinitionsMap)) {
throw new InternalServerException("The format $format is not defined.");
}
// maps field names to their attribute data
$nameToFieldDefinitionsMap = $formatToFieldDefinitionsMap[$format];
$formatInstance = MetaFormatHelper::createFormatInstance($format);
foreach ($nameToFieldDefinitionsMap as $fieldName => $requestParamData) {
$value = null;
// top-level format
if ($valueDictionary === null) {
$value = $this->getValueFromParamData($requestParamData);
// nested format
} else {
// Instead of retrieving the values with the getRequest call, use the provided $valueDictionary.
// This makes the nested format ignore the parameter type (path, query, post) which is intended.
// The data for this nested format cannot be spread across multiple param types, but it could be
// if this was not a nested format but the top level format.
if (array_key_exists($requestParamData->name, $valueDictionary)) {
$value = $valueDictionary[$requestParamData->name];
}
}
// handle nested format creation
// replace the value dictionary stored in $value with a format instance
$nestedFormatName = $requestParamData->getFormatName();
if ($nestedFormatName !== null) {
$value = $this->processParamsFormat($nestedFormatName, $value);
}
// this throws if the value is invalid
$formatInstance->checkedAssignWithSchema($requestParamData, $fieldName, $value);
}
// validate structural constraints
if (!$formatInstance->validateStructure()) {
throw new BadRequestException("All request fields are valid but additional structural constraints failed.");
}
return $formatInstance;
}
/**
* Calls either getPostField, getQueryField or getPathField based on the provided metadata.
* @param \App\Helpers\MetaFormats\RequestParamData $paramData Metadata of the request parameter.
* @throws \App\Exceptions\InternalServerException Thrown when an unexpected parameter location was set.
* @return mixed Returns the value from the request.
*/
private function getValueFromParamData(RequestParamData $paramData): mixed
{
switch ($paramData->type) {
case Type::Post:
return $this->getPostField($paramData->name, required: $paramData->required);
case Type::Query:
return $this->getQueryField($paramData->name, required: $paramData->required);
case Type::Path:
return $this->getPathField($paramData->name);
case Type::File:
return $this->getFileField(required: $paramData->required);
default:
throw new InternalServerException("Unknown parameter type: {$paramData->type->name}");
}
}
private function getPostField($param, $required = true)
{
$req = $this->getRequest();
$post = $req->getPost();
if ($req->isMethod("POST")) {
// nothing to see here...
} else {
if ($req->isMethod("PUT") || $req->isMethod("DELETE")) {
parse_str(file_get_contents('php://input'), $post);
} else {
throw new WrongHttpMethodException(
"Cannot get the post parameters in method '" . $req->getMethod() . "'."
);
}
}
if (array_key_exists($param, $post)) {
return $post[$param];
} else {
if ($required) {
throw new BadRequestException("Missing required POST field $param");
} else {
return null;
}
}
}
/**
* @param bool $required Whether the file field is required.
* @throws BadRequestException Thrown when the number of files is not 1 (and the field is required).
* @return FileUpload|null Returns a FileUpload object or null if the file was optional and not sent.
*/
private function getFileField(bool $required = true): FileUpload | null
{
$req = $this->getRequest();
$files = $req->getFiles();
if (count($files) === 0) {
if ($required) {
throw new BadRequestException("No file was uploaded");
} else {
return null;
}
} elseif (count($files) > 1) {
throw new BadRequestException("Too many files were uploaded");
}
$file = array_pop($files);
return $file;
}
private function getQueryField($param, $required = true)
{
$value = $this->getRequest()->getParameter($param);
if ($value === null && $required) {
throw new BadRequestException("Missing required query field $param");
}
return $value;
}
private function getPathField($param)
{
$value = $this->getParameter($param);
if ($value === null) {
throw new BadRequestException("Missing required path field $param");
}
return $value;
}
protected function logUserAction($code = IResponse::S200_OK)
{
if ($this->getUser()->isLoggedIn()) {
$remoteAddr = $this->getHttpRequest()->getRemoteAddress();
$params = $this->getRequest()->getParameters();
unset($params[self::ActionKey]);
$this->userActions->log($this->getAction(true), $remoteAddr, $params, $code);
}
}
protected function sendSuccessResponse($payload, $code = IResponse::S200_OK)
{
$this->logUserAction($code);
$resp = $this->getHttpResponse();
$resp->setCode($code);
$this->sendJson(
[
"success" => true,
"code" => $code,
"payload" => $payload
]
);
}
/**
* Special response for paginated contents. Sends items over with metadata about pagination, ordering, and filters.
* @param array $items Items to be sent.
* @param Pagination $pagination Object holding pagination metadata and ordering.
* @param bool $sliceItems If true, a slice of items array is created using pagination data.
* Otherwise, the items are expected to be already sliced.
* @param int|null $totalCount total count of all resources
* @param int $code response code
*/
protected function sendPaginationSuccessResponse(
array $items,
Pagination $pagination,
bool $sliceItems = false,
?int $totalCount = null,
$code = IResponse::S200_OK
) {
$this->sendSuccessResponse(
[
"items" => $sliceItems
? array_slice(
array_values($items),
$pagination->getOffset(),
$pagination->getLimit() ? $pagination->getLimit() : null
)
: array_values($items),
"totalCount" => ($totalCount === null) ? count($items) : $totalCount,
"offset" => $pagination->getOffset(),
"limit" => $pagination->getLimit(),
"orderBy" => $pagination->getOriginalOrderBy(),
"filters" => $pagination->getRawFilters(),
],
$code
);
}
protected function getPagination(...$params): Pagination
{
return new Pagination(...$params);
}
/**
* Wrapper for special responses that send one file directly from the storage.
* @param IImmutableFile $file to be sent
* @param string $name under which the file is presented in download
* @param string $contentType MIME
* @param bool $forceDownload
*/
protected function sendStorageFileResponse(
IImmutableFile $file,
string $name,
?string $contentType = null,
bool $forceDownload = true
) {
$this->logUserAction(200);
$this->sendResponse(new StorageFileResponse($file, $name, $contentType, $forceDownload));
}
/**
* Wrapper for special responses that prepare a new ZIP archive and send it over.
* @param array $files indexed by original name (becomes zip entry) where values are local paths (strings)
* or possibly IImmutableFile objects
* @param string|null $name
* @param bool $forceDownload
*/
protected function sendZipFilesResponse(array $files, ?string $name = null, bool $forceDownload = true)
{
$this->logUserAction(200);
$this->sendResponse(new ZipFilesResponse($files, $name, $forceDownload));
}
}