Example #1
5
 function google()
 {
     $client = new Google_Client();
     $client->setApplicationName("snmmaurya");
     $client->setClientId(CLIENT_ID);
     $client->setClientSecret(CLIENT_SECRET);
     $client->setRedirectUri(REDIRECT_URI);
     $client->setApprovalPrompt(APPROVAL_PROMPT);
     $client->setAccessType(ACCESS_TYPE);
     $oauth2 = new Google_Oauth2Service($client);
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['token'] = $client->getAccessToken();
     }
     if (isset($_SESSION['token'])) {
         $client->setAccessToken($_SESSION['token']);
     }
     if (isset($_REQUEST['error'])) {
         echo '<script type="text/javascript">window.close();</script>';
         exit;
     }
     if ($client->getAccessToken()) {
         $user = $oauth2->userinfo->get();
         $_SESSION['User'] = $user;
         $_SESSION['token'] = $client->getAccessToken();
     } else {
         $authUrl = $client->createAuthUrl();
         header('Location: ' . $authUrl);
     }
 }
 /**
  * Returns an authorized API client.
  * @return Google_Client the authorized client object
  */
 private function getGoogleApiClient()
 {
     $client = new Google_Client();
     $client->setApplicationName($this->CFG['GOOGLE_API_APPLICATION_NAME']);
     $client->setScopes(Google_Service_Calendar::CALENDAR);
     $client->setAuthConfigFile($this->CFG['GOOGLE_API_CLIENT_SECRET_PATH']);
     $client->setAccessType('offline');
     // Load previously authorized credentials from a file.
     $credentialsPath = $this->CFG['GOOGLE_API_CREDENTIALS_PATH'];
     if (file_exists($credentialsPath)) {
         $accessToken = file_get_contents($credentialsPath);
     } else {
         // Request authorization from the user.
         $authUrl = $client->createAuthUrl();
         printf("Open the following link in your browser:\n%s\n", $authUrl);
         print 'Enter verification code: ';
         $authCode = trim(fgets(STDIN));
         // Exchange authorization code for an access token.
         $accessToken = $client->authenticate($authCode);
         // Store the credentials to disk.
         if (!file_exists(dirname($credentialsPath))) {
             mkdir(dirname($credentialsPath), 0700, true);
         }
         file_put_contents($credentialsPath, $accessToken);
         printf("Credentials saved to %s\n", $credentialsPath);
     }
     $client->setAccessToken($accessToken);
     // Refresh the token if it's expired.
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents($credentialsPath, $client->getAccessToken());
     }
     return $client;
 }
Example #3
2
 private function instantiateClient()
 {
     $this->client = new \Google_Client();
     $this->client->setApplicationName($this->config['applicationName']);
     $this->client->setAuthConfig($this->config['jsonFilePath']);
     $this->client->setScopes($this->config['scopes']);
 }
Example #4
1
 /**
  * @Route("/gatest2", name="front_ga2")
  *
  * @param Request $request
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function indexAction(Request $request)
 {
     $this->client = $this->get('GoogleClient');
     $this->client->setAuthConfig($this->getParameter('googleCredentialsFile'));
     $this->client->setApplicationName('Pingvin');
     $this->client->setScopes($this->getParameter('googleAnalyticsAuthUrl'));
     $this->analyticsService = $this->get('GoogleAnalyticsService');
     $accounts = $this->analyticsService->management_accounts->listManagementAccounts();
     $data = array();
     if (count($accounts->getItems()) > 0) {
         $items = $accounts->getItems();
         foreach ($items as $item) {
             $id = $item->getId();
             $properties = $this->analyticsService->management_webproperties->listManagementWebproperties($id);
             $items_e = $properties->getItems();
             foreach ($items_e as $item_e) {
                 $profiles = $this->analyticsService->management_profiles->listManagementProfiles($id, $item_e->getId());
                 $items_ee = $profiles->getItems();
                 foreach ($items_ee as $item_ee) {
                     $data[] = array($item_ee->getId(), $item_e->getId());
                 }
             }
         }
         var_dump('<pre>', $data);
     }
     return $this->render('CronBundle::message.html.twig', array('message' => '...'));
 }
 /**
  * @return \Google_Client
  */
 public function getClient()
 {
     if ($this->_client == null) {
         $this->_client = new Google_Client();
         $this->_client->setApplicationName($this->appName);
         $key = file_get_contents(Yii::getAlias($this->keyFile));
         $cred = new Google_Auth_AssertionCredentials($this->serviceAccountEmail, $this->scopes, $key);
         $this->_client->setAssertionCredentials($cred);
         if ($this->_client->getAuth()->isAccessTokenExpired()) {
             $this->_client->getAuth()->refreshTokenWithAssertion($cred);
         }
     }
     return $this->_client;
 }
 /**
  * Initialize the google calendar
  *
  * @throws \KevinDitscheid\KdCalendar\Exception\NoAuthDataException
  */
 public function initializeObject()
 {
     $this->settings = \KevinDitscheid\KdCalendar\Utility\ExtensionUtility::getMergedExtensionConfiguration();
     $this->client = new \Google_Client();
     $this->client->setApplicationName($this->settings['applicationName']);
     $this->client->setScopes(\Google_Service_Calendar::CALENDAR_READONLY);
     if ($this->settings['auth']['jsonFile']) {
         $this->client->setAuthConfigFile($this->settings['auth']['jsonFile']);
     } elseif ($this->settings['auth']['jsonString']) {
         $this->client->setAuthConfig($this->settings['auth']['jsonString']);
     } else {
         throw new \KevinDitscheid\KdCalendar\Exception\NoAuthDataException("No auth data is provided for Google Calendar!", 1454958940);
     }
     $this->client->setAccessType(self::ACCESS_TYPE_OFFLINE);
 }
Example #7
1
function gapps_service($domain)
{
    global $directory;
    $info = libraries_load('google-api-php-client');
    if (!$info['loaded']) {
        drupal_set_message(t('Can`t authenticate with google as library is missing check Status report or Readme for requirements, download from') . l('https://github.com/google/google-api-php-client/archive/master.zip', 'https://github.com/google/google-api-php-client/archive/master.zip'), 'error');
        return FALSE;
    }
    $client_email = variable_get('gapps_service_client_email');
    $file = file_load(variable_get('gapps_service_private_key'));
    $private_key = file_get_contents(drupal_realpath($file->uri));
    if ($domain == 'teacher') {
        $user_to_impersonate = variable_get('gapps_teacher_admin');
    } else {
        $user_to_impersonate = variable_get('gapps_student_admin');
    }
    $scopes = array('https://www.googleapis.com/auth/admin.directory.orgunit', 'https://www.googleapis.com/auth/admin.directory.group', 'https://www.googleapis.com/auth/admin.directory.group.member', 'https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.user.alias');
    $credentials = new Google_Auth_AssertionCredentials($client_email, $scopes, $private_key);
    $credentials->sub = $user_to_impersonate;
    $client = new Google_Client();
    $client->setApplicationName('Drupal gapps module');
    $client->setAssertionCredentials($credentials);
    while ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($credentials);
    }
    $directory = new Google_Service_Directory($client);
    $_SESSION['gapps_' . $domain . '_access_token'] = $client->getAccessToken();
    if ($_SESSION['gapps_' . $domain . '_access_token']) {
        return $directory;
    } else {
        return NULL;
    }
}
Example #8
1
 public function googleCallbackAction()
 {
     $response = array("status" => 0, "message" => "Thao tác không thành công");
     $code = $this->request->getPost("code", null, false);
     if ($code) {
         $google = new \Google_Client();
         $google->setApplicationName($this->config["GOOGLE_NAME"]);
         $google->setClientId($this->config["GOOGLE_ID"]);
         $google->setClientSecret($this->config["GOOGLE_SECRET"]);
         $google->setRedirectUri('postmessage');
         $scopes = array("https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email");
         $google->setScopes($scopes);
         $google->authenticate($code);
         $request = new \Google_Http_Request("https://www.googleapis.com/oauth2/v2/userinfo?alt=json");
         $userinfo = $google->getAuth()->authenticatedRequest($request);
         $response = $userinfo->getResponseBody();
         $userinfo = json_decode($response, true);
         $id = $userinfo["id"];
         $username = explode("@", $userinfo["email"]);
         $username = $username[0] . "_gg_" . $id;
         $data_user = array("email" => $userinfo["email"], "nickname" => $userinfo["name"], "username" => $username, "id" => $id);
         $response = $this->doSocialLogin($data_user);
     }
     echo json_encode($response);
     exit;
 }
 /**
  * @param   Entity\CloudCredentials $entity
  * @param   Entity\CloudCredentials $prevConfig
  *
  * @throws  ApiErrorException
  */
 public function validateEntity($entity, $prevConfig = null)
 {
     parent::validateEntity($entity, $prevConfig);
     $ccProps = $entity->properties;
     $prevCcProps = isset($prevConfig) ? $prevConfig->properties : null;
     if ($this->needValidation($ccProps, $prevCcProps)) {
         $ccProps[Entity\CloudCredentialsProperty::GCE_ACCESS_TOKEN] = "";
         try {
             $client = new \Google_Client();
             $client->setApplicationName("Scalr GCE");
             $client->setScopes(['https://www.googleapis.com/auth/compute']);
             $key = base64_decode($ccProps[Entity\CloudCredentialsProperty::GCE_KEY]);
             // If it's not a json key we need to convert PKCS12 to PEM
             if (!$ccProps[Entity\CloudCredentialsProperty::GCE_JSON_KEY]) {
                 @openssl_pkcs12_read($key, $certs, 'notasecret');
                 $key = $certs['pkey'];
             }
             $client->setAuthConfig(['type' => 'service_account', 'project_id' => $ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID], 'private_key' => $key, 'client_email' => $ccProps[Entity\CloudCredentialsProperty::GCE_SERVICE_ACCOUNT_NAME], 'client_id' => $ccProps[Entity\CloudCredentialsProperty::GCE_CLIENT_ID]]);
             $client->setClientId($ccProps[Entity\CloudCredentialsProperty::GCE_CLIENT_ID]);
             $gce = new \Google_Service_Compute($client);
             $gce->zones->listZones($ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID]);
         } catch (Exception $e) {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Provided GCE credentials are incorrect: ({$e->getMessage()})");
         }
         $entity->status = Entity\CloudCredentials::STATUS_ENABLED;
     }
 }
Example #10
1
 public function testSettersGetters()
 {
     $client = new Google_Client();
     $client->setClientId("client1");
     $client->setClientSecret('client1secret');
     $client->setState('1');
     $client->setApprovalPrompt('force');
     $client->setAccessType('offline');
     $client->setRedirectUri('localhost');
     $client->setApplicationName('me');
     $this->assertEquals('object', gettype($client->getAuth()));
     $this->assertEquals('object', gettype($client->getCache()));
     $this->assertEquals('object', gettype($client->getIo()));
     $client->setAuth(new Google_Auth_Simple($client));
     $client->setAuth(new Google_Auth_OAuth2($client));
     try {
         $client->setAccessToken(null);
         die('Should have thrown an Google_Auth_Exception.');
     } catch (Google_Auth_Exception $e) {
         $this->assertEquals('Could not json decode the token', $e->getMessage());
     }
     $token = json_encode(array('access_token' => 'token'));
     $client->setAccessToken($token);
     $this->assertEquals($token, $client->getAccessToken());
 }
function getService()
{
    // Creates and returns the Analytics service object.
    // Load the Google API PHP Client Library.
    require_once 'vendor/autoload.php';
    // Use the developers console and replace the values with your
    // service account email, and relative location of your key file.
    //Charlie's email
    // $service_account_email = '*****@*****.**';
    //My email
    $service_account_email = '*****@*****.**';
    $key_file_location = 'client_secrets.p12';
    // Create and configure a new client object.
    $client = new Google_Client();
    $client->setApplicationName("HelloAnalytics");
    $analytics = new Google_Service_Analytics($client);
    // Read the generated client_secrets.p12 key.
    $key = file_get_contents($key_file_location);
    $cred = new Google_Auth_AssertionCredentials($service_account_email, array(Google_Service_Analytics::ANALYTICS_READONLY), $key);
    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    return $analytics;
}
Example #12
0
 /**
  * Create a new Google  instance.
  *
  * @param array $config
  *
  * @return void
  */
 public function __construct(array $config)
 {
     $this->config = $config;
     $this->client = new \Google_Client();
     $this->client->setApplicationName("Tag media Mrs");
     $this->client->setDeveloperKey($config['developer_key']);
 }
 function __construct($API_SERVER_TOKEN)
 {
     $this->apiClient = new \Google_Client();
     $this->apiClient->setApplicationName("EHF-YouTube-Playlist");
     $this->apiClient->setDeveloperKey($API_SERVER_TOKEN);
     $this->apiService = new \Google_Service_YouTube($this->apiClient);
 }
Example #14
0
 /**
  * Google constructor.
  */
 public function __construct()
 {
     $this->_googleClient = new \Google_Client();
     $this->_googleClient->setClientId(KACANA_SOCIAL_GOOGLE_KEY);
     $this->_googleClient->setClientSecret(KACANA_SOCIAL_GOOGLE_SECRET);
     $this->_googleClient->setApplicationName(KACANA_SOCIAL_GOOGLE_APP_NAME);
     $this->_googleClient->setRedirectUri('postmessage');
 }
Example #15
0
 public function __construct(ContainerInterface $container, $api_key, $project_name)
 {
     $this->service_container = $container;
     $this->client = new \Google_Client();
     $this->client->setApplicationName($project_name);
     $this->client->setDeveloperKey($api_key);
     $this->searcher = new \Google_Service_Books($this->client);
 }
 /**
  * GoogleServiceProvider constructor.
  * @param $config
  */
 public function __construct()
 {
     $this->client = new \Google_Client();
     $this->projectName = config('google_cloud_storage.application');
     $this->projectBucket = config('google_cloud_storage.bucket');
     $this->authJsonFile = config('google_cloud_storage.auth_json_filename');
     $this->client->setApplicationName($this->projectName);
     $this->client->setAuthConfigFile(base_path($this->authJsonFile));
     $this->client->addScope(\Google_Service_Storage::DEVSTORAGE_FULL_CONTROL);
 }
 /**
  * GoogleServiceProvider constructor.
  * @param $config
  */
 public function __construct()
 {
     $this->client = new \Google_Client();
     $this->projectName = config('google_pub_sub.application');
     $this->authJsonFile = config('google_pub_sub.auth_json_filename');
     $this->client->setApplicationName($this->projectName);
     $this->client->setAuthConfigFile(base_path($this->authJsonFile));
     //THIS IS NEEDED FOR CHROME ENV
     //$this->client->useApplicationDefaultCredentials();
     $this->client->addScope(Google_Service_Pubsub::PUBSUB);
 }
Example #18
0
 public function initializeClient()
 {
     $this->client = new Client();
     $this->client->setAccessType('offline');
     $this->client->setApplicationName('playlister');
     $this->client->setClientId($this->config->get('services.youtube.client_id'));
     $this->client->setClientSecret($this->config->get('services.youtube.client_secret'));
     $this->client->setRedirectUri($this->config->get('services.youtube.redirect'));
     $this->client->setDeveloperKey($this->config->get('services.youtube.api_key'));
     $this->client->addScope('https://www.googleapis.com/auth/youtube.readonly');
     if ($this->auth->check() && $this->request->session()->has('user.token')) {
         $this->setToken($this->request->session()->get('user.token'));
     }
 }
Example #19
0
function do_something_with_user($email)
{
    global $key;
    $user_client = new Google_Client();
    $user_client->setApplicationName("Google+ Domains API Sample");
    $user_credentials = new Google_AssertionCredentials(SERVICE_ACCOUNT_EMAIL, array("https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/plus.stream.read"), $key);
    // Set the API Client to act on behalf of the specified user
    $user_credentials->sub = $email;
    $user_client->setAssertionCredentials($user_credentials);
    $user_client->setClientId(CLIENT_ID);
    $plusService = new Google_PlusService($user_client);
    // Try to retrieve Google+ Profile information about the current user
    try {
        $result = $plusService->people->get("me");
    } catch (Exception $e) {
        printf("        / Not a Google+ User<br><br>\n");
        return;
    }
    printf("        / <a href=\"%s\">Google+ Profile</a>\n", $result["url"]);
    // Retrieve a list of Google+ activities for the current user
    $activities = $plusService->activities->listActivities("me", "user", array("maxResults" => 100));
    if (isset($activities["items"])) {
        printf("        / %s activities found<br><br>\n", count($activities["items"]));
    } else {
        printf("        / No activities found<br><br>\n");
    }
}
/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    global $credentialsPath;
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(GAPI_SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');


    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        die("Please, get token via connect.php");
    }

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client = refreshToken($client);
    }

    return $client;
}
Example #21
0
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET);
    $client->setAccessType('offline');
    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory(CREDENTIAL_PATH);
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n\n\t%s\n\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));
        // Exchange authorization code for an access token.
        $accessToken = $client->authenticate($authCode);
        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);
    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
    }
    return $client;
}
Example #22
0
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName(getGAAppName());
    $client->setClientId(getGAClientID());
    return $client;
}
 public function __construct()
 {
     $config_file = $_SERVER['HOME'] . '/' . self::CONFIG_FILE_NAME;
     if (file_exists($config_file)) {
         $config = json_decode(file_get_contents($config_file));
     }
     if (!$config) {
         throw new Exception(sprintf('Could not find or read the config file at ' . '%s. You can use the config.json file in the samples root as a ' . 'template.', $config_file));
     }
     $client = new Google_Client();
     $client->setApplicationName($config->applicationName);
     $client->setClientId($config->clientId);
     $client->setClientSecret($config->clientSecret);
     try {
         $client->refreshToken($config->refreshToken);
     } catch (Google_Auth_Exception $exception) {
         print str_repeat('*', 40);
         print "Your refresh token was missing or invalid, fetching a new one\n";
         $refresh_token = $this->getRefreshToken($client);
         $config->refreshToken = $refresh_token;
         file_put_contents($config_file, json_encode($config));
         print "Refresh token saved to your config file\n";
         print str_repeat('*', 40);
     }
     $this->merchant_id = $config->merchantId;
     $this->service = new Google_Service_ShoppingContent($client);
 }
 /**
  * @return object | $service | Google Analytics Service Object used to run queries 
  **/
 private function createAnalyticsService()
 {
     /** 
      * Create and Authenticate Google Analytics Service Object
      **/
     $client = new Google_Client();
     $client->setApplicationName(GOOGLE_API_APP_NAME);
     /**
      * Makes sure Private Key File exists and is readable. If you get an error, check path in apiConfig.php
      **/
     if (!file_exists(GOOGLE_API_PRIVATE_KEY_FILE)) {
         array_push($GLOBALS['criticalErrors'], "CRITICAL-ERROR: Unable to find GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE);
         criticalErrorOccurred($criticalErrors, $errors);
         exit("CRITICAL-ERROR: Unable to find GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE . ' Backup aborted.');
     } elseif (!is_readable(GOOGLE_API_PRIVATE_KEY_FILE)) {
         array_push($GLOBALS['criticalErrors'], "CRITICAL-ERROR: Unable to read GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE);
         criticalErrorOccurred($criticalErrors, $errors);
         exit("CRITICAL-ERROR: Unable to read GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE . ' Backup aborted.');
     }
     $client->setAssertionCredentials(new Google_AssertionCredentials(GOOGLE_API_SERVICE_EMAIL, array('https://www.googleapis.com/auth/analytics.readonly'), file_get_contents(GOOGLE_API_PRIVATE_KEY_FILE)));
     $client->setClientId(GOOGLE_API_SERVICE_CLIENT_ID);
     $client->setUseObjects(true);
     $service = new Google_AnalyticsService($client);
     return $service;
 }
Example #25
0
function getClient()
{
    $config = (include __DIR__ . '/ini.php');
    $client = new Google_Client();
    $client->setApplicationName("Webkameleon");
    $client->setClientId($config['oauth2_client_id']);
    $client->setClientSecret($config['oauth2_client_secret']);
    $client->setRedirectUri($config['oauth2_redirect_uri']);
    $client->setScopes($config['oauth2_scopes']);
    $client->setState('offline');
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        die($client->getAccessToken());
    } elseif (!isset($config['token'])) {
        Header('Location: ' . $client->createAuthUrl());
    } else {
        $client->setAccessToken($config['token']);
        if ($client->isAccessTokenExpired()) {
            $token = json_decode($config['token'], true);
            $client->refreshToken($token['refresh_token']);
        }
    }
    return $client;
}
 private function createClient()
 {
     $options = ['auth' => 'google_auth', 'exceptions' => false];
     if ($proxy = getenv('HTTP_PROXY')) {
         $options['proxy'] = $proxy;
         $options['verify'] = false;
     }
     // adjust constructor depending on guzzle version
     if (!$this->isGuzzle6()) {
         $options = ['defaults' => $options];
     }
     $httpClient = new GuzzleHttp\Client($options);
     $client = new Google_Client();
     $client->setApplicationName('google-api-php-client-tests');
     $client->setHttpClient($httpClient);
     $client->setScopes(["https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/urlshortener", "https://www.googleapis.com/auth/tasks", "https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/drive"]);
     if ($this->key) {
         $client->setDeveloperKey($this->key);
     }
     list($clientId, $clientSecret) = $this->getClientIdAndSecret();
     $client->setClientId($clientId);
     $client->setClientSecret($clientSecret);
     $client->setCache($this->getCache());
     return $client;
 }
Example #27
0
 function authorizeGoogleUser($access_code)
 {
     $client = new \Google_Client();
     $google = $this->config->google;
     $client->setApplicationName('Portal da Rede');
     $client->setClientId($google->clientId);
     $client->setClientSecret($google->secret);
     $client->setRedirectUri('postmessage');
     $client->addScope('https://www.googleapis.com/auth/userinfo.profile');
     $client->addScope('https://www.googleapis.com/auth/userinfo.email');
     $client->authenticate($access_code);
     $json_token = $client->getAccessToken();
     $client->setAccessToken($json_token);
     $plus = new \Google_Service_Plus($client);
     $user = $plus->people->get('me');
     if (!$user->emails || !is_array($user->emails)) {
         return;
     }
     $email = $user->emails[0]['value'];
     $user_email = $this->db->user_email->find_one($email);
     if (!$user_email) {
         return;
     }
     $this->login($user_email->user);
 }
 public static function revokeAccessToken()
 {
     $xmpData = erLhcoreClassModelChatConfig::fetch('xmp_data');
     $data = (array) $xmpData->data;
     try {
         if (isset($data['gtalk_client_token']) && $data['gtalk_client_token'] != '') {
             require_once 'lib/core/lhxmp/google/Google_Client.php';
             $client = new Google_Client();
             $client->setApplicationName('Live Helper Chat');
             $client->setScopes(array("https://www.googleapis.com/auth/googletalk", "https://www.googleapis.com/auth/userinfo.email"));
             $client->setClientId($data['gtalk_client_id']);
             $client->setClientSecret($data['gtalk_client_secret']);
             $client->setAccessType('offline');
             $client->setApprovalPrompt('force');
             $token = $data['gtalk_client_token'];
             $client->setAccessToken($data['gtalk_client_token']);
             // Refresh token if it's
             if ($client->isAccessTokenExpired()) {
                 $tokenData = json_decode($token);
                 $client->refreshToken($tokenData->refresh_token);
                 $accessToken = $client->getAccessToken();
             }
             if ($accessToken = $client->getAccessToken()) {
                 $client->revokeToken();
             }
             unset($data['gtalk_client_token']);
             $xmpData->value = serialize($data);
             $xmpData->saveThis();
         }
         return true;
     } catch (Exception $e) {
         throw $e;
     }
 }
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');
    $credentialsPath = CREDENTIALS_PATH;
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));
        $accessToken = $client->authenticate($authCode);
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);
    if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
    }
    return $client;
}
Example #30
0
 /**
  * Login to facebook and get the associated cloudrexx user.
  */
 public function login()
 {
     $client = new \Google_Client();
     $client->setApplicationName('Contrexx Login');
     $client->setClientId($this->applicationData[0]);
     $client->setClientSecret($this->applicationData[1]);
     $client->setRedirectUri(\Cx\Lib\SocialLogin::getLoginUrl(self::OAUTH_PROVIDER));
     $client->setDeveloperKey($this->applicationData[2]);
     $client->setUseObjects(true);
     $client->setApprovalPrompt('auto');
     $client->setScopes(self::$scopes);
     self::$google = new \Google_Oauth2Service($client);
     self::$googleplus = new \Google_PlusService($client);
     if (isset($_GET['code'])) {
         try {
             $client->authenticate();
         } catch (\Google_AuthException $e) {
         }
     }
     if (!$client->getAccessToken()) {
         \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . $client->createAuthUrl());
         exit;
     }
     self::$userdata = $this->getUserData();
     $this->getContrexxUser(self::$userdata['oauth_id']);
 }