2016-08-09 2 views
0

내 웹 사이트에 가입 할 수 있습니다. 나는 FOSUserBundle을 사용한다. 사용자가 가입하면 ROLE_SUBSCRIBER 역할을 획득하여 새 페이지에 대한 액세스 권한을 부여합니다. 사용자 엔티티에 기록한 기간이 지나면이 역할이 만료되기를 바랍니다.역할 만료 Symfony

class User extends BaseUser 
{ 
    // ... 

    * @ORM\Column(type="datetime") 
    protected $subscribeExpiration; 


    public function setSubscribeExpiration(\DateTime $subscribeExpiration) { 
     $this->subscribeExpiration = clone $subscribeExpiration; 

     return $this; 
    } 
    public function getSubscribeExpiration() { 
     return $this->subscribeExpiration; 
    } 

    // ... 
} 

답변

1

ROLE은 사용하지 말고 Voter을 사용하십시오.

// src/AppBundle/Security/PostVoter.php 
namespace AppBundle\Security; 

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; 
use Symfony\Component\Security\Core\Authorization\Voter\Voter; 

use AppBundle\Entity\User; 

class SubscriberVoter extends Voter 
{ 
    const IS_SUBSCRIBER = 'is_subscriber'; 

    protected function supports($attribute, $subject) 
    { 
     if (!in_array($attribute, array(self::IS_SUBSCRIBER))) { 
      return false; 
     } 

     return true; 
    } 

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token) 
    { 
     $user = $token->getUser(); 

     if (!$user instanceof User) { 
      // the user must be logged in; if not, deny access 
      return false; 
     } 

     // you know $subject is a Post object, thanks to supports 
     /** @var Post $post */ 
     $post = $subject; 

     switch ($attribute) { 
      case self::IS_SUBSCRIBER: 
       $expireDate = $user->getSubscriberExpireDate(); 
       $currendDate = new \DateTime(); 

       return (null !== $expireDate && $expireDate > $currendDate); 
     } 

     throw new \LogicException('This code should not be reached!'); 
    } 
} 

이 '역할'을 확인하려면 :

$this->isGranted('is_subscriber'); 
사용자가에 가입자인지 아닌지

그런 다음 유권자 검사에서 EXPIREDATE 결정하기 위해