I'm trying to return the 404 page instead of 403 response for unpublished nodes in Drupal 8.
I tested kernel response subscriber, but found the code I was using would only change the status code to 404 from 403, not actually display the 404 page. So maybe someone can show me how to generate a 404 page Response object there?
This is the code I was using:
class ResponseSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [KernelEvents::RESPONSE => [['alterResponse']]];
}
/**
* Change status code to 404 from 403 if page is an unpublished node.
*
* @param FilterResponseEvent $event
* The route building event.
*/
public function alterResponse(FilterResponseEvent $event) {
if ($event->getResponse()->getStatusCode() == 403) {
/** @var \Symfony\Component\HttpFoundation\Request $request */
$request = $event->getRequest();
$node = $request->attributes->get('node');
if ($node instanceof Node && !$node->isPublished()) {
$response = $event->getResponse();
// This changes the code, but doesn't return a 404 page.
$response->setStatusCode(404);
$event->setResponse($response);
}
}
}
}
I finally resorted to removing this response subscriber completely and used hook_node_access like this:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\Core\Access\AccessResult;
function unpublished_404_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
if ($op == 'view' && !$node->isPublished()) {
if (\Drupal::moduleHandler()->moduleExists('workbench_moderation') && $account->hasPermission('view any unpublished content')) {
return AccessResult::neutral();
}
elseif (\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical' && \Drupal::routeMatch()->getRawParameter('node') == $node->id()) {
throw new NotFoundHttpException();
return AccessResult::neutral();
}
}
return AccessResult::neutral();
}
This seems to be in line with several answers on this site for Drupal 7. But I wanted to see if anyone has a better way of doing this either with a KernelEvent subscriber, rather than hook_node_access. It seems like what I want to do is test if a node is returning a 403 and then generate a new response with the 404 page and 404 status code. I'm not sure how to do that.