Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Secured Links 2.0 #11

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,28 @@
}
],
"require": {
"php": ">=5.4",
"php": ">=5.6",
"nette/application": "~2.2",
"nette/utils": "~2.2"
},
"require-dev": {
"nette/di": "~2.2",
"nette/tester": "~1.3",
"mockery/mockery": "~0.9"
"tracy/tracy": "~2.2",
"mockery/mockery": "~0.9",
"nikic/php-parser": "~2.0"
},
"suggest": {
"nette/di": "to use SecuredLinksExtension",
"nikic/php-parser": "to detect return types without @return annotation"
},
"extra": {
"branch-alias": {
"dev-master": "1.3-dev"
}
},
"autoload": {
"psr-4": { "Nextras\\Application\\UI\\": "src/" }
"psr-4": { "Nextras\\SecuredLinks\\": "src/" }
},
"replace": {
"nextras/application": "self.version"
Expand Down
209 changes: 209 additions & 0 deletions src/Bridges/NetteDI/SecuredLinksExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
<?php

/**
* This file is part of the Nextras Secured Links library.
*
* @license MIT
* @link https://github.com/nextras/secured-links
*/

namespace Nextras\SecuredLinks\Bridges\NetteDI;

use Generator;
use Nette;
use Nette\Application\IRouter;
use Nette\Application\UI\Presenter;
use Nette\DI\PhpReflection;
use Nette\Neon\Neon;
use Nette\Utils\Strings;
use Nextras\SecuredLinks\Bridges\PhpParser\ReturnTypeResolver;
use Nextras\SecuredLinks\RedirectChecker;
use Nextras\SecuredLinks\SecuredRouterFactory;
use PhpParser\Node;
use ReflectionClass;
use ReflectionMethod;


class SecuredLinksExtension extends Nette\DI\CompilerExtension
{

/** @var array */
public $defaults = [
'annotation' => 'secured', // can be NULL to disable
'destinations' => [],
'strictMode' => TRUE,
];


/**
* @inheritdoc
*/
public function beforeCompile()
{
$builder = $this->getContainerBuilder();
$builder->addDefinition($this->prefix('routerFactory'))
->setImplement(SecuredRouterFactory::class)
->setParameters(['Nette\Application\IRouter innerRouter'])
->setArguments([
$builder->literal('$innerRouter'),
'@Nette\Application\IPresenterFactory',
'@Nette\Http\Session',
$this->findSecuredRequests()
]);

$innerRouter = $builder->getByType(IRouter::class);
$builder->getDefinition($innerRouter)
->setAutowired(FALSE);

$builder->addDefinition($this->prefix('router'))
->setClass(IRouter::class)
->setFactory("@{$this->name}.routerFactory::create", ["@$innerRouter"])
->setAutowired(TRUE);

$builder->addDefinition($this->prefix('redirectChecker'))
->setClass(RedirectChecker::class);

$builder->getDefinition($builder->getByType(Nette\Application\Application::class))
->addSetup('?->onResponse[] = [?, ?]', ['@self', '@Nextras\SecuredLinks\RedirectChecker', 'checkResponse']);
}


/**
* @return array
*/
private function findSecuredRequests()
{
$securedRequests = [];

foreach ($this->findSecuredDestinations() as $presenterClass => $destinations) {
foreach ($destinations as $destination => $ignoredParams) {
if (Strings::endsWith($destination, '!')) {
$key = 'do';
$value = Strings::substring($destination, 0, -1);

} else {
$key = 'action';
$value = $destination;
}

$securedRequests[$presenterClass][$key][$value] = $ignoredParams;
}
}

return $securedRequests;
}


/**
* @return Generator
*/
private function findSecuredDestinations()
{
$config = $this->validateConfig($this->defaults);

foreach ($config['destinations'] as $presenterClass => $destinations) {
yield $presenterClass => $destinations;
}

if ($config['annotation']) {
$presenters = $this->getContainerBuilder()->findByType(Presenter::class);
foreach ($presenters as $presenterDef) {
$presenterClass = $presenterDef->getClass();
if (!isset($config['destinations'][$presenterClass])) {
$presenterRef = new \ReflectionClass($presenterClass);
yield $presenterClass => $this->findSecuredMethods($presenterRef);
}
}
}
}


/**
* @param ReflectionClass $classRef
* @return Generator
*/
private function findSecuredMethods(ReflectionClass $classRef)
{
foreach ($this->findTargetMethods($classRef) as $destination => $methodRef) {
if ($this->isSecured($methodRef, $ignoredParams)) {
yield $destination => $ignoredParams;
}
}
}


/**
* @param ReflectionClass $classRef
* @return Generator|ReflectionMethod[]
*/
private function findTargetMethods(ReflectionClass $classRef)
{
foreach ($classRef->getMethods() as $methodRef) {
$methodName = $methodRef->getName();

if (Strings::startsWith($methodName, 'action') && $classRef->isSubclassOf(Presenter::class)) {
$destination = Strings::firstLower(Strings::after($methodName, 'action'));
yield $destination => $methodRef;

} elseif (Strings::startsWith($methodName, 'handle')) {
$destination = Strings::firstLower(Strings::after($methodName, 'handle')) . '!';
yield $destination => $methodRef;

} elseif (Strings::startsWith($methodName, 'createComponent')) {
$returnType = $this->getMethodReturnType($methodRef);
if ($returnType !== NULL) {
$returnTypeRef = new ReflectionClass($returnType);
$componentName = Strings::firstLower(Strings::after($methodName, 'createComponent'));
foreach ($this->findTargetMethods($returnTypeRef) as $innerDestination => $innerRef) {
yield "$componentName-$innerDestination" => $innerRef;
}

} elseif ($this->config['strictMode']) {
$className = $methodRef->getDeclaringClass()->getName();
throw new \LogicException(
"Unable to deduce return type for method $className::$methodName(); " .
"add @return annotation, install nikic/php-parser or disable strictMode in config"
);
}
}
}
}


/**
* @param ReflectionMethod $ref
* @param array|bool $params
* @return bool
*/
private function isSecured(ReflectionMethod $ref, & $params)
{
$annotation = preg_quote(isset($this->config['annotation'])
? $this->config['annotation']
: $this->defaults['annotation'],
'#'
);

if (preg_match("#^[ \\t/*]*@$annotation(?:[ \\t]+(\\[.*?\\])?|$)#m", $ref->getDocComment(), $matches)) {
$params = !empty($matches[1]) ? Neon::decode($matches[1]) : TRUE;
return TRUE;

} else {
return FALSE;
}
}


/**
* @param ReflectionMethod $methodRef
* @return NULL|string
*/
private function getMethodReturnType(ReflectionMethod $methodRef)
{
$returnType = PhpReflection::getReturnType($methodRef);
if ($returnType !== NULL || !interface_exists(\PhpParser\Node::class)) {
return $returnType;
} else {
return ReturnTypeResolver::getReturnType($methodRef);
}
}
}
Loading