Skip to content

Commit

Permalink
Breaking change: Also add CORS headers to failed requests
Browse files Browse the repository at this point in the history
  • Loading branch information
cundd committed Jan 30, 2019
1 parent d22351b commit ba3f86c
Showing 1 changed file with 38 additions and 29 deletions.
67 changes: 38 additions & 29 deletions Classes/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,35 +97,7 @@ public function processRequest(ServerRequestInterface $request, ResponseInterfac
*/
public function dispatch(RestRequestInterface $request, ResponseInterface $response)
{
$requestPath = $request->getPath();
if (!$requestPath || $requestPath === '/') {
return $this->greet($request);
}

// Checks if the request needs authentication
$access = $this->objectManager->getAccessController()->getAccess($request);
switch (true) {
case $access->isAllowed():
case $access->isAuthorized():
break;

case $access->isUnauthorized():
return $this->responseFactory->createErrorResponse('Unauthorized', 401, $request);

case $access->isDenied():
default:
return $this->responseFactory->createErrorResponse('Forbidden', 403, $request);
}

$newResponse = $this->getCachedResponseOrCallHandler($request, $response);
$newResponse = $this->addAdditionalHeaders($newResponse);

$this->logger->logResponse(
'response: ' . $newResponse->getStatusCode(),
['response' => (string)$newResponse->getBody()]
);

return $newResponse;
return $this->addAdditionalHeaders($this->dispatchInternal($request, $response));
}

/**
Expand Down Expand Up @@ -270,4 +242,41 @@ private function addAdditionalHeaders(ResponseInterface $response)

return $response;
}

/**
* @param RestRequestInterface $request
* @param ResponseInterface $response
* @return ResponseInterface
*/
private function dispatchInternal(RestRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$requestPath = $request->getPath();
if (!$requestPath || $requestPath === '/') {
return $this->greet($request);
}

// Checks if the request needs authentication
$access = $this->objectManager->getAccessController()->getAccess($request);
switch (true) {
case $access->isAllowed():
case $access->isAuthorized():
break;

case $access->isUnauthorized():
return $this->responseFactory->createErrorResponse('Unauthorized', 401, $request);

case $access->isDenied():
default:
return $this->responseFactory->createErrorResponse('Forbidden', 403, $request);
}

$newResponse = $this->getCachedResponseOrCallHandler($request, $response);

$this->logger->logResponse(
'response: ' . $newResponse->getStatusCode(),
['response' => (string)$newResponse->getBody()]
);

return $newResponse;
}
}

0 comments on commit ba3f86c

Please sign in to comment.