Skip to content
Snippets Groups Projects
Commit a53ca419 authored by Dieter Holvoet's avatar Dieter Holvoet Committed by Geoff Appleby
Browse files

Issue #3409435: Add hook_csp_policy_alter for themes

parent f914ed79
No related branches found
No related tags found
No related merge requests found
<?php
/**
* @file
* Documentation for CSP module APIs.
*/
/**
* @addtogroup hooks
* @{
*/
use Drupal\csp\Csp;
use Symfony\Component\HttpFoundation\Response;
/**
* Alters the CSP policy.
*
* This hook is only invoked for themes, modules should add an event subscriber
* listening to the CspEvents::POLICY_ALTER event.
*
* @param \Drupal\csp\Csp $policy
* The CSP policy.
* @param \Symfony\Component\HttpFoundation\Response $response
* The response the policy is applied to.
*/
function hook_csp_policy_alter(Csp $policy, Response $response): void {
$policy->appendDirective('img-src', 'https://example.com');
}
/**
* @} End of "addtogroup hooks".
*/
......@@ -33,6 +33,13 @@ services:
tags:
- { name: event_subscriber }
csp.theme_hook_csp_subscriber:
class: Drupal\csp\EventSubscriber\ThemeHookCspSubscriber
arguments:
- '@theme.manager'
tags:
- { name: event_subscriber }
logger.channel.csp:
parent: logger.channel_base
arguments: ['csp']
<?php
namespace Drupal\csp\EventSubscriber;
use Drupal\Core\Theme\ThemeManagerInterface;
use Drupal\csp\CspEvents;
use Drupal\csp\Event\PolicyAlterEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Invoke a hook allowing themes to alter the CSP policy.
*/
class ThemeHookCspSubscriber implements EventSubscriberInterface {
/**
* The theme manager service.
*
* @var \Drupal\Core\Theme\ThemeManagerInterface
*/
protected $themeManager;
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[CspEvents::POLICY_ALTER] = ['onCspPolicyAlter', -10];
return $events;
}
/**
* ThemeHookCspSubscriber constructor.
*
* @param \Drupal\Core\Theme\ThemeManagerInterface $themeManager
* The theme manager service.
*/
public function __construct(ThemeManagerInterface $themeManager) {
$this->themeManager = $themeManager;
}
/**
* Invoke a hook allowing themes to alter the CSP policy.
*
* @param \Drupal\csp\Event\PolicyAlterEvent $alterEvent
* The policy alter event.
*/
public function onCspPolicyAlter(PolicyAlterEvent $alterEvent) {
$policy = $alterEvent->getPolicy();
$response = $alterEvent->getResponse();
$this->themeManager->alter('csp_policy', $policy, $response);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment