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;
 }
 public function refreshToken($accessToken)
 {
     $this->_googleClient->setAccessToken($accessToken);
     // Refresh the token if it's expired.
     if ($this->_googleClient->isAccessTokenExpired()) {
         $this->_googleClient->refreshToken($this->_googleClient->getRefreshToken());
     }
     return $this->_googleClient->getAccessToken();
 }
 public function signin()
 {
     $client = new \Google_Client();
     $client->setClientId(Config::get('ntentan:social.google.client_id'));
     $client->setClientSecret(Config::get('ntentan:social.google.client_secret'));
     $client->setRedirectUri(Config::get('ntentan:social.google.redirect_uri'));
     $client->addScope(array('profile', 'email'));
     $oauth2 = new \Google_Service_Oauth2($client);
     if (isset($_REQUEST['logout'])) {
         Session::set('access_token', '');
         $client->revokeToken();
     }
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         Session::set('access_token', $client->getAccessToken());
         Redirect::path(\ntentan\Router::getRoute());
     }
     if (isset($_SESSION['access_token'])) {
         $client->setAccessToken($_SESSION['access_token']);
     }
     if ($client->isAccessTokenExpired()) {
         $authUrl = $client->createAuthUrl();
         header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
     }
     if ($client->getAccessToken()) {
         $user = $oauth2->userinfo->get();
         $_SESSION['token'] = $client->getAccessToken();
         return array('firstname' => $user['given_name'], 'lastname' => $user['family_name'], 'key' => "google_{$user['id']}", 'avatar' => $user['picture'], 'email' => $user['email'], 'email_confirmed' => $user['verified_email']);
     } else {
         header("Location: {$client->createAuthUrl()}");
         die;
     }
     return false;
 }
Example #5
1
 public function add_google_client()
 {
     $auth_config = $this->get_auth_config();
     if (!empty($auth_config)) {
         try {
             $client = new Google_Client();
             $client->setAuthConfig($this->get_auth_config());
             $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
             $client->setAccessType('offline');
             $token = $this->get_token();
             if ($token) {
                 $client->setAccessToken($token);
             }
             if ($client->isAccessTokenExpired()) {
                 $refresh_token = $this->get_refresh_token();
                 if ($refresh_token) {
                     $client->refreshToken($refresh_token);
                     $this->update_token($client->getAccessToken());
                 }
             }
             $this->client = $client;
             $this->service = new Google_Service_Analytics($this->client);
         } catch (Exception $e) {
             $message = 'Google Analytics Error[' . $e->getCode() . ']: ' . $e->getMessage();
             $this->disconnect($message);
             error_log($message, E_USER_ERROR);
             return;
         }
     }
 }
Example #6
0
 /**
  * Retrieves an access token from the storage object and sets it into the
  * client object.
  */
 public function setTokenFromStorage()
 {
     $accessToken = $this->storage->get();
     if (isset($accessToken)) {
         $this->client->setAccessToken($accessToken);
     }
 }
 /**
  * @param ContainerInterface  $container
  * @param TranslatorInterface $translator
  * @param LoggerInterface     $logger
  *
  * @throws InvalidConfigurationException
  */
 public function __construct(ContainerInterface $container, TranslatorInterface $translator, LoggerInterface $logger)
 {
     $this->container = $container;
     // Check if we have the API key
     $rootDir = $this->container->getParameter('kernel.root_dir');
     $configDir = $rootDir . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR;
     $apiKeyFile = $configDir . $this->container->getParameter('dms.service_account_key_file');
     if (!file_exists($apiKeyFile)) {
         throw new InvalidConfigurationException('Store your Google API key in ' . $apiKeyFile . ' - see https://code.google.com/apis/console');
     }
     // Perform API authentication
     $apiKeyFileContents = file_get_contents($apiKeyFile);
     $serviceAccountEmail = $this->container->getParameter('dms.service_account_email');
     $auth = new \Google_Auth_AssertionCredentials($serviceAccountEmail, array('https://www.googleapis.com/auth/drive'), $apiKeyFileContents);
     $this->client = new \Google_Client();
     if (isset($_SESSION['service_token'])) {
         $this->client->setAccessToken($_SESSION['service_token']);
     }
     $this->client->setAssertionCredentials($auth);
     /*
     if ($this->client->getAuth()->isAccessTokenExpired()) {
         $this->client->getAuth()->refreshTokenWithAssertion($auth);
     }
     */
     $this->translator = $translator;
     $this->logger = $logger;
     $this->service = new \Google_Service_Drive($this->client);
 }
Example #8
0
 public function testSettersGetters()
 {
     $client = new Google_Client();
     $client->setClientId("client1");
     $client->setClientSecret('client1secret');
     $client->setState('1');
     $client->setApprovalPrompt('force');
     $client->setAccessType('offline');
     global $apiConfig;
     $this->assertEquals('client1', $apiConfig['oauth2_client_id']);
     $this->assertEquals('client1secret', $apiConfig['oauth2_client_secret']);
     $client->setRedirectUri('localhost');
     $client->setApplicationName('me');
     $client->setUseObjects(false);
     $this->assertEquals('object', gettype($client->getAuth()));
     $this->assertEquals('object', gettype($client->getCache()));
     $this->assertEquals('object', gettype($client->getIo()));
     $client->setAuthClass('Google_AuthNone');
     $client->setAuthClass('Google_OAuth2');
     try {
         $client->setAccessToken(null);
         die('Should have thrown an Google_AuthException.');
     } catch (Google_AuthException $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());
 }
Example #9
0
 public function shorten($longUrl)
 {
     $this->_googleClient->setAccessToken(json_encode(["access_token" => 'ya29.Ci-nA63j_-YJy7-M4u0F490pttfSg-Gka2xLyDzaqmfWgDCMXLVsisYGoGLmqT55Vg']));
     $service = new \Google_Service_Urlshortener($this->_googleClient);
     $url = new \Google_Service_Urlshortener_Url();
     $url->longUrl = $longUrl;
     print_r($service->url->insert($url));
     die;
     return $service->url->insert($url);
 }
 /**
  * @param string $accessToken The token
  */
 public function setAccessToken($accessToken)
 {
     if (is_null($accessToken)) {
         $this->token = null;
     } else {
         $token = array('access_token' => $accessToken);
         $this->token = json_encode($token);
     }
     $this->client->setAccessToken($this->token);
 }
Example #11
0
 /**
  * @return string
  */
 public function isLoggedIn()
 {
     if (\Session::has('token')) {
         $this->client->setAccessToken(\Session::get('token'));
     } else {
         return false;
     }
     if ($this->client->isAccessTokenExpired()) {
         \Session::set('token', $this->client->getRefreshToken());
     }
     return !$this->client->isAccessTokenExpired();
 }
Example #12
0
 public function __construct()
 {
     parent::__construct();
     if (!BaseTest::$client) {
         global $apiConfig;
         $apiConfig['ioFileCache_directory'] = '/tmp/google-api-php-client/tests';
         BaseTest::$client = new Google_Client();
         if (!BaseTest::$client->getAccessToken()) {
             BaseTest::$client->setAccessToken($apiConfig['oauth_test_token']);
         }
     }
 }
Example #13
0
 /**
  * Auth over command line
  */
 public function cmdLineAuth()
 {
     $authUrl = $this->client->createAuthUrl();
     //Request authorization
     print "Please visit:\n{$authUrl}\n\n";
     print "Please enter the auth code:\n";
     $authCode = trim(fgets(STDIN));
     // Exchange authorization code for access token
     $accessToken = $this->client->authenticate($authCode);
     $this->client->setAccessToken($accessToken);
     $this->accessToken = $accessToken;
     $this->refreshToken = $this->client->getRefreshToken();
 }
 /**
  * Return Google Content Client Instance
  *
  * @param int  $storeId
  * @param bool $noAuthRedirect
  *
  * @return bool|Google_Client
  */
 public function getClient($storeId, $noAuthRedirect = false)
 {
     if (isset($this->_client)) {
         if ($this->_client->isAccessTokenExpired()) {
             return $this->redirectToAuth($storeId, $noAuthRedirect);
         }
         return $this->_client;
     }
     $clientId = $this->getConfig()->getConfigData('client_id', $storeId);
     $clientSecret = $this->getConfig()->getClientSecret($storeId);
     $accessToken = $this->_getAccessToken($storeId);
     if (!$clientId || !$clientSecret) {
         Mage::getSingleton('adminhtml/session')->addError("Please specify Google Content API access data for this store!");
         return false;
     }
     if (!isset($accessToken) || empty($accessToken)) {
         return $this->redirectToAuth($storeId, $noAuthRedirect);
     }
     $this->_client = new Google_Client();
     $this->_client->setApplicationName(self::APPNAME);
     $this->_client->setClientId($clientId);
     $this->_client->setClientSecret($clientSecret);
     $this->_client->setScopes('https://www.googleapis.com/auth/content');
     $this->_client->setAccessToken($accessToken);
     if ($this->_client->isAccessTokenExpired()) {
         return $this->redirectToAuth($storeId, $noAuthRedirect);
     }
     if ($this->getConfig()->getIsDebug($storeId)) {
         $this->_client->setLogger(Mage::getModel('gshoppingv2/logger', $this->_client)->setStoreID($storeId));
     }
     return $this->_client;
 }
Example #15
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 _init_service($access_token)
 {
     $client = new \Google_Client();
     $client->setClientId($this->_client_id);
     $client->setAccessToken($access_token);
     $this->_service = new \Google_Service_Drive($client);
 }
Example #17
0
 public function googlecallback()
 {
     $ret = null;
     //$google_redirect_url = site_url('user/signup');
     $google_redirect_url = 'http://localhost/punu/punu/index.php/user/signup';
     $client = new Google_Client();
     $client->setClientId($this->google_client_id);
     $client->setClientSecret($this->google_client_secret);
     $client->setDeveloperKey($this->google_api_key);
     $client->setRedirectUri($google_redirect_url);
     $client->addScope($this->google_scope);
     // Send Client Request
     $objOAuthService = new Google_Service_Oauth2($client);
     // Add Access Token to Session
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['google_access_token'] = $client->getAccessToken();
         //header('Location: ' . filter_var($this->google_redirect_url, FILTER_SANITIZE_URL));
     }
     // Set Access Token to make Request
     if (isset($_SESSION['google_access_token']) && $_SESSION['google_access_token']) {
         $client->setAccessToken($_SESSION['google_access_token']);
     }
     // Get User Data from Google and store them in $data
     if ($client->getAccessToken()) {
         $userData = $objOAuthService->userinfo->get();
         //$_SESSION['userData'] = $userData;
         $_SESSION['google_access_token'] = $client->getAccessToken();
         $ret = $userData;
     }
     return $ret;
 }
Example #18
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);
 }
Example #19
0
 /**
  * Sets the required params for authentication 
  * 
  * @param string $client_id our app's client id
  * @param string $client_secret our app's client secret 
  * @param string $redirect_uri where will the auth server send the client 
  * after generating an authorization code to authenticate
  * @param null|string $token token obtained when a code is authenticated
  * @param null|string $code response code to authenticate
  * @param null|array $scopes array of strings with OAuth2/google scopes 
  * to requested
  * @param null|Google_Client $client
  * @param bool $debug defaults to false
  */
 public function __construct($client_id, $client_secret, $redirect_uri, $token = null, $code = null, $scopes = null, $client = null, $debug = null)
 {
     $this->client_id = $client_id;
     $this->client_secret = $client_secret;
     $this->redirect_uri = $redirect_uri;
     $this->code = $code;
     $this->token = $token;
     if ($scopes !== null) {
         $this->scopes = $scopes;
     }
     if (is_bool($this->debug)) {
         $this->debug = $debug;
     } else {
         $this->debug = false;
     }
     if ($client === null) {
         $this->client = new Google_Client();
         $this->client->setClientId($this->client_id);
         $this->client->setClientSecret($this->client_secret);
         $this->client->setRedirectUri($this->redirect_uri);
         if ($token !== null) {
             $this->client->setAccessToken($token);
         }
         $this->client->setScopes($this->scopes);
     }
 }
    /**
     * Check, if the analytics account is authenticated and has an access token.
     * Authenticate it, if it is not.
     *
     * TODO: have the access token in a transient and check if the token expired before continuing
     *
     * @return bool
     */
    function is_app_authenticated()
    {
        $access_token = WooCommerce_Grow_Helpers::get_option('access_token');
        // We have an access token already
        if (!empty($access_token)) {
            try {
                $this->client->setAccessToken($access_token);
            } catch (Exception $e) {
                echo sprintf(__('Error: Unable to set Google Analytics access token. Error Code: %s. Error Message: %s  ', 'woocommerce-grow'), $e->getCode(), $e->getMessage());
                return false;
            }
        } else {
            $settings = get_option('woocommerce_woocommerce_grow_settings', array());
            $auth_code = WooCommerce_Grow_Helpers::get_field('authorization_token', $settings);
            if (empty($auth_code)) {
                // TODO: needs behavior
                return false;
            }
            try {
                // The authenticate method gets an access token, sets the access token
                // and returns the access token all at once.
                $access_token = $this->client->authenticate($auth_code);
                $this->client->setAccessToken($access_token);
                WooCommerce_Grow_Helpers::update_option('access_token', $access_token);
            } catch (Exception $e) {
                echo sprintf(__('Google Analytics was unable to authenticate you.
						Please refresh and try again. If the problem persists, please obtain a new authorizations token.
						Error Code: %s. Error Message: %s  ', 'woocommerce-grow'), $e->getCode(), $e->getMessage());
                return false;
            }
        }
        return true;
    }
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
 /**
  * Checks whether the user is authenticate or not.
  *
  * @return bool true when logged in.
  */
 public function check_login() {
     if ($token = $this->get_access_token()) {
         $this->client->setAccessToken($token);
         return true;
     }
     return false;
 }
Example #23
0
function bdn_is_user_auth2()
{
    global $driveService;
    $current_user_id = get_current_user_id();
    $client = new Google_Client();
    $client->setRedirectUri(home_url('/'));
    $driveService = new Google_DriveService($client);
    $oauth2 = new Google_Oauth2Service($client);
    if (!isset($_GET['code']) && (!is_user_logged_in() || ($access_token = get_user_meta($current_user_id, '_google_access_token', true)) && $client->setAccessToken($access_token) && !$client->getAccessToken())) {
        header('Location: ' . $client->createAuthUrl());
        exit;
    }
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $user = $oauth2->userinfo->get();
        $new_user = get_user_by('email', $user['email']);
        if (!$current_user_id) {
            wp_set_current_user($new_user->ID, $new_user->user_login);
            wp_set_auth_cookie($new_user->ID);
            do_action('wp_login', $new_user->user_login);
        } elseif ($new_user->ID == $current_user_id) {
            update_user_meta($new_user->ID, '_google_access_token', $client->getAccessToken());
        } else {
            die('Sorry, please use your BDN account');
        }
        header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
    }
    return $driveService;
}
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 #25
0
 /**
  * Initializes the Google Drive connection
  *
  * @param   array   $params  Any connection params needed
  * @return  object
  **/
 public static function init($params = [])
 {
     // Get the params
     $pparams = Plugin::params('filesystem', 'googledrive');
     $app_id = isset($params['app_id']) && $params['app_id'] != '' ? $params['app_id'] : $pparams->get('app_id');
     $app_secret = isset($params['app_secret']) && $params['app_secret'] != '' ? $params['app_secret'] : $pparams->get('app_secret');
     $client = new \Google_Client();
     $client->setClientId($app_id);
     $client->setClientSecret($app_secret);
     $client->addScope(Google_Service_Drive::DRIVE);
     $client->setAccessType('offline');
     $client->setApprovalPrompt('force');
     $client->setIncludeGrantedScopes(true);
     if (isset($params['app_token'])) {
         $accessToken = $params['app_token'];
         // json encode turned our array into an object, we need to undo that
         $accessToken = (array) $accessToken;
     } else {
         \Session::set('googledrive.app_id', $app_id);
         \Session::set('googledrive.app_secret', $app_secret);
         \Session::set('googledrive.connection_to_set_up', Request::getVar('connection', 0));
         // Set upp a return and redirect to Google for auth
         $return = Request::getVar('return') ? Request::getVar('return') : Request::current(true);
         $return = base64_encode($return);
         $redirectUri = trim(Request::root(), '/') . '/developer/callback/googledriveAuthorize';
         $client->setRedirectUri($redirectUri);
         Session::set('googledrive.state', $return);
         App::redirect($client->createAuthUrl());
     }
     $client->setAccessToken($accessToken);
     $service = new \Google_Service_Drive($client);
     $adapter = new \Hypweb\Flysystem\GoogleDrive\GoogleDriveAdapter($service, 'root');
     return $adapter;
 }
Example #26
0
function getClient()
{
    $client = new Google_Client();
    $client->setAuthConfigFile('includes/OAuth2/client_secret.json');
    $client->setAccessToken($_SESSION['access_token']);
    return $client;
}
Example #27
0
 function onNextendYoutube(&$google, &$youtube)
 {
     $config = new NextendData();
     $config->loadJson(NextendSmartSliderStorage::get(self::$_group));
     if (!class_exists('Google_Client')) {
         require_once dirname(__FILE__) . '/googleclient/Google_Client.php';
     }
     if (!class_exists('Google_YouTubeService')) {
         require_once dirname(__FILE__) . '/googleclient/contrib/Google_YouTubeService.php';
     }
     $google = new Google_Client();
     $google->setClientId($config->get('apikey', ''));
     $google->setClientSecret($config->get('apisecret', ''));
     $token = $config->get('token', null);
     if ($token) {
         $google->setAccessToken($token);
     }
     $youtube = new Google_YouTubeService($google);
     if ($google->isAccessTokenExpired()) {
         $token = json_decode($google->getAccessToken(), true);
         if (isset($token['refresh_token'])) {
             $google->refreshToken($token['refresh_token']);
             $config->set('token', $google->getAccessToken());
             NextendSmartSliderStorage::set(self::$_group, $config->toJSON());
         }
     }
 }
Example #28
0
 public function call_back()
 {
     $config = new Controllers_Api_Google_Config_App();
     $client = new Google_Client();
     $client->setClientId($config->config['client_id']);
     $client->setClientSecret($config->config['client_secret']);
     $client->setRedirectUri($config->config['redirect_uri']);
     $client->addScope("email");
     $client->addScope("profile");
     $service = new Google_Service_Oauth2($client);
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['access_token'] = $client->getAccessToken();
         header('Location: ' . filter_var($config->config['redirect_uri'], FILTER_SANITIZE_URL));
         exit;
     }
     /************************************************
         If we have an access token, we can make
         requests, else we generate an authentication URL.
        ************************************************/
     if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
         $client->setAccessToken($_SESSION['access_token']);
     } else {
         $authUrl = $client->createAuthUrl();
     }
     if (isset($authUrl)) {
         //show login url
         echo json_encode(array('status' => false, 'data' => $authUrl));
     } else {
         $user = $service->userinfo->get();
         //get user info
         echo json_encode(array('status' => true, 'data' => $user));
     }
 }
Example #29
0
function getClient()
{
    // Authenticate your API Client
    $client = new Google_Client();
    //$client->addScope(Google_Service_Storage::DEVSTORAGE_FULL_CONTROL);
    $client->addScope(Google_Service_Storage::DEVSTORAGE_READ_WRITE);
    // see ~/sandbox/zouk-event-calendar/vendor/google/apiclient/src/Google/Service/Storage.php
    $client->setAccessType("offline");
    $client->useApplicationDefaultCredentials();
    // no need to acquire special credentials
    $token = $client->getAccessToken();
    if (!$token) {
        // this is always the case, and same access token is aquired in the fetch call below (can be printed)
        //syslog(LOG_DEBUG, "girish: access token not present");
        $token = $client->fetchAccessTokenWithAssertion();
        $client->setAccessToken($token);
        //syslog(LOG_DEBUG, $token['access_token']);
    }
    // token acquried above is always expired. and even if you run fetchAccess...Refreshtoken() it still stays expired
    //if ($client->isAccessTokenExpired()) {
    //    //syslog(LOG_DEBUG, "girish: access token expired");
    //    $client->fetchAccessTokenWithRefreshToken($token);
    //}
    //if ($client->isAccessTokenExpired()) {
    //    syslog(LOG_DEBUG, "girish: access token still expired!"); // no idea how this works
    //}
    return $client;
}
/**
 * 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;
}