2013-04-10 122 views
0

在我的web應用程序中,我使用谷歌api php客戶端訪問谷歌任務。我跟着一些教程,如here刷新標記谷歌API api php庫

$client = new Google_Client(); 
$tasksService = new Google_TasksService($client); 

$client->setAccessType('offline'); 

$cookie = $_COOKIE["token1"]; 

if(!empty($cookie)){ 
    $client->refreshToken($cookie); 
} 
else{ 
    $client->setAccessToken($client->authenticate($_GET['code'])); 
    $_SESSION['access_token'] = $client->getAccessToken(); 
    $sessionToken = json_decode($_SESSION['access_token']); 
    setcookie("token1", $sessionToken->refresh_token, time() + (20 * 365 * 24 * 60 * 60)); 
} 

當用戶點擊登錄URL時,他將被帶到許可屏幕。如果用戶點擊「允許訪問」,他將被重定向到網頁作爲已認證的用戶,然後我將refresh_token存儲在cookie中。如果在Cookie中存儲了refresh_token,則用戶將被重定向而不再允許訪問。我的代碼出現問題時,用戶註銷,他們可以訪問該網站作爲註銷用戶。如何解決問題?

謝謝!

回答

0

不要將令牌存儲在用戶的cookie中(由於種種原因,包括您的直接問題,這是一個壞主意)。您已經將它存儲在會話中。只需從$ _SESSION中檢索它。然後確保用戶註銷時會話過期。

0

更加用戶友好的方法是將授權碼存儲在與用戶ID相關聯的數據庫中。然後,當他登錄時,可以在不需要用戶再次授權的情況下獲取它(除非它已經過期 - 如果嘗試使用它時發生錯誤,則只需再次授權)。這些是我用來存儲授權碼和用戶ID的功能。這些_store和_get函數的變體可用於存儲與用戶關聯的任何數據。

function _store_auth_code($auth_code) { 
    $entry = array('auth_code'=> $auth_code, 
        'uid'  => $GLOBALS['user']->uid, 
    ); 
    flashum_entry_delete('flashum_auth_code', $entry); 
    flashum_entry_insert('flashum_auth_code', $entry); 
} 

function _get_auth_code() { 
    $entry = array('uid' => $GLOBALS['user']->uid, 
    ); 
    $return = flashum_entry_load('flashum_auth_code', $entry); 
    if ($return) { 
     return $return[0]->auth_code; 
    } else 
     return null; 
} 

function flashum_entry_load($db, $entry = array()) { 
    // Read all fields from the flashum table. 
    $select = db_select($db, 'flashum'); 
    $select->fields('flashum'); 

    // Add each field and value as a condition to this query. 
    foreach ($entry as $field => $value) { 
    $select->condition($field, $value); 
    } 
    // Return the result in object format. 
    return $select->execute()->fetchAll(); 
} 

function flashum_entry_delete($db, $entry) { 
    db_delete($db) 
    ->condition('uid', $entry['uid']) 
    ->execute(); 
} 

function flashum_entry_insert($db, $entry) { 
    $return_value = NULL; 
    try { 
    $return_value = db_insert($db) 
        ->fields($entry) 
        ->execute(); 
    } 
    catch (Exception $e) { 
    drupal_set_message(t('db_insert failed. Message = %message, query= %query', 
     array('%message' => $e->getMessage(), '%query' => $e->query_string)), 'error'); 
    } 
    return $return_value; 
}