Exemple #1
0
 /**
  * Create temporary auth token in database and cache. Delete old authentication
  * records for this client with current ip address.
  * @return type
  */
 private function createApiDeviceRecord()
 {
     if ($this->model == null) {
         return;
     }
     $pkAttribute = $this->model->tableSchema->primaryKey;
     // generate data for new temp auth token
     $newRecord = array('ip_address' => $this->module->getIpAddress(), 'token' => self::generateRandomToken(), 'connected_type' => $this->model->tableName(), 'connected_id' => $this->model->{$pkAttribute}, 'update_time' => date('Y-m-d H:i:s'));
     // delete auth record for the current entity
     if (Yii::app()->cache) {
         $oldTokensCommand = Yii::app()->db->createCommand("SELECT * FROM {$this->module->authTableName} WHERE connected_type=:type AND connected_id=:id AND ip_address=:ip");
         $oldTokensCommand->bindValues(array(':type' => $newRecord['connected_type'], ':id' => $newRecord['connected_id'], ':ip' => $newRecord['ip_address']));
         $tokens = $oldTokensCommand->queryAll();
         foreach ($tokens as $token) {
             Yii::app()->cache->delete("api-auth-token-" . $token['token']);
         }
     }
     // delete auth records from database
     $deleteCommand = Yii::app()->db->createCommand("DELETE FROM {$this->module->authTableName} WHERE connected_type=:type AND connected_id=:id AND ip_address=:ip");
     $deleteCommand->bindValues(array(':type' => $newRecord['connected_type'], ':id' => $newRecord['connected_id'], ':ip' => $newRecord['ip_address']));
     $deleteCommand->execute();
     // insert new one
     $insertCommand = Yii::app()->db->createCommand("INSERT INTO {$this->module->authTableName}(token, ip_address, update_time, connected_type, connected_id) VALUES(:token, :ip, :date, :type, :id)");
     $insertCommand->bindValues(array(':token' => $newRecord['token'], ':date' => $newRecord['update_time'], ':type' => $newRecord['connected_type'], ':id' => $newRecord['connected_id'], ':ip' => $newRecord['ip_address']));
     if ($insertCommand->execute()) {
         // update this model with new token
         $this->setIsAuthenticated($newRecord);
         if (isset(Yii::app()->cache)) {
             Yii::app()->cache->set("api-auth-token-" . $this->token, $newRecord, $this->module->authCacheDuration);
         }
     }
 }