角色Symfony到期

时间:2016-08-09 15:53:55

标签: php fosuserbundle symfony

您可以在我的网站上订阅。我使用FOSUserBundle。 当用户订阅时,他赢得了角色ROLE_SUBSCRIBER,使其可以访问新页面。 我想这个角色在我记录在用户实体中的一段时间后过期。

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 个答案:

答案 0 :(得分:1)

不要使用ROLE,而是使用Voter

然后,在你的选民中检查expireDate,以决定用户是否是子纤维:

// 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');