public function testFileCache()
 {
     $this->onlyPhp55AndAbove();
     $this->checkServiceAccountCredentials();
     $client = new Google_Client();
     $client->useApplicationDefaultCredentials();
     $client->setScopes(['https://www.googleapis.com/auth/drive.readonly']);
     // filecache with new cache dir
     $cache = $this->getCache(sys_get_temp_dir() . '/cloud-samples-tests-php-cache-test/');
     $client->setCache($cache);
     $token1 = null;
     $client->setTokenCallback(function ($cacheKey, $accessToken) use($cache, &$token1) {
         $token1 = $accessToken;
         $cacheItem = $cache->getItem($cacheKey);
         // expire the item
         $cacheItem->expiresAt(new DateTime('now -1 second'));
         $cache->save($cacheItem);
         $cacheItem2 = $cache->getItem($cacheKey);
     });
     /* Refresh token when expired */
     if ($client->isAccessTokenExpired()) {
         $client->refreshTokenWithAssertion();
     }
     /* Make a service call */
     $service = new Google_Service_Drive($client);
     $files = $service->files->listFiles();
     $this->assertInstanceOf('Google_Service_Drive_FileList', $files);
     sleep(1);
     // make sure the token expires
     $client = new Google_Client();
     $client->useApplicationDefaultCredentials();
     $client->setScopes(['https://www.googleapis.com/auth/drive.readonly']);
     $client->setCache($cache);
     $token2 = null;
     $client->setTokenCallback(function ($cacheKey, $accessToken) use(&$token2) {
         $token2 = $accessToken;
     });
     /* Make another service call */
     $service = new Google_Service_Drive($client);
     $files = $service->files->listFiles();
     $this->assertInstanceOf('Google_Service_Drive_FileList', $files);
     $this->assertNotEquals($token1, $token2);
 }
 /**
  * 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();
 }
Example #4
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;
         }
     }
 }
 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;
 }
 /**
  * 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 #7
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();
 }
/**
 * 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 #9
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;
}
 /**
  * @throws MissingConfigurationException
  * @return \Google_Client
  */
 public function create()
 {
     $client = new \Google_Client();
     $requiredAuthenticationSettings = array('applicationName', 'clientId', 'clientSecret', 'developerKey');
     foreach ($requiredAuthenticationSettings as $key) {
         if (!isset($this->authenticationSettings[$key])) {
             throw new MissingConfigurationException(sprintf('Missing setting "TYPO3.Neos.GoogleAnalytics.authentication.%s"', $key), 1415796352);
         }
     }
     $client->setApplicationName($this->authenticationSettings['applicationName']);
     $client->setClientId($this->authenticationSettings['clientId']);
     $client->setClientSecret($this->authenticationSettings['clientSecret']);
     $client->setDeveloperKey($this->authenticationSettings['developerKey']);
     $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
     $client->setAccessType('offline');
     $accessToken = $this->tokenStorage->getAccessToken();
     if ($accessToken !== NULL) {
         $client->setAccessToken($accessToken);
         if ($client->isAccessTokenExpired()) {
             $refreshToken = $this->tokenStorage->getRefreshToken();
             $client->refreshToken($refreshToken);
         }
     }
     return $client;
 }
Example #11
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;
}
Example #12
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());
         }
     }
 }
 private function refreshAuthToken(\Google_Client $client)
 {
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents(CREDENTIALS_FILE, $client->getAccessToken());
     }
 }
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;
}
/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    global $credentialsPath, $client;
    $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 {
        logStatusFailure("Please, get token via http://" . BASE_SERVER . "/connect.php");
        closeSession();
    }

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        logMessage("Token Expired. Refreshing via curl connect");
        $ch = curl_init("http://" . BASE_SERVER . "/connect.php");
        curl_exec($ch);
        curl_close($ch);

    }
    return $client;
}
Example #16
0
 /**
  * Load Google and Calendar Service data by Staff
  *
  * @param AB_Staff $staff
  * @return bool
  */
 public function loadByStaff(AB_Staff $staff)
 {
     $this->staff = $staff;
     if ($staff->get('google_data')) {
         try {
             $this->client->setAccessToken($staff->get('google_data'));
             if ($this->client->isAccessTokenExpired()) {
                 $this->client->refreshToken($this->client->getRefreshToken());
                 $staff->set('google_data', $this->client->getAccessToken());
                 $staff->save();
             }
             $this->service = new Google_Service_Calendar($this->client);
             return true;
         } catch (Exception $e) {
             $this->errors[] = $e->getMessage();
         }
     }
     return false;
 }
 public function fetchAction()
 {
     $em = $this->getDoctrine()->getEntityManager();
     // TODO move to a cron job
     // TODO move google credentials to symfony parameters file
     $configDirectories = array(__DIR__ . '/../Resources/config');
     $locator = new FileLocator($configDirectories);
     $clientSecret = $locator->locate('client_secret.json');
     $credentialsPath = $locator->locate('calendar-api-quickstart.json');
     // Get the API client and construct the service object.
     $client = new \Google_Client();
     $client->setApplicationName('Google Calendar API Quickstart');
     $client->setScopes(implode(' ', array(\Google_Service_Calendar::CALENDAR_READONLY)));
     $client->setAuthConfigFile($clientSecret);
     $client->setAccessType('offline');
     // Load previously authorized credentials from a file.
     if (file_exists($credentialsPath)) {
         $accessToken = file_get_contents($credentialsPath);
     } else {
         //TODO this should be accomplished with an error status
         return $this->render('TechlancasterWebBundle:Default:calendar.html.twig', array('message' => 'Invalid Credentials'));
     }
     $client->setAccessToken($accessToken);
     // Refresh the token if it's expired.
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents($credentialsPath, $client->getAccessToken());
     }
     $service = new \Google_Service_Calendar($client);
     $calendarId = '*****@*****.**';
     $optParams = array('maxResults' => 29, 'orderBy' => 'startTime', 'singleEvents' => true, 'timeMin' => date('c'));
     $results = $service->events->listEvents($calendarId, $optParams);
     $events = array();
     $connection = $em->getConnection();
     $platform = $connection->getDatabasePlatform();
     $connection->executeUpdate($platform->getTruncateTableSQL('event', false));
     /**
      * @var $googleEvent Google_Service_Calendar_Event
      */
     foreach ($results->getItems() as $googleEvent) {
         $event = new Event();
         $event->setId($googleEvent->getId());
         $event->setDescription($googleEvent->getDescription());
         $event->setLocation($googleEvent->getLocation());
         $event->setStart(new \DateTime($googleEvent->getStart()->dateTime));
         $event->setEnd(new \DateTime($googleEvent->getEnd()->dateTime));
         $event->setSummary($googleEvent->getSummary());
         $em->persist($event);
         $events[] = $event;
     }
     $em->flush();
     return $this->render('TechlancasterWebBundle:Default:calendar.html.twig', array('message' => json_encode($events)));
 }
 /**
  * Get the access token to the calendar
  *
  * @return string
  *
  * @throws \KevinDitscheid\KdCalendar\Exception\NoCredentialsException
  */
 public function getCredentials()
 {
     $accessToken = $this->registry->get('tx_kdcalendar', 'accessToken');
     if (!$accessToken) {
         throw new \KevinDitscheid\KdCalendar\Exception\NoCredentialsException('No crendetials found!', 1460891865);
     }
     $this->client->setAccessToken($accessToken);
     if ($this->client->isAccessTokenExpired()) {
         $this->refreshToken();
     }
     return $this->client->getAccessToken();
 }
 public function __construct(array $options = [])
 {
     $this->_client = new \Google_Client();
     $this->_client->setClientId($options['client_id']);
     $this->_client->setClientSecret($options['client_secret']);
     touch(sys_get_temp_dir() . '/googleplay_access_token.txt');
     chmod(sys_get_temp_dir() . '/googleplay_access_token.txt', 0777);
     try {
         $this->_client->setAccessToken(file_get_contents(sys_get_temp_dir() . '/googleplay_access_token.txt'));
     } catch (\Exception $e) {
         // skip exceptions when the access token is not valid
     }
     try {
         if ($this->_client->isAccessTokenExpired()) {
             $this->_client->refreshToken($options['refresh_token']);
             file_put_contents(sys_get_temp_dir() . '/googleplay_access_token.txt', $this->_client->getAccessToken());
         }
     } catch (\Exception $e) {
         throw new RuntimeException('Failed refreshing access token - ' . $e->getMessage());
     }
     $this->_androidPublisherService = new \Google_Service_AndroidPublisher($this->_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 {
        $authUrl = $client->createAuthUrl();
        $authCode = false;
        if (isset($_POST['authCode']) && $_POST['authCode']) {
            $authCode = $_POST['authCode'];
        }

        if (!$authCode) {
            printf("Open the following link in your browser:\n<a href='%s' target='_blank'>link</a>\n", $authUrl);
            echo "<form method='post'><input name='authCode'><input type='submit' name='Check auth code'></form>";
            die;
        }

        if ($authCode) {
            // Exchange authorization code for an access token.
            $accessToken = $client->authenticate($authCode);
            if (file_put_contents($credentialsPath, $accessToken)) {
                printf("Credentials saved to %s: " . colorize("SUCCESS", "SUCCESS") . "<br>", $credentialsPath);
            } else {
                printf("Credentials saved to %s: " . colorize("FAILED", "FAILURE") . "<br>", $credentialsPath);
                die;
            }
        } else {
            die("No authCode");
        }
    }

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        echo "Token is Expired. Trying to refresh.. <br>";
        $client = refreshToken($client);
    } else {
        echo "Everything fine<br>";
    }

    return $client;
}
 /**
  * This function connect with google and return the service
  * @param ExternalCalendarUser $user
  * @return Google_Service_Calendar
  */
 private function connect_with_google_calendar($user)
 {
     $client = new Google_Client();
     $client->setAccessToken($user->getAuthPass());
     //if isAccessTokenExpired then refresh the token and store it
     if ($client->isAccessTokenExpired()) {
         $credentials = json_decode($user->getAuthPass());
         $client->refreshToken($credentials->refresh_token);
         $user->setAuthPass($client->getAccessToken());
         $user->save();
     }
     $service = new Google_Service_Calendar($client);
     return $service;
 }
Example #22
0
 /**
  * Authenticate
  * @param int $type
  * @throws Exception
  */
 public function auth($type = self::AUTH_TYPE_CMD_LINE)
 {
     if ($this->accessToken !== null) {
         // Already got an auth token
         $this->getLogger()->debug('Using existing accessToken');
         $this->client->setAccessToken($this->accessToken);
         if (!$this->client->isAccessTokenExpired()) {
             return;
         }
         $this->getLogger()->info('Existing accessToken no longer valid');
         if ($this->refreshToken !== null) {
             $this->getLogger()->debug('Using refreshToken');
             $this->client->refreshToken($this->refreshToken);
             return;
         }
     }
     switch ($type) {
         case self::AUTH_TYPE_CMD_LINE:
             $this->cmdLineAuth();
             break;
         default:
             throw new Exception('Auth Type not valid');
     }
 }
Example #23
0
 public function steal_control($stage)
 {
     global $CFG;
     if ($stage != PORTFOLIO_STAGE_CONFIG) {
         return false;
     }
     $this->initialize_oauth();
     if ($this->get_access_token()) {
         // Ensure that token is not expired.
         if (!$this->client->isAccessTokenExpired()) {
             return false;
         }
     }
     return $this->client->createAuthUrl();
 }
 public function callback()
 {
     $redirectUri = 'http' . (isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] ? 's' : '' : '') . '://' . $_SERVER['HTTP_HOST'] . '/GoogleAuthenticatorController/callback';
     $client = new Google_Client();
     $client->setClientId(GOOGLE_AUTHENTICATOR_CLIENT_ID);
     $client->setClientSecret(GOOGLE_AUTHENTICATOR_CLIENT_SECRET);
     $client->setRedirectUri($redirectUri);
     $client->addScope("email");
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['google_accesstoken'] = $client->getAccessToken();
         header('Location: ' . filter_var($redirectUri, FILTER_SANITIZE_URL));
     }
     if (isset($_SESSION['google_accesstoken']) && $_SESSION['google_accesstoken']) {
         $client->setAccessToken($_SESSION['google_accesstoken']);
     }
     $form = new GoogleAuthenticatorLoginForm($this, 'LoginForm');
     if ($client->getAccessToken() && !$client->isAccessTokenExpired()) {
         $_SESSION['google_accesstoken'] = $client->getAccessToken();
         $token_data = $client->verifyIdToken()->getAttributes();
         $email = $token_data['payload']['email'];
         $member = Member::get()->filter(array('Email' => $email))->first();
         if (isset($_SESSION['BackURL']) && $_SESSION['BackURL'] && Director::is_site_url($_SESSION['BackURL'])) {
             $backURL = $_SESSION['BackURL'];
         }
         if ($member) {
             $member->logIn();
             if ($backURL) {
                 return $this->redirect($backURL);
             }
             if (Security::config()->default_login_dest) {
                 return $this->redirect(Director::absoluteBaseURL() . Security::config()->default_login_dest);
             }
             return Controller::curr()->redirectBack();
         } else {
             $form->sessionMessage("The Google account {$email} is not authorised to access the system.", 'bad');
         }
     } else {
         $form->sessionMessage("There is an error authenticating with Google. Please try again.", 'bad');
     }
     $loginLink = Director::absoluteURL('/Security/login');
     if ($backURL) {
         $loginLink .= '?BackURL=' . urlencode($backURL);
     }
     $loginLink .= '#GoogleAuthenticatorLoginForm_LoginForm_tab';
     return $this->redirect($loginLink);
 }
Example #25
0
 public function oAuthCheckToken($params, $smarty)
 {
     $token = GoogleShopping::getConfigValue('oauth_access_token');
     if (!$token) {
         $smarty->assign('tokenExist', 'none');
         return;
     }
     $client = new \Google_Client();
     $client->setApplicationName(GoogleShopping::getConfigValue('application_name'));
     $client->setClientId(GoogleShopping::getConfigValue('client_id'));
     $client->setClientSecret(GoogleShopping::getConfigValue('client_secret'));
     $client->setRedirectUri(URL::getInstance()->absoluteUrl('/googleshopping/oauth2callback'));
     $client->setScopes('https://www.googleapis.com/auth/content');
     $client->setAccessToken($token);
     if (true === $client->isAccessTokenExpired()) {
         $smarty->assign('tokenExpired', true);
     }
 }
 public function checkGoogleAuth()
 {
     $token = GoogleShopping::getConfigValue('oauth_access_token');
     if (!$token) {
         return false;
     }
     $client = new \Google_Client();
     $client->setApplicationName(GoogleShopping::getConfigValue('application_name'));
     $client->setClientId(GoogleShopping::getConfigValue('client_id'));
     $client->setClientSecret(GoogleShopping::getConfigValue('client_secret'));
     $client->setRedirectUri(URL::getInstance()->absoluteUrl('/googleshopping/oauth2callback'));
     $client->setScopes('https://www.googleapis.com/auth/content');
     $client->setAccessToken($token);
     if (true === $client->isAccessTokenExpired()) {
         return false;
     }
     return true;
 }
 /**
  * Returns an authorized API client.
  * @return \Google_Client the authorized client object
  */
 public function __construct()
 {
     $client = new \Google_Client();
     $client->setApplicationName(APPLICATION_NAME);
     $client->setScopes(SCOPES);
     $client->setAuthConfigFile(CLIENT_SECRET_PATH);
     $client->setAccessType('offline');
     if (!file_exists(CREDENTIALS_PATH)) {
         throw new \Exception('No credentials set');
     }
     $accessToken = file_get_contents(CREDENTIALS_PATH);
     $client->setAccessToken($accessToken);
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents(CREDENTIALS_PATH, $client->getAccessToken());
     }
     $this->client = $client;
     $this->service = new \Google_Service_Calendar($client);
 }
    public function startClient()
    {
        if ($this->accessToken === false) {
            die;
        }
        try {
            $token = $this->accessToken;
            $this->client->setAccessToken($token);
            if ($this->client->isAccessTokenExpired()) {
                $tokenobj = json_decode($token);
                if (isset($tokenobj->refresh_token)) {
                    try {
                        $this->client->refreshToken($tokenobj->refresh_token);
                    } catch (Exception $e) {
                        $this->settings['googledrive_app_current_token'] = '';
                        $this->settings['googledrive_app_refresh_token'] = '';
                        update_option('use_your_drive_settings', $this->settings);
                        if ($this->settings['lostauthorization_notification'] !== 'No') {
                            $subject = get_bloginfo() . ' | ' . __('Use-your-Drive authorization', 'useyourdrive');
                            $message = 'Hi!

The Use-your-Drive plugin has lost its authorization to Box. Without authorization the plugin cannot longer function. Please authorize the plugin again to make sure that your visitors can access your files.';
                            $message .= "<br>********<br>" . $e->getMessage() . '<br>********';
                            $result = wp_mail($this->settings['lostauthorization_notification'], $subject, $message);
                        }
                        return new WP_Error('broke', __("Use-your-Drive isn't ready to run", 'useyourdrive') . $e->getMessage());
                    }
                    $this->accessToken = $this->client->getAccessToken();
                    $this->settings['googledrive_app_current_token'] = $this->accessToken;
                    update_option('use_your_drive_settings', $this->settings);
                } else {
                    $this->settings['googledrive_app_current_token'] = '';
                    $this->settings['googledrive_app_refresh_token'] = '';
                    update_option('use_your_drive_settings', $this->settings);
                    return new WP_Error('broke', __("Use-your-Drive isn't ready to run", 'useyourdrive'));
                }
            }
        } catch (Exception $e) {
            return new WP_Error('broke', __("Couldn't connect to Google API: ", 'useyourdrive') . $e->getMessage());
        }
        return $this->client;
    }
Example #29
0
 /**
  * Deletes a video from the account specified by the Access Token
  * Attempts to automatically refresh the token if it's expired.
  *
  * @param $id of the video to delete
  * @return true if the video was deleted and false if it was not
  * @throws \Exception
  */
 public function delete($video_id)
 {
     $accessToken = $this->client->getAccessToken();
     if (is_null($accessToken)) {
         throw new \Exception('You need an access token to delete.');
     }
     // Attempt to refresh the access token if it's expired and save the new one in the database
     if ($this->client->isAccessTokenExpired()) {
         $accessToken = json_decode($accessToken);
         $refreshToken = $accessToken->refresh_token;
         $this->client->refreshToken($refreshToken);
         $newAccessToken = $this->client->getAccessToken();
         $this->saveAccessTokenToDB($newAccessToken);
     }
     $result = $this->youtube->videos->delete($video_id);
     if (!$result) {
         throw new \Exception("Couldn't delete the video from the youtube account.");
     }
     return $result->getId();
 }
Example #30
0
 public function login($token)
 {
     $client = new Google_Client();
     $oauth2 = new Google_Oauth2Service($client);
     if (!empty($token)) {
         $token = base64_decode($token);
         $client->setAccessToken($token);
         if (!$client->isAccessTokenExpired()) {
             $user = $oauth2->userinfo->get();
             $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
             $student = $this->getByEmail($email);
             if ($student != null) {
                 return $student;
             }
         }
         $this->logout($token);
     }
     $authUrl = $client->createAuthUrl();
     return $authUrl;
 }