如何在特征内使用authorizationChecker

时间:2015-06-22 13:56:23

标签: symfony traits

我有一个特征,可以检查用户是否登录以及特定位置的尝试次数。

这个特性我试图在FormType中使用,以便在多次尝试后显示验证码。

内部getIpOrUserId()我正在尝试检查用户是否已登录$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY'),但它返回错误 Attempted to call an undefined method named "get" of class

我认为不可能创建Trait即服务,因此我可以注入安全对象。

有没有办法实现这个目标?

  

性状

<?php

Trait CheckAttempts {

public function getTryAttempts()
{
    if ($this->getIpOrUserId() == null) {
        return false;
    } else {
        $attempts = $this->getDoctrine()
            ->getRepository('SiteBundle:LoginAttempts')
            ->findOneByIpOrUserId($this->getIpOrUserId());
    }

    return $attempts->getAttempts();
}

protected function getIpOrUserId()
{
     //get logged in user
    //if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
      if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
        $ipOrUserId = $this->get('security.token_storage')->getToken()->getUser()->getId();            
    } else {
        $ipOrUserId = $this->container->get('request_stack')->getCurrentRequest()->getClientIp();
    }
    return $ipOrUserId;
}
  

FormType

class RegisterType extends AbstractType
{

use FormSendLimitTrait;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {

    $form = $event->getForm();
    var_dump($this->getTryAttempts());

    $form->add('captcha', 'captcha', 
          'label' => 'site.captcha'
    ]);

    /*if ($attempts->getAttempts() > 6) {
        $form->add('captcha', 'captcha', [
            'label' => 'site.captcha'
        ]);
    }*/
})

1 个答案:

答案 0 :(得分:2)

get方法仅在扩展Symfony\Bundle\FrameworkBundle\Controller\Controller类时有效,通常在控制器类中使用。它只返回$this->container->get($id),没有别的,这意味着它返回Symfony\Component\DependencyInjection\Container类。您应该将security.authorization_checker服务注入您的课程(或您想要的其他服务),甚至整个service_container服务(,但不推荐)。

示例:

class MyClass
{
    private $securityChecker;

    public function __construct(Symfony\Component\Security\Core\Authorization\AuthorizationChecker $securityChecker)
    {
        $this->securityChecker = $securityChecker;
    }

    ...
}

services.yml

services:
    my_class_service:
        class: Acme\DemoBundle\MyClass
        arguments: 
           - @security.authorization_checker

在您的案例中str_replace()