Skip to content

Commit

Permalink
Configure headers in response setup
Browse files Browse the repository at this point in the history
  • Loading branch information
mabar committed Mar 25, 2019
1 parent b244945 commit c23f7b6
Showing 1 changed file with 7 additions and 12 deletions.
19 changes: 7 additions & 12 deletions src/Bridges/HttpDI/HttpExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
namespace Nette\Bridges\HttpDI;

use Nette;
use Nette\PhpGenerator\Helpers;


/**
* HTTP extension for Nette DI.
Expand Down Expand Up @@ -71,13 +69,13 @@ public function loadConfiguration()
}


public function afterCompile(Nette\PhpGenerator\ClassType $class)
public function beforeCompile()
{
if ($this->cliMode) {
return;
}

$initialize = $class->getMethod('initialize');
$builder = $this->getContainerBuilder();
$config = $this->getConfig();
$headers = array_map('strval', $config['headers']);

Expand All @@ -91,16 +89,14 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
$headers['X-Frame-Options'] = $frames;
}

$code = [];
foreach (['csp', 'cspReportOnly'] as $key) {
if (empty($config[$key])) {
continue;
}
$value = self::buildPolicy($config[$key]);
if (strpos($value, "'nonce'")) {
$code[0] = '$cspNonce = base64_encode(random_bytes(16));';
$value = Nette\DI\ContainerBuilder::literal(
'str_replace(?, ? . $cspNonce, ?)',
'str_replace(?, ? . (isset($cspNonce) \? $cspNonce : $cspNonce = base64_encode(random_bytes(16))), ?)',
["'nonce", "'nonce-", $value]
);
}
Expand All @@ -111,16 +107,15 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
$headers['Feature-Policy'] = self::buildPolicy($config['featurePolicy']);
}

$code[] = Helpers::formatArgs('$response = $this->getService(?);', [$this->prefix('response')]);
foreach ($headers as $key => $value) {
if ($value !== '') {
$code[] = Helpers::formatArgs('$response->setHeader(?, ?);', [$key, $value]);
$builder->getDefinition($this->prefix('response'))
->addSetup('?->setHeader(?, ?);', ['@self', $key, $value]);
}
}

$code[] = Helpers::formatArgs('$response->setCookie(...?);', [['nette-samesite', '1', 0, '/', null, null, true, 'Strict']]);

$initialize->addBody("(function () {\n\t" . implode("\n\t", $code) . "\n})();");
$builder->getDefinition($this->prefix('response'))
->addSetup('?->setCookie(...?)', ['@self', ['nette-samesite', '1', 0, '/', null, null, true, 'Strict']]);
}


Expand Down

0 comments on commit c23f7b6

Please sign in to comment.