Class to extend the generic Zend Http Client with the ability to perform secure AuthSub requests
Inheritance: extends Zend_Http_Client
Example #1
0
function setupDocsClient($token = null)
{
    global $authSubURL;
    $docsClient = null;
    // Fetch a new AuthSub token?
    if (!$token && !isset($_SESSION['sessionToken'])) {
        $next = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        $scope = 'http://docs.google.com/feeds/ https://docs.google.com/feeds/';
        $secure = 0;
        $session = 1;
        $permission = 1;
        // 1 - allows posting notices && allows reading profile data
        $authSubURL = Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
    } else {
        if (isset($_SESSION['sessionToken'])) {
            $httpClient = new Zend_Gdata_HttpClient();
            $httpClient->setAuthSubToken($_SESSION['sessionToken']);
            $docsClient = new Zend_Gdata_Docs($httpClient, 'google-OCRPHPDemo-v0.1');
        } else {
            $httpClient = new Zend_Gdata_HttpClient();
            $_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken(trim($token), $httpClient);
            $httpClient->setAuthSubToken($_SESSION['sessionToken']);
            $docsClient = new Zend_Gdata_Docs($httpClient, 'google-OCRPHPDemo-v0.1');
        }
    }
    return $docsClient;
}
Example #2
0
 public function testSecureAuthSubSigning()
 {
     if (!extension_loaded('openssl')) {
         $this->markTestSkipped('The openssl extension is not available');
     } else {
         $c = new Zend_Gdata_HttpClient();
         $c->setAuthSubPrivateKeyFile("Zend/Gdata/_files/RsaKey.pem", null, true);
         $c->setAuthSubToken('abcdefg');
         $requestData = $c->filterHttpRequest('POST', 'http://www.example.com/feed', array(), 'foo bar', 'text/plain');
         $authHeaderCheckPassed = false;
         $headers = $requestData['headers'];
         foreach ($headers as $headerName => $headerValue) {
             if (strtolower($headerName) == 'authorization') {
                 preg_match('/data="([^"]*)"/', $headerValue, $matches);
                 $dataToSign = $matches[1];
                 preg_match('/sig="([^"]*)"/', $headerValue, $matches);
                 $sig = $matches[1];
                 if (function_exists('openssl_verify')) {
                     $fp = fopen('Zend/Gdata/_files/RsaCert.pem', 'r', true);
                     $cert = '';
                     while (!feof($fp)) {
                         $cert .= fread($fp, 8192);
                     }
                     fclose($fp);
                     $pubkeyid = openssl_get_publickey($cert);
                     $verified = openssl_verify($dataToSign, base64_decode($sig), $pubkeyid);
                     $this->assertEquals(1, $verified, 'The generated signature was unable ' . 'to be verified.');
                     $authHeaderCheckPassed = true;
                 }
             }
         }
         $this->assertEquals(true, $authHeaderCheckPassed, 'Auth header not found for sig verification.');
     }
 }
Example #3
0
 /**
  * Returns a HTTP client object with the appropriate headers for communicating
  * with Google using AuthSub authentication.
  *
  * @return Zend_Http_Client
  */
 protected function _getAuthSubHttpClient()
 {
     $client = new Zend_Gdata_HttpClient();
     #$this->_client = Zend_Gdata_AuthSub::getHttpClient($this->_sessionNs->sessionToken);
     // This sets your private key to be used to sign subsequent requests
     $client->setAuthSubPrivateKeyFile('/pub/www/core_live/application/configs/core.key', null, true);
     return $client;
 }
Example #4
0
 public function picasaDelete($photoId)
 {
     $token = $this->get_login_token();
     $client = new Zend_Gdata_HttpClient();
     $client->setAuthSubToken($token);
     $client->setClientLoginToken($token);
     $gphoto = new Zend_Gdata_Photos($client);
     $photoQuery = $gphoto->newPhotoQuery();
     $photoQuery->setUser($this->config['user']);
     $photoQuery->setAlbumId($this->config['album_id']);
     $photoQuery->setPhotoId($photoId);
     $photoQuery->setType('entry');
     $entry = $gphoto->getPhotoEntry($photoQuery);
     $gphoto->deletePhotoEntry($entry, true);
 }
Example #5
0
 /**
  * Performs a HTTP request using the specified method.
  *
  * Overrides the definition in the parent (Zend_Gdata_App)
  * and uses the Zend_Gdata_HttpClient functionality
  * to filter the HTTP requests and responses.
  *
  * @param string $method The HTTP method for the request -
  *                       'GET', 'POST', 'PUT', 'DELETE'
  * @param string $url The URL to which this request is being performed,
  *                    or null if found in $data
  * @param array $headers An associative array of HTTP headers
  *                       for this request
  * @param string $body The body of the HTTP request
  * @param string $contentType The value for the content type of the
  *                            request body
  * @param int $remainingRedirects Number of redirects to follow
  *                                if requests results in one
  * @return Zend_Http_Response The response object
  */
 public function performHttpRequest($method, $url, $headers = array(), $body = null, $contentType = null, $remainingRedirects = null)
 {
     if ($this->_httpClient instanceof Zend_Gdata_HttpClient) {
         $filterResult = $this->_httpClient->filterHttpRequest($method, $url, $headers, $body, $contentType);
         $method = $filterResult['method'];
         $url = $filterResult['url'];
         $body = $filterResult['body'];
         $headers = $filterResult['headers'];
         $contentType = $filterResult['contentType'];
         return $this->_httpClient->filterHttpResponse(parent::performHttpRequest($method, $url, $headers, $body, $contentType, $remainingRedirects));
     } else {
         return parent::performHttpRequest($method, $url, $headers, $body, $contentType, $remainingRedirects);
     }
 }
 /**
  * Retrieve a HTTP client object with AuthSub credentials attached
  * as the Authorization header
  *
  * @param string $token The token to retrieve information about
  * @param Zend_Gdata_HttpClient $client (optional) HTTP client to use to make the request
  */
 public static function getHttpClient($token, $client = null)
 {
     if ($client == null) {
         $client = new Zend_Gdata_HttpClient();
     }
     if (!$client instanceof Zend_Gdata_HttpClient) {
         // require_once 'Zend/Gdata/App/HttpException.php';
         throw new Zend_Gdata_App_HttpException('Client is not an instance of Zend_Gdata_HttpClient.');
     }
     $useragent = 'Zend_Framework_Gdata/' . Zend_Version::VERSION;
     $client->setConfig(array('strictredirects' => true, 'useragent' => $useragent));
     $client->setAuthSubToken($token);
     return $client;
 }
function authenticate($singleUseToken = null)
{
    $sessionToken = isset($_SESSION['sessionToken']) ? $_SESSION['sessionToken'] : null;
    // If there is no AuthSub session or one-time token waiting for us,
    // redirect the user to Google Health's AuthSub handler to get one.
    if (!$sessionToken && !$singleUseToken) {
        $next = getCurrentUrl();
        $secure = 1;
        $session = 1;
        $authSubHandler = 'https://www.google.com/h9/authsub';
        $permission = 1;
        // 1 - allows reading of the profile && posting notices
        $authSubURL = Zend_Gdata_AuthSub::getAuthSubTokenUri($next, SCOPE, $secure, $session, $authSubHandler);
        $authSubURL .= '&permission=' . $permission;
        echo '<a href="' . $authSubURL . '">Link your Google Health Account</a>';
        exit;
    }
    $client = new Zend_Gdata_HttpClient();
    $client->setAuthSubPrivateKeyFile(HEALTH_PRIVATE_KEY, null, true);
    // Convert an AuthSub one-time token into a session token if needed
    if ($singleUseToken && !$sessionToken) {
        $sessionToken = Zend_Gdata_AuthSub::getAuthSubSessionToken($singleUseToken, $client);
        $_SESSION['sessionToken'] = $sessionToken;
    }
    $client->setAuthSubToken($sessionToken);
    return $client;
}
Example #8
0
    public function getAuthSubHttpClient() {
        // Security check
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('IWagendas::', '::', ACCESS_READ));

        //global $_SESSION, $_GET, $_authSubKeyFile, $_authSubKeyFilePassphrase;
        $client = new Zend_Gdata_HttpClient();
        if ($_authSubKeyFile != null) {
            // set the AuthSub key
            $client->setAuthSubPrivateKeyFile($_authSubKeyFile, $_authSubKeyFilePassphrase, true);
        }
        if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
            $_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token'], $client);
        }
        $client->setAuthSubToken($_SESSION['sessionToken']);
        return $client;
    }
 /**
  * Returns a HTTP client object with the appropriate headers for communicating
  * with Google using AuthSub authentication.
  *
  * Uses the $_SESSION['sessionToken'] to store the AuthSub session token after
  * it is obtained.  The single use token supplied in the URL when redirected
  * after the user succesfully authenticated to Google is retrieved from the
  * $_GET['token'] variable.
  *
  * @return Zend_Http_Client
  */
 public function getAuthSubHttpClient()
 {
     global $_SESSION, $_GET, $_authSubKeyFile, $_authSubKeyFilePassphrase;
     $client = new Zend_Gdata_HttpClient();
     if ($_authSubKeyFile != null) {
         // set the AuthSub key
         $client->setAuthSubPrivateKeyFile($_authSubKeyFile, $_authSubKeyFilePassphrase, true);
     }
     if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
         $_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token'], $client);
     }
     $client->setAuthSubToken($_SESSION['sessionToken']);
     return $client;
 }
Example #10
0
 /**
  *
  * @return Bridge_Api_Youtube
  */
 protected function initialize_transport()
 {
     $http_client = new Zend_Gdata_HttpClient();
     $http_client->setHeaders('Accept', 'application/atom+xml');
     $this->_api = new Zend_Gdata_YouTube($http_client, Uuid::uuid4(), $this->conf->get(['main', 'bridge', 'youtube', 'client_id']), $this->conf->get(['main', 'bridge', 'youtube', 'developer_key']));
     $this->_api->setMajorProtocolVersion(2);
     return $this;
 }
Example #11
0
 private function getHttpClient($userEmail, $password, $proxyHost = null, $proxyPort = null, $tries = 3)
 {
     $authenticationURL = Zend_Gdata_YouTube::CLIENTLOGIN_URL;
     $service = Zend_Gdata_YouTube::AUTH_SERVICE_NAME;
     if (isset($userEmail) && isset($password)) {
         try {
             if (isset($proxyHost) && isset($proxyPort)) {
                 $httpConfig = array('adapter' => 'Zend_Gdata_HttpAdapterStreamingProxy', 'proxy_host' => $proxyHost, 'proxy_port' => $proxyPort, 'maxredirects' => 5, 'timeout' => 120, 'keepalive' => true);
                 //$httpConfig = array ('adapter' => 'Zend_Http_Client_Adapter_Proxy', 'proxy_host' => $proxy->proxy, 'proxy_port' => $proxy->port,'maxredirects' => 10, 'timeout' => 120, 'keepalive' => true );
                 try {
                     // creates a proxied client to use for authentication
                     $clientp = new Zend_Gdata_HttpClient($authenticationURL, $httpConfig);
                     // To turn cookie stickiness on, set a Cookie Jar
                     $clientp->setCookieJar();
                     // authenticate
                     //$httpClient = Zend_Gdata_ClientLogin::getHttpClient ( $userEmail, $password, $service, $clientp );
                     $httpClient = Zend_Gdata_ClientLogin::getHttpClient($userEmail, $password, $service, $clientp, 'WePromoteThis.com', null, null, $authenticationURL);
                     // set the proxy information back into the client
                     // necessary due to http://framework.zend.com/issues/browse/ZF-1920
                     $httpClient->setConfig($httpConfig);
                     //echo ("Using Proxy: $proxyHost port: $proxyPort<br>");
                 } catch (Zend_Gdata_App_HttpException $e) {
                     //var_dump ( $e );
                     //echo ("Error Using Proxy: $proxyHost  port: $proxyPort<br>" . $e->getMessage () . "<br>");
                     $httpClient = Zend_Gdata_ClientLogin::getHttpClient($userEmail, $password, $service, null, 'WePromoteThis.com', null, null, $authenticationURL);
                 }
             } else {
                 //echo ("Not Using Proxy");
                 $httpClient = Zend_Gdata_ClientLogin::getHttpClient($userEmail, $password, $service, null, 'WePromoteThis.com', null, null, $authenticationURL);
             }
         } catch (Exception $e) {
             //echo ("Error getting Youtube HttpClient: " . $e->getMessage () . "<br>");
             $this->httpException = $e->getMessage();
         }
     } else {
         //echo ("Credentials missing. Username: $userEmail | Password length: " . strlen ( $password ) . " <br>");
     }
     if (!isset($httpClient) && $tries > 0) {
         sleep(30);
         $httpClient = $this->getHttpClient($userEmail, $password, $proxyHost, $proxyPort, --$tries);
     }
     return $httpClient;
 }
Example #12
0
 public function testPrivateKeyNotFound()
 {
     $this->setExpectedException('Zend_Gdata_App_InvalidArgumentException');
     if (!extension_loaded('openssl')) {
         $this->markTestSkipped('The openssl extension is not available');
     } else {
         $c = new Zend_Gdata_HttpClient();
         $c->setAuthSubPrivateKeyFile("zendauthsubfilenotfound", null, true);
     }
 }
 /**
  * N.B.: A session token must be available before calling this method
  *
  * @return void
  */
 public function init()
 {
     if (!is_object($this->service)) {
         $pathToKey = sfConfig::get('sf_root_dir') . '/' . sfConfig::get('app_googleCalendarIntegration_privateKeyPath');
         $client = new Zend_Gdata_HttpClient();
         $client->setAuthSubPrivateKeyFile($pathToKey, null, true);
         $sessionToken = $this->getSessionToken();
         if (!$sessionToken) {
             throw new Exception("GoogleCalendarInterface: missing session token");
         }
         $client->setAuthSubToken($sessionToken);
         $this->service = new Zend_Gdata_Calendar($client, 'google-calendar-plancake-integration');
         $this->service->setMajorProtocolVersion(2);
         $this->service->setMinorProtocolVersion(null);
     }
 }
// if there is no AuthSub session or one-time token waiting for us,
// redirect the user to the AuthSub server to get one.
if (!isset($_GET['token'])) {
    // Parameters to give to AuthSub server
    $next = getCurrentUrl();
    $scope = GoogleCalendarInterface::GCAL_INTEGRATION_SCOPE;
    $secure = false;
    $session = true;
    // Redirect the user to the AuthSub server to sign in
    $authSubUrl = Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
    header("HTTP/1.0 307 Temporary redirect");
    header("Location: " . $authSubUrl);
    exit;
} else {
    try {
        $client = new Zend_Gdata_HttpClient();
        $pathToKey = sfConfig::get('sf_root_dir') . '/' . sfConfig::get('app_googleCalendarIntegration_privateKeyPath');
        $client->setAuthSubPrivateKeyFile($pathToKey, null, true);
        $sessionToken = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token'], $client);
    } catch (Exception $e) {
        sfErrorNotifier::alert("Google Calendar Init: " . $e->getMessage());
        $this->redirect('default', array('module' => 'googleCalendarIntegration', 'action' => 'step3Error'));
    }
    $redirectUrl = '';
    if ($sessionToken) {
        $loggedInUser = PcUserPeer::getLoggedInUser();
        if ($loggedInUser) {
            $googleCalendarInterface = new GoogleCalendarInterface($loggedInUser);
            $googleCalendarInterface->resetDbEntry();
            $googleCalendarInterface->setSessionToken($sessionToken);
        }
Example #15
0
 /**
  * Set Google authentication credentials.
  * Must be done before trying to do any Google Data operations that
  * require authentication.
  * For example, viewing private data, or posting or deleting entries.
  *
  * @param string $email
  * @param string $password
  * @param string $service
  * @param Zend_Gdata_HttpClient $client
  * @param string $source
  * @param string $loginToken The token identifier as provided by the server.
  * @param string $loginCaptcha The user's response to the CAPTCHA challenge.
  * @param string $accountType An optional string to identify whether the
  * account to be authenticated is a google or a hosted account. Defaults to
  * 'HOSTED_OR_GOOGLE'. See: http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#Request
  * @throws Zend_Gdata_App_AuthException
  * @throws Zend_Gdata_App_HttpException
  * @throws Zend_Gdata_App_CaptchaRequiredException
  * @return Zend_Gdata_HttpClient
  */
 public static function getHttpClient($email, $password, $service = 'xapi', $client = null, $source = self::DEFAULT_SOURCE, $loginToken = null, $loginCaptcha = null, $loginUri = self::CLIENTLOGIN_URI, $accountType = 'HOSTED_OR_GOOGLE')
 {
     if (!($email && $password)) {
         // require_once 'Zend/Gdata/App/AuthException.php';
         throw new Zend_Gdata_App_AuthException('Please set your Google credentials before trying to ' . 'authenticate');
     }
     if ($client == null) {
         $client = new Zend_Gdata_HttpClient();
     }
     if (!$client instanceof Zend_Http_Client) {
         // require_once 'Zend/Gdata/App/HttpException.php';
         throw new Zend_Gdata_App_HttpException('Client is not an instance of Zend_Http_Client.');
     }
     // Build the HTTP client for authentication
     $client->setUri($loginUri);
     $useragent = $source . ' Zend_Framework_Gdata/' . Zend_Version::VERSION;
     $client->setConfig(array('maxredirects' => 0, 'strictredirects' => true, 'useragent' => $useragent));
     $client->setParameterPost('accountType', $accountType);
     $client->setParameterPost('Email', (string) $email);
     $client->setParameterPost('Passwd', (string) $password);
     $client->setParameterPost('service', (string) $service);
     $client->setParameterPost('source', (string) $source);
     if ($loginToken || $loginCaptcha) {
         if ($loginToken && $loginCaptcha) {
             $client->setParameterPost('logintoken', (string) $loginToken);
             $client->setParameterPost('logincaptcha', (string) $loginCaptcha);
         } else {
             // require_once 'Zend/Gdata/App/AuthException.php';
             throw new Zend_Gdata_App_AuthException('Please provide both a token ID and a user\'s response ' . 'to the CAPTCHA challenge.');
         }
     }
     // Send the authentication request
     // For some reason Google's server causes an SSL error. We use the
     // output buffer to supress an error from being shown. Ugly - but works!
     ob_start();
     try {
         $response = $client->request('POST');
     } catch (Zend_Http_Client_Exception $e) {
         // require_once 'Zend/Gdata/App/HttpException.php';
         throw new Zend_Gdata_App_HttpException($e->getMessage(), $e);
     }
     ob_end_clean();
     // Parse Google's response
     $goog_resp = array();
     foreach (explode("\n", $response->getBody()) as $l) {
         $l = chop($l);
         if ($l) {
             list($key, $val) = explode('=', chop($l), 2);
             $goog_resp[$key] = $val;
         }
     }
     if ($response->getStatus() == 200) {
         $client->setClientLoginToken($goog_resp['Auth']);
         $useragent = $source . ' Zend_Framework_Gdata/' . Zend_Version::VERSION;
         $client->setConfig(array('strictredirects' => true, 'useragent' => $useragent));
         return $client;
     } elseif ($response->getStatus() == 403) {
         // Check if the server asked for a CAPTCHA
         if (array_key_exists('Error', $goog_resp) && $goog_resp['Error'] == 'CaptchaRequired') {
             // require_once 'Zend/Gdata/App/CaptchaRequiredException.php';
             throw new Zend_Gdata_App_CaptchaRequiredException($goog_resp['CaptchaToken'], $goog_resp['CaptchaUrl']);
         } else {
             // require_once 'Zend/Gdata/App/AuthException.php';
             throw new Zend_Gdata_App_AuthException('Authentication with Google failed. Reason: ' . (isset($goog_resp['Error']) ? $goog_resp['Error'] : 'Unspecified.'));
         }
     }
 }
Example #16
0
 /**
  * @expectedException Zend_Gdata_App_HttpException
  */
 public function testGetAuthSubTokenInfoCatchesHttpClientException()
 {
     $adapter = new Zend_Http_Client_Adapter_Test();
     $adapter->setNextRequestWillFail(true);
     $client = new Zend_Gdata_HttpClient();
     $client->setUri('http://example.com/AuthSub');
     $client->setAdapter($adapter);
     $revoked = Zend_Gdata_AuthSub::getAuthSubTokenInfo($this->token, $client);
 }
Example #17
0
        $query_params = substr($_SERVER['QUERY_STRING'], strlen('popup=true') + 1);
    }
    $_SESSION['redirect_to'] = "http://{$CONSUMER_KEY}{$_SERVER['PHP_SELF']}?{$query_params}";
    echo '<script type = "text/javascript">window.close();</script>';
    exit;
} else {
    if (isset($_SESSION['redirect_to'])) {
        $redirect = $_SESSION['redirect_to'];
        unset($_SESSION['redirect_to']);
        header('Location: ' . $redirect);
    }
}
$request_token = @$_REQUEST['openid_ext2_request_token'];
if ($request_token) {
    $data = array();
    $httpClient = new Zend_Gdata_HttpClient();
    $access_token = getAccessToken($request_token);
    // Query the Documents API ===================================================
    $feedUri = 'http://docs.google.com/feeds/documents/private/full';
    $params = array('max-results' => 50, 'strict' => 'true');
    $req = OAuthRequest::from_consumer_and_token($consumer, $access_token, 'GET', $feedUri, $params);
    $req->sign_request($sig_method, $consumer, $access_token);
    // Note: the Authorization header changes with each request
    $httpClient->setHeaders($req->to_header());
    $docsService = new Zend_Gdata_Docs($httpClient);
    $query = $feedUri . '?' . implode_assoc('=', '&', $params);
    $feed = $docsService->getDocumentListFeed($query);
    $data['docs']['html'] = listEntries($feed);
    $data['docs']['xml'] = $feed->saveXML();
    // ===========================================================================
    // Query the Spreadsheets API ================================================