2017-04-08 50 views
0

我有一個代碼,它工作的問題是它唯一的1人工作。因此,如果我登錄,那麼除非該令牌過期,否則不會再爲任何用戶顯示登錄屏幕。PHP谷歌雲端硬盤API集成用戶登錄和列表文件

的index.php

<?php 

session_start(); 
require_once __DIR__ . '/vendor/autoload.php'; 

$client = new Google_Client(); 
$client->setAuthConfig('client_id.json'); 
$client->addScope(Google_Service_Drive::DRIVE); 

if (file_exists("credentials.json")) { 
    $access_token = (file_get_contents("credentials.json")); 
    $client->setAccessToken($access_token); 
    //Refresh the token if it's expired. 
    if ($client->isAccessTokenExpired()) { 
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); 
    file_put_contents($credentialsPath, json_encode($client->getAccessToken())); 
    } 
    $drive_service = new Google_Service_Drive($client); 
    $files_list = $drive_service->files->listFiles(array())->getFiles(); 
    if (count($files_list) == 0) { 
    print "No files found.\n"; 
} else { 
    foreach ($files_list as $file) { 
     $res['name'] = $file->getName(); 
     $res['id'] = $file->getId(); 
     $files[] = $res; 
    } 
    print_r($files); 
} 
} else { 
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/callback.php'; 
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); 
} 

所以索引文件檢查credentials.json文件有訪問令牌與否,如果存在,那麼列表通過回調文件中的文件其他明智的登錄用戶。

callback.php

<?php 
session_start(); 
require_once __DIR__ . '/vendor/autoload.php'; 
$client = new Google_Client(); 
$client->setAuthConfigFile('client_id.json'); 
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/callback.php'); 
$client->addScope(Google_Service_Drive::DRIVE); //::DRIVE_METADATA_READONLY 

if (! isset($_GET['code'])) { 
    $auth_url = $client->createAuthUrl(); 
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); 
} else { 
    $client->authenticate($_GET['code']); 
    $access_token = $client->getAccessToken(); 
    file_put_contents("credentials.json", json_encode($access_token)); 

    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php'; 
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); 
} 

這是錯誤的做法我猜是因爲它只存儲1個令牌,並顯示出其價值。有沒有辦法每個沒有登錄的人都需要登錄才能看到他的文件列表。

感謝。

回答

0

您可以嘗試添加用於註銷的按鈕或創建一個會自動註銷用戶的功能。如post所述,您可以使用gapi.auth2.getAuthInstance().signOut()來防止您的網站在被調用後自動登錄。

你可以試試他的演示site。在演示中,當他們離開如下面的代碼所示的頁面在用戶登出:

window.onbeforeunload = function(e){ 
    gapi.auth2.getAuthInstance().signOut(); 
}; 

他在相關答案後,大約有防止自動登入解釋。您可以使用諸如關閉窗口或離開的事件來觸發註銷方法。

希望這會有所幫助。

相關問題