Hugo Fouquet Hugo Fouquet - 8 months ago 60
PHP Question

expiration of a role Symfony

You can subscribe on my website. I use FOSUserBundle.
When the user subscribes, he won the role ROLE_SUBSCRIBER giving it access to new page.
I would like this role expires after a period that I recorded in the User entity.

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;

// ...


Don't use a ROLE, but a Voter.

Then, in your voter check for the expireDate to decide if the user is a subsciber or not :

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

To check this 'role' :