2016-12-05 88 views
0

我的目標是隻允許每個用戶一個會話。Symfony3:在會話表中添加user_id字段以防止併發連接

爲此,我嘗試檢測某人在嘗試連接時某個會話是否對特定用戶仍處於活動狀態。

我想出的最佳解決方案是將用戶ID添加到我在數據庫的會話存儲中,但無法使其工作。

我試圖用this answer和適應它的Symfony 3,但我一直有以下錯誤,無法找出原因:

AuthorizationChecker cannot be converted to string 

這裏是我的代碼:

UserIdPdoSessionHandler.php

<?php 

namespace UserBundle\Utils; 


use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler; 
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; 
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; 

class UserIdPdoSessionHandler extends PdoSessionHandler 
{ 
    /** 
    * @var \PDO PDO instance. 
    */ 
    private $pdo; 

    /** 
    * @var array Database options. 
    */ 
    private $dbOptions; 

    /** 
    * @var AuthorizationCheckerInterface 
    */ 
    private $authorizationChecker; 

    /** 
    * @var TokenStorageInterface 
    */ 
    private $tokenStorage; 

    public function __construct(\PDO $pdo, array $dbOptions = array(), AuthorizationChecker $authorizationChecker, TokenStorage $tokenStorage) 
    { 
     $this->pdo = $pdo; 
     $this->dbOptions = array_merge(
      array('db_user_id_col' => 'user_id'), 
      $dbOptions 
     ); 
     $this->$authorizationChecker = $authorizationChecker; 
     $this->$tokenStorage = $tokenStorage; 

     parent::__construct($pdo, $dbOptions); 
    } 

    public function read($id) 
    { 
     // get table/columns 
     $dbTable = $this->dbOptions['db_table']; 
     $dbDataCol = $this->dbOptions['db_data_col']; 
     $dbIdCol = $this->dbOptions['db_id_col']; 

     try { 
      $sql = "SELECT $dbDataCol FROM $dbTable WHERE $dbIdCol = :id"; 

      $stmt = $this->pdo->prepare($sql); 
      $stmt->bindParam(':id', $id, \PDO::PARAM_STR); 

      $stmt->execute(); 
      // it is recommended to use fetchAll so that PDO can close the DB cursor 
      // we anyway expect either no rows, or one row with one column. fetchColumn, seems to be buggy #4777 
      $sessionRows = $stmt->fetchAll(\PDO::FETCH_NUM); 

      if (count($sessionRows) == 1) { 
       return base64_decode($sessionRows[0][0]); 
      } 

      // session does not exist, create it 
      $this->createNewSession($id); 

      return ''; 
     } catch (\PDOException $e) { 
      throw new \RuntimeException(sprintf('PDOException was thrown when trying to read the session data: %s', $e->getMessage()), 0, $e); 
     } 
    } 

    /** 
    * {@inheritDoc} 
    */ 
    public function write($id, $data) 
    { 
     // get table/column 
     $dbTable  = $this->dbOptions['db_table']; 
     $dbDataCol = $this->dbOptions['db_data_col']; 
     $dbIdCol  = $this->dbOptions['db_id_col']; 
     $dbTimeCol = $this->dbOptions['db_time_col']; 
     $dbUserIdCol = $this->dbOptions['db_user_id_col']; 

     //session data can contain non binary safe characters so we need to encode it 
     $encoded = base64_encode($data); 

     $userId = $this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED') ? 
      $this->tokenStorage->getToken()->getUser()->getId() : 
      null 
     ; 

     try { 
      $driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME); 

      if ('mysql' === $driver) { 
       // MySQL would report $stmt->rowCount() = 0 on UPDATE when the data is left unchanged 
       // it could result in calling createNewSession() whereas the session already exists in 
       // the DB which would fail as the id is unique 
       $stmt = $this->pdo->prepare(
        "INSERT INTO $dbTable ($dbIdCol, $dbDataCol, $dbTimeCol, $dbUserIdCol) VALUES (:id, :data, :time, :user_id) " . 
        "ON DUPLICATE KEY UPDATE $dbDataCol = VALUES($dbDataCol), $dbTimeCol = VALUES($dbTimeCol)" 
       ); 
       $stmt->bindParam(':id', $id, \PDO::PARAM_STR); 
       $stmt->bindParam(':data', $encoded, \PDO::PARAM_STR); 
       $stmt->bindValue(':time', time(), \PDO::PARAM_INT); 
       $stmt->bindParam(':user_id', $userId, \PDO::PARAM_STR); 
       $stmt->execute(); 
      } elseif ('oci' === $driver) { 
       $stmt = $this->pdo->prepare("MERGE INTO $dbTable USING DUAL ON($dbIdCol = :id) ". 
        "WHEN NOT MATCHED THEN INSERT ($dbIdCol, $dbDataCol, $dbTimeCol, $dbUserIdCol) VALUES (:id, :data, sysdate, :user_id) " . 
        "WHEN MATCHED THEN UPDATE SET $dbDataCol = :data WHERE $dbIdCol = :id"); 

       $stmt->bindParam(':id', $id, \PDO::PARAM_STR); 
       $stmt->bindParam(':data', $encoded, \PDO::PARAM_STR); 
       $stmt->bindParam(':user_id', $userId, \PDO::PARAM_STR); 
       $stmt->execute(); 
      } else { 
       $stmt = $this->pdo->prepare("UPDATE $dbTable SET $dbDataCol = :data, $dbTimeCol = :time WHERE $dbIdCol = :id"); 
       $stmt->bindParam(':id', $id, \PDO::PARAM_STR); 
       $stmt->bindParam(':data', $encoded, \PDO::PARAM_STR); 
       $stmt->bindValue(':time', time(), \PDO::PARAM_INT); 
       $stmt->execute(); 

       if (!$stmt->rowCount()) { 
        // No session exists in the database to update. This happens when we have called 
        // session_regenerate_id() 
        $this->createNewSession($id, $data); 
       } 
      } 
     } catch (\PDOException $e) { 
      throw new \RuntimeException(sprintf('PDOException was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e); 
     } 

     return true; 
    } 

    private function createNewSession($id, $data = '') 
    { 
     // get table/column 
     $dbTable  = $this->dbOptions['db_table']; 
     $dbDataCol = $this->dbOptions['db_data_col']; 
     $dbIdCol  = $this->dbOptions['db_id_col']; 
     $dbTimeCol = $this->dbOptions['db_time_col']; 
     $dbUserIdCol = $this->dbOptions['db_user_id_col']; 

     $userId = $this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED') ? 
      $this->tokenStorage->getToken()->getUser()->getId() : 
      null 
     ; 

     $sql = "INSERT INTO $dbTable ($dbIdCol, $dbDataCol, $dbTimeCol, $dbUserIdCol) VALUES (:id, :data, :time, :user_id)"; 

     //session data can contain non binary safe characters so we need to encode it 
     $encoded = base64_encode($data); 
     $stmt = $this->pdo->prepare($sql); 
     $stmt->bindParam(':id', $id, \PDO::PARAM_STR); 
     $stmt->bindParam(':data', $encoded, \PDO::PARAM_STR); 
     $stmt->bindValue(':time', time(), \PDO::PARAM_INT); 
     $stmt->bindParam(':user_id', $userId, \PDO::PARAM_STR); 
     $stmt->execute(); 

     return true; 
    } 
} 

services.yml

pdo: 
    class: PDO 
    arguments: 
     dsn:  "mysql:host=%database_host%;dbname=%database_name%" 
     user:  "%database_user%" 
     password: "%database_password%" 

session.handler.pdo: 
    class:  UserBundle\Utils\UserIdPdoSessionHandler 
    public: false 
    arguments: [ "@pdo", "%pdo.db_options%", "@service_container" ] 

我的第一個想法是添加最後的sessionId用戶使用,並檢查它是否還活着,但存儲在數據庫中的ID是由

$request->getSession()->getId(); 

檢索到的一個不同的我這樣做是正確的?你能想出一個更好的方法來實現我的最終目標嗎?

回答

0

我的不好,我忘了從會話配置中刪除「save_path」。 這就是爲什麼保存在數據庫中的會話ID與從Request對象中檢索到的ID不同。

所以我只在我的用戶實體中添加了一個字段「lastSessionId」,所以現在我可以檢查這個會話是否仍然有效。