2
votes

I want to give to an user a ROLE for a time limited. For example, if I have three roles:

  1. ROLE_ADMIN
  2. ROLE_ACTIVE
  3. ROLE_USER

When a user is created he become with the ROLE_ACTIVE account, he has 30 days to use the account, then he become the ROLE_USER.

I have seen the credentials_expire_at in the user entity, but how do I use it?

1

1 Answers

1
votes

You can set the credentialsExpiresAt like:

$user = new User(); // depends on your user class name
$user->setCredentialsExpireAt(new \DateTime()); // expires now for example

This only solves part of your problem as once the Date has passed the setCredentialsExpireAt date the user wont be able to login anymore as their login has expired.

You could tackle this issue a number of ways, maybe run a cronjob that looks for expired users with the ROLE_ACTIVE role and changes their ROLE and re-activates the account.

Or this other option may work better for your situation:

Override the following method in the User Model:

//  FOSUserBundle/Model/User.php - override this in your child bundle.
public function isCredentialsNonExpired()
{
    if (true === $this->credentialsExpired) {
        return false;
    }
    if (null !== $this->credentialsExpireAt && $this->credentialsExpireAt->getTimestamp() < time()) {
        return false;
    }
    return true;
}

In this if block:

if (null !== $this->credentialsExpireAt && $this->credentialsExpireAt->getTimestamp() < time()) {

Replace the return false with logic to change the users role if they have ROLE_ACTIVE, remove the expiry and reactivate the account. Save the user details and return true.

Basically this should mean that when the user logs in and the FOSUserBundle checks to see if the account has expired, you will have an opportunity to override the expiration and make the required changes before the user is denied access, You will still need to set the credentialsExpireAt on account creation.

EDIT:

For your particular use case I think it would be a good idea to set the credentialsExpiresAt field to now + 30 days globally. You can do this in your User Entity, Which when using FOSUserBundle.. you are required to extend.

// Your file that extends FOSUserBundle/Model/User.php
public function __construct()
{
    parent::__construct();
    $this->setCredentialsExpireAt(
        new \DateTime(date('Y-m-d H:i:s', strtotime("+30 days")))
    );
}

With this code in place every new user's credentials will expire within 30 days, in which your code will have an opportunity to catch the event and override whatever you need.