symnedi/security

此包已被废弃且不再维护。作者建议使用 symplify/symfony-security 包。

从 Symfony\Security 集成到 Nette 的投票和防火墙功能。

v0.3.0 2016-12-02 00:05 UTC

This package is not auto-updated.

Last update: 2022-02-01 12:47:43 UTC


README

Build Status Quality Score Code Coverage Downloads Latest stable

安装

composer require symnedi/security

注册扩展

# app/config/config.neon
extensions:
	- Symnedi\Security\DI\SecurityExtension
	- Symnedi\EventDispatcher\DI\EventDispatcherExtension

用法

投票者

首先,阅读 Symfony 烹饪书

然后创建一个新的投票者实现 Symfony\Component\Security\Core\Authorization\Voter\VoterInterface 并将其注册为服务在 config.neon

services:
	- App\SomeModule\Security\Voter\MyVoter

然后在需要验证访问的地方,我们将使用 AuthorizationChecker

use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;


class Presenter
{

	/**
	 * @var AuthorizationCheckerInterface
	 */
	private $authorizationChecker;

	
	public function __construct(AuthorizationCheckerInterface $authorizationChecker)
	{
		$this->authorizationChecker = $authorizationChecker;
	}


	/**
	 * @param PresenterComponentReflection $element
	 */
	public function checkRequirements($element)
	{
		if ($this->authorizationChecker->isGranted('access', $element) === FALSE) {
			throw new ForbiddenRequestException;
		}
	}

}

防火墙

原始 Symfony 防火墙 简化了模块化支持。

我们需要创建的是一个 匹配器 和一个 监听器

请求匹配器

此服务将匹配管理员模块中的所有站点 - 以 /admin 开头的 url

use Symfony\Component\HttpFoundation\Request;
use Symnedi\Security\Contract\HttpFoundation\RequestMatcherInterface;


class AdminRequestMatcher implements RequestMatcherInterface
{

	/**
	 * {@inheritdoc}
	 */
	public function getFirewallName()
	{
		return 'adminSecurity';
	}
	
	
	/**
	 * {@inheritdoc}
	 */
	public function matches(Request $request)
	{
		$url = $request->getPathInfo();
		return strpos($url, '/admin') === 0;
	}

}

防火墙监听器

它将确保用户已登录并且具有 'admin' 角色,否则将重定向。

use Nette\Application\AbortException;
use Nette\Application\Application;
use Nette\Application\Request;
use Nette\Security\User;
use Symnedi\Security\Contract\Http\FirewallListenerInterface;


class LoggedAdminFirewallListener implements FirewallListenerInterface
{

	/**
	 * @var User
	 */
	private $user;
	

	public function __construct(User $user)
	{
		$this->user = $user;
	}
	
	
	/**
	 * {@inheritdoc}
	 */
	public function getFirewallName()
	{
		return 'adminSecurity';
	}

	
	/**
	 * {@inheritdoc}
	 */
	public function handle(Application $application, Request $applicationRequest)
	{
		if ( ! $this->user->isLoggedIn()) {
			throw new AbortException;
		}

		if ( ! $this->user->isInRole('admin')) {
			throw new AbortException;
		}
	}

}

然后我们注册这两个服务。

services:
	- AdminRequestMatcher
	- LoggedAdminFirewallListener

就这样!

测试

composer check-cs # see "scripts" section of composer.json for more details 
vendor/bin/phpunit

贡献

规则很简单

  • 新功能需要测试
  • 所有测试必须通过
  • 每个 PR 一个功能

我们很乐意合并你的功能!