Esempio n. 1
0
 /**
  * Validate a token.
  *
  * Tokens should be deleted if they are generated as one-time tokens
  * with a unique ID each time.  If the are per-session, then they should be
  * generated with the same unique ID and not deleted when validated here.
  *
  * @param string  $token       Token to validate.
  * @param boolean $delete      Whether to delete the token if valid.
  * @param boolean $checkExpire Whether to check for token expiry.
  *
  * @return boolean
  */
 public function validate($token, $delete = true, $checkExpire = true)
 {
     if (!$token) {
         return false;
     }
     list($id, $hash, $timestamp) = $this->tokenGenerator->decode($token);
     $decoded = array('id' => $id, 'time' => $timestamp);
     // Garbage collect the session.
     $this->tokenGenerator->garbageCollection();
     // Check if token ID exists first.
     $stored = $this->storage->get($decoded['id']);
     if (!$stored) {
         return false;
     }
     // Check if the token has been tampered with.
     $duplicateToken = $this->tokenGenerator->generate($decoded['id'], $decoded['time'])->getToken();
     if ($stored['token'] !== $duplicateToken) {
         $this->storage->delete($decoded['id']);
         return false;
     }
     // Check if token has expired.
     if ($checkExpire) {
         $timeDiff = (int) $decoded['time'] + $this->tokenGenerator->getMaxLifetime() - time();
         if ($timeDiff < 0) {
             $this->storage->delete($decoded['id']);
             return false;
         }
     }
     // All checked out, delete the token and return true.
     if ($delete) {
         $this->storage->delete($decoded['id']);
     }
     return true;
 }
Esempio n. 2
0
 /**
  * Runs garbage collection to clean up tokens that expire
  * before the session expired.
  *
  * Generates a number between 1 and $probability and runs
  * garbage collection if result is 1.
  *
  * @param integer $probability Defaults to 20, ie 1/20 = 5%
  */
 public function garbageCollection($probability = 20)
 {
     if (mt_rand(1, $probability) === 1) {
         $this->storage->gc($this->maxLifetime);
     }
 }