Пример #1
0
 /**
  * Retrieve a new access token and store it in cache
  * @param mixed $scopes
  * @param string $cacheKey
  */
 private function retrieveToken($scopes, $cacheKey)
 {
     $this->token = AppIdentityService::getAccessToken($scopes);
     if ($this->token) {
         $this->client->getCache()->set($cacheKey, $this->token);
     }
 }
 public function testReturnsExpectedToken()
 {
     // include the mock AppIdentityService class
     require_once __DIR__ . '/../mocks/AppIdentityService.php';
     $wantedToken = ['access_token' => '1/abdef1234567890', 'expires_in' => '57', 'token_type' => 'Bearer'];
     AppIdentityService::$accessToken = $wantedToken;
     $_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
     $g = new AppIdentityCredentials();
     $this->assertEquals($wantedToken, $g->fetchAuthToken());
 }
Пример #3
0
 /**
  * Send an email.
  *
  * This is a re-implementation of PHP's mail() function using App Engine
  * mail API. The function relies on mailparse extension to parse emails.
  *
  * @param string $to Receiver, or receivers of the mail.
  * @param string $subject Subject of the email to be sent.
  * @param string $message Message to be sent.
  * @param string $additional_headers optional
  *   String to be inserted at the end of the email header.
  * @param string $additional_parameters optional
  *   Additional flags to be passed to the mail program. This arugment is
  *   added only to match the signature of PHP's mail() function. The value is
  *   always ignored.
  * @return bool
  *   TRUE if the message is sent successfully, otherwise return FALSE.
  *
  * @see http://php.net/mail
  */
 public static function sendMail($to, $subject, $message, $additional_headers = null, $additional_parameters = null)
 {
     $raw_mail = "To: {$to}\r\nSubject: {$subject}\r\n";
     if ($additional_headers != null) {
         $raw_mail .= trim($additional_headers);
     }
     $raw_mail .= "\r\n\r\n{$message}";
     $mime = mailparse_msg_create();
     mailparse_msg_parse($mime, $raw_mail);
     $root_part = mailparse_msg_get_part_data($mime);
     // Set sender address based on the following order
     // 1. "From" header in $additional_headers
     // 2. "sendmail_from" ini setting
     // 3. Default address "mailer@<app-id>.appspotmail.com
     $from = ini_get('sendmail_from');
     if (isset($root_part['headers']['from'])) {
         $from = $root_part['headers']['from'];
     }
     if ($from === false || $from == "") {
         $from = sprintf(self::DEFAULT_SENDER_ADDRESS_FORMAT, AppIdentityService::getApplicationId());
         syslog(LOG_WARNING, "mail(): Unable to determine sender's email address from the " . "'sendmail_from' directive in php.ini or from the 'From' " . "header. Falling back to the default {$from}.");
     }
     $email = new Message();
     try {
         $email->setSender($from);
         $email->addTo($root_part['headers']['to']);
         if (isset($root_part['headers']['cc'])) {
             $email->AddCc($root_part['headers']['cc']);
         }
         if (isset($root_part['headers']['bcc'])) {
             $email->AddBcc($root_part['headers']['bcc']);
         }
         $email->setSubject($root_part['headers']['subject']);
         $parts = mailparse_msg_get_structure($mime);
         if (count($parts) > 1) {
             foreach ($parts as $part_id) {
                 $part = mailparse_msg_get_part($mime, $part_id);
                 self::parseMimePart($part, $raw_mail, $email);
             }
         } else {
             if ($root_part['content-type'] == 'text/plain') {
                 $email->setTextBody($message);
             } else {
                 if ($root_part['content-type'] == 'text/html') {
                     $email->setHtmlBody($message);
                 }
             }
         }
         $email->send();
     } catch (\Exception $e) {
         trigger_error('mail(): ' . $e->getMessage(), E_USER_WARNING);
         return false;
     }
     return true;
 }
Пример #4
0
 /**
  * Retrieve an access token for the scopes supplied.
  */
 public function authenticateForScope($scopes)
 {
     if ($this->token && $this->tokenScopes == $scopes) {
         return $this->token;
     }
     $memcache = new Memcached();
     $this->token = $memcache->get(self::CACHE_PREFIX . $scopes);
     if (!$this->token) {
         $this->token = AppIdentityService::getAccessToken($scopes);
         if ($this->token) {
             $memcache->set(self::CACHE_PREFIX . $scopes, $this->token, self::CACHE_LIFETIME);
         }
     }
     $this->tokenScopes = $scopes;
     return $this->token;
 }
Пример #5
0
 /**
  * Retrieve an access token for the scopes supplied.
  */
 public function authenticateForScope($scopes)
 {
     if ($this->token && $this->tokenScopes == $scopes) {
         return $this->token;
     }
     $cacheKey = self::CACHE_PREFIX;
     if (is_string($scopes)) {
         $cacheKey .= $scopes;
     } else {
         if (is_array($scopes)) {
             $cacheKey .= implode(":", $scopes);
         }
     }
     $this->token = $this->client->getCache()->get($cacheKey);
     if (!$this->token) {
         $this->token = AppIdentityService::getAccessToken($scopes);
         if ($this->token) {
             $this->client->getCache()->set($cacheKey, $this->token);
         }
     }
     $this->tokenScopes = $scopes;
     return $this->token;
 }
Пример #6
0
 /**
  * Retrieve an access token for the scopes supplied.
  */
 public function authenticateForScope($scopes)
 {
     if ($this->token && $this->tokenScopes == $scopes) {
         return $this->token;
     }
     $memcache = new Memcached();
     $this->token = $memcache->get(self::CACHE_PREFIX . $scopes);
     if (!$this->token) {
         $this->token = AppIdentityService::getAccessToken($scopes);
         if ($this->token) {
             $memcache_key = self::CACHE_PREFIX;
             if (is_string($scopes)) {
                 $memcache_key .= $scopes;
             } else {
                 if (is_array($scopes)) {
                     $memcache_key .= implode(":", $scopes);
                 }
             }
             $memcache->set($memcache_key, $this->token, self::CACHE_LIFETIME);
         }
     }
     $this->tokenScopes = $scopes;
     return $this->token;
 }
Пример #7
0
 private static function sign_auth_key($auth_key)
 {
     if (self::is_production()) {
         return AppIdentityService::signForApp($auth_key);
     } else {
         // In the development server we are not concerned with trying to generate
         // a secure signature.
         return ['key_name' => 'development_hash', 'signature' => sha1($auth_key)];
     }
 }
 /**
  * Get the OAuth Token HTTP header for the supplied scope.
  *
  * @param $scopes mixed The scopes to acquire the token for.
  *
  * @return array The HTTP authorization header for the scopes, using the
  * applications service account. False if the call failed.
  */
 protected function getOAuthTokenHeader($scopes)
 {
     if ($this->anonymous) {
         return [];
     }
     try {
         $token = AppIdentityService::getAccessToken($scopes);
         return ["Authorization" => sprintf(self::OAUTH_TOKEN_FORMAT, $token['access_token'])];
     } catch (AppIdentityException $e) {
         return false;
     }
 }
 /**
  * Implements FetchAuthTokenInterface#fetchAuthToken.
  *
  * Fetches the auth tokens using the AppIdentityService if available.
  * As the AppIdentityService uses protobufs to fetch the access token,
  * the GuzzleHttp\ClientInterface instance passed in will not be used.
  *
  * @param callable $httpHandler callback which delivers psr7 request
  * @return array the auth metadata:
  *  array(2) {
  *   ["access_token"]=>
  *   string(3) "xyz"
  *   ["expiration_time"]=>
  *   string(10) "1444339905"
  *  }
  */
 public function fetchAuthToken(callable $httpHandler = null)
 {
     if (!self::onAppEngine()) {
         return array();
     }
     if (!class_exists('google\\appengine\\api\\app_identity\\AppIdentityService')) {
         throw new \Exception('This class must be run in App Engine, or you must include the AppIdentityService ' . 'mock class defined in tests/mocks/AppIdentityService.php');
     }
     // AppIdentityService expects an array when multiple scopes are supplied
     $scope = is_array($this->scope) ? $this->scope : explode(' ', $this->scope);
     $token = AppIdentityService::getAccessToken($scope);
     return $token;
 }
Пример #10
0
 function gethostname()
 {
     return AppIdentityService::getApplicationId();
 }
Пример #11
0
 public function testGetDefaultVersionHostname()
 {
     putenv("DEFAULT_VERSION_HOSTNAME=my-app.appspot.com");
     $this->assertEquals("my-app.appspot.com", AppIdentityService::getDefaultVersionHostname());
 }
 /**
  * Get an OAuth2 access token for the applications service account without
  * caching the result. Usually getAccessToken($scopes) should be used instead
  * which calls this method and caches the result in memcache.
  *
  * @param array $scopes The scopes to acquire the access token for.
  * Can be either a single string or an array of strings.
  *
  * @throws InvalidArgumentException If $scopes is not a string or an array of
  * strings.
  * @throws AppIdentityException If there is an error using the AppIdentity
  * service.
  *
  * @return array An array with the following key/value pairs.
  * 'access_token' - The access token for the application.
  * 'expiration_time' - The expiration time for the access token.
  */
 private static function getAccessTokenUncached($scopes)
 {
     $req = new GetAccessTokenRequest();
     $resp = new GetAccessTokenResponse();
     if (is_string($scopes)) {
         $req->addScope($scopes);
     } else {
         if (is_array($scopes)) {
             foreach ($scopes as $scope) {
                 if (is_string($scope)) {
                     $req->addScope($scope);
                 } else {
                     throw new \InvalidArgumentException('Invalid scope ' . $scope);
                 }
             }
         } else {
             throw new \InvalidArgumentException('Invalid scope ' . $scopes);
         }
     }
     try {
         ApiProxy::makeSyncCall(self::PACKAGE_NAME, 'GetAccessToken', $req, $resp);
     } catch (ApplicationError $e) {
         throw AppIdentityService::applicationErrorToException($e);
     }
     return ['access_token' => $resp->getAccessToken(), 'expiration_time' => $resp->getExpirationTime()];
 }
Пример #13
0
 private function executeServiceErrorTest($error, $expected_response)
 {
     $req = new \google\appengine\GetAccessTokenRequest();
     $scope = 'mail.google.com/invalid-scope';
     $req->addScope($scope);
     $exception = new \google\appengine\runtime\ApplicationError($error, "not initialized");
     $this->setExpectedException('\\google\\appengine\\api\\app_identity\\AppIdentityException', $expected_response);
     self::expectGetAccessTokenRequest(array($scope), false, $exception);
     $result = AppIdentityService::getAccessToken($scope);
 }
Пример #14
0
 protected function callNotifier($endpoint, $params)
 {
     $credentials = file_get_contents(storage_path('notifier.json'));
     $credentials = json_decode($credentials);
     $auth = sprintf('%s:%s', $credentials->username, $credentials->password);
     $headers = [sprintf('Authorization: Basic %s', base64_encode($auth)), 'Content-type: application/x-www-form-urlencoded', sprintf('User-Agent: %s', AppIdentityService::getApplicationId())];
     $contextParams = ['http' => ['method' => 'POST', 'header' => implode("\r\n", $headers) . "\r\n", 'content' => http_build_query($params)]];
     $context = stream_context_create($contextParams);
     $response = file_get_contents($credentials->url . $endpoint, false, $context);
     //syslog(LOG_DEBUG, print_r($contextParams, true));
     //syslog(LOG_DEBUG, print_r($http_response_header, true));
     return $response;
 }
Пример #15
0
 /**
  * Get the default email address for App Engine
  *
  * @param string $user User part of the email address (typically 'wordpress')
  * @return string Email address with the correct email domain
  */
 function get_default_email($user = '******')
 {
     // Let's build an email address for the app via the app identity api
     $service_account = new AppIdentityService();
     $id = $service_account->getApplicationId();
     if (empty($id)) {
         $service_account_name = $service_account->getServiceAccountName();
         $service_account_from_name = explode('@', $service_account_name);
         $id = $service_account_from_name[0];
     }
     return $user . '@' . $id . '.appspotmail.com';
 }