Skip to content

Commit

Permalink
Move response configuration from initialize method to response service
Browse files Browse the repository at this point in the history
  • Loading branch information
mabar committed Jul 6, 2019
1 parent 9901e0f commit 1718bd2
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions src/Bridges/HttpDI/HttpExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,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->config;
$headers = array_map('strval', $config->headers);

Expand All @@ -96,16 +96,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 @@ -116,16 +114,16 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
$headers['Feature-Policy'] = self::buildPolicy($config->featurePolicy);
}

$code[] = Helpers::formatArgs('$response = $this->getService(?);', [$this->prefix('response')]);
$response = $builder->getDefinition($this->prefix('response'));
assert($response instanceof Nette\DI\Definitions\ServiceDefinition);

foreach ($headers as $key => $value) {
if ($value !== '') {
$code[] = Helpers::formatArgs('$response->setHeader(?, ?);', [$key, $value]);
$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})();");
$response->addSetup('?->setCookie(...?)', ['@self', ['nette-samesite', '1', 0, '/', null, null, true, 'Strict']]);
}


Expand Down

0 comments on commit 1718bd2

Please sign in to comment.