public function tryToGetAnAccessToken(Google_Client $client)
 {
     $this->checkClientCredentials();
     $client->setRedirectUri("urn:ietf:wg:oauth:2.0:oob");
     $client->setConfig('access_type', 'offline');
     $authUrl = $client->createAuthUrl();
     echo "\nPlease enter the auth code:\n";
     ob_flush();
     `open '{$authUrl}'`;
     $authCode = trim(fgets(STDIN));
     if ($accessToken = $client->fetchAccessTokenWithAuthCode($authCode)) {
         if (isset($accessToken['access_token'])) {
             return $accessToken;
         }
     }
     return false;
 }
define('CREDENTIALS_PATH', ApiGmail::CREDENTIALS_PATH);
define('CLIENT_SECRET_PATH', 'www/cfg/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/gmail-php-quickstart.json
define('SCOPES', implode(' ', array(Google_Service_Gmail::GMAIL_READONLY)));
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = ApiGmail::expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
    printf("Credentials exist in %s\n", $credentialsPath);
    echo PHP_EOL . 'Delete it for remake and restsrt this script';
} 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->fetchAccessTokenWithAuthCode($authCode);
    // Store the credentials to disk.
    if (!file_exists(dirname($credentialsPath))) {
        mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
}
exit;
Example #3
2
 public function buildYoutube($token)
 {
     $oauthClient = new \Google_Client();
     $oauthClient->setApplicationName("strebo");
     if (!isset($token["code"]) && !isset($token["token"])) {
         $oauthClient->setDeveloperKey(getenv("strebo_youtube_1"));
     }
     if (isset($token["code"]) || isset($token["token"])) {
         $oauthClient->setClientId(getenv("strebo_youtube_3"));
         $oauthClient->setClientSecret(getenv("strebo_youtube_4"));
     }
     $oauthClient->setRedirectUri($this->getApiCallback());
     if (isset($token["code"])) {
         $tokenArray = $oauthClient->fetchAccessTokenWithAuthCode($token['code']);
         $oauthClient->setAccessToken($tokenArray);
     }
     if (isset($token["token"])) {
         $oauthClient->setAccessToken($token["token"]);
     }
     return new \Google_Service_YouTube($oauthClient);
 }
/************************************************
 * If we're logging out we just need to clear our
 * local access token in this case
 ************************************************/
if (isset($_REQUEST['logout'])) {
    unset($_SESSION['id_token_token']);
}
/************************************************
 * If we have a code back from the OAuth 2.0 flow,
 * we need to exchange that with the
 * Google_Client::fetchAccessTokenWithAuthCode()
 * function. We store the resultant access token
 * bundle in the session, and redirect to ourself.
 ************************************************/
if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);
    // store in the session also
    $_SESSION['id_token_token'] = $token;
    // redirect back to the example
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
/************************************************
  If we have an access token, we can make
  requests, else we generate an authentication URL.
 ************************************************/
if (!empty($_SESSION['id_token_token']) && isset($_SESSION['id_token_token']['id_token'])) {
    $client->setAccessToken($_SESSION['id_token_token']);
} else {
    $authUrl = $client->createAuthUrl();
}
 /**
  * Prepare
  * Call from elFinder::netmout() before volume->mount().
  *
  * @return array
  *
  * @author Naoki Sawada
  * @author Raja Sharma updating for GoogleDrive
  **/
 public function netmountPrepare($options)
 {
     if (empty($options['client_id']) && defined('ELFINDER_GOOGLEDRIVE_CLIENTID')) {
         $options['client_id'] = ELFINDER_GOOGLEDRIVE_CLIENTID;
     }
     if (empty($options['client_secret']) && defined('ELFINDER_GOOGLEDRIVE_CLIENTSECRET')) {
         $options['client_secret'] = ELFINDER_GOOGLEDRIVE_CLIENTSECRET;
     }
     if (empty($options['googleApiClient']) && defined('ELFINDER_GOOGLEDRIVE_GOOGLEAPICLIENT')) {
         $options['googleApiClient'] = ELFINDER_GOOGLEDRIVE_GOOGLEAPICLIENT;
         include_once $options['googleApiClient'];
     }
     if (!isset($options['pass'])) {
         $options['pass'] = '';
     }
     try {
         $client = new \Google_Client();
         $client->setClientId($options['client_id']);
         $client->setClientSecret($options['client_secret']);
         if ($options['pass'] === 'reauth') {
             $options['pass'] = '';
             $this->session->set('GoogleDriveAuthParams', [])->set('GoogleDriveTokens', []);
         } elseif ($options['pass'] === 'googledrive') {
             $options['pass'] = '';
         }
         $options = array_merge($this->session->get('GoogleDriveAuthParams', []), $options);
         if (!isset($options['access_token'])) {
             $options['access_token'] = $this->session->get('GoogleDriveTokens', []);
             $this->session->remove('GoogleDriveTokens');
         }
         $aToken = $options['access_token'];
         $rootObj = $service = null;
         if ($aToken) {
             try {
                 $client->setAccessToken($aToken);
                 if ($client->isAccessTokenExpired()) {
                     $aToken = array_merge($aToken, $client->fetchAccessTokenWithRefreshToken());
                     $client->setAccessToken($aToken);
                 }
                 $service = new \Google_Service_Drive($client);
                 $rootObj = $service->files->get('root');
                 $options['access_token'] = $aToken;
                 $this->session->set('GoogleDriveAuthParams', $options);
             } catch (Exception $e) {
                 $aToken = [];
                 $options['access_token'] = [];
                 if ($options['user'] !== 'init') {
                     $this->session->set('GoogleDriveAuthParams', $options);
                     return ['exit' => true, 'error' => elFinder::ERROR_REAUTH_REQUIRE];
                 }
             }
         }
         if ($options['user'] === 'init') {
             if (empty($options['url'])) {
                 $options['url'] = elFinder::getConnectorUrl();
             }
             $callback = $options['url'] . '?cmd=netmount&protocol=googledrive&host=1';
             $client->setRedirectUri($callback);
             if (!$aToken && empty($_GET['code'])) {
                 $client->setScopes([Google_Service_Drive::DRIVE]);
                 if (!empty($options['offline'])) {
                     $client->setApprovalPrompt('force');
                     $client->setAccessType('offline');
                 }
                 $url = $client->createAuthUrl();
                 $html = '<input id="elf-volumedriver-googledrive-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\'' . $url . '\')">';
                 $html .= '<script>
                     $("#' . $options['id'] . '").elfinder("instance").trigger("netmount", {protocol: "googledrive", mode: "makebtn"});
                 </script>';
                 if (empty($options['pass']) && $options['host'] !== '1') {
                     $options['pass'] = '******';
                     $this->session->set('GoogleDriveAuthParams', $options);
                     return ['exit' => true, 'body' => $html];
                 } else {
                     $out = ['node' => $options['id'], 'json' => '{"protocol": "googledrive", "mode": "makebtn", "body" : "' . str_replace($html, '"', '\\"') . '", "error" : "' . elFinder::ERROR_ACCESS_DENIED . '"}', 'bind' => 'netmount'];
                     return ['exit' => 'callback', 'out' => $out];
                 }
             } else {
                 if (!empty($_GET['code'])) {
                     $aToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);
                     $options['access_token'] = $aToken;
                     $this->session->set('GoogleDriveTokens', $aToken)->set('GoogleDriveAuthParams', $options);
                     $out = ['node' => $options['id'], 'json' => '{"protocol": "googledrive", "mode": "done", "reset": 1}', 'bind' => 'netmount'];
                     return ['exit' => 'callback', 'out' => $out];
                 }
                 $folders = [];
                 foreach ($service->files->listFiles(['pageSize' => 1000, 'q' => 'trashed = false and mimeType = "application/vnd.google-apps.folder"']) as $f) {
                     $folders[$f->getId()] = $f->getName();
                 }
                 natcasesort($folders);
                 $folders = ['root' => $rootObj->getName()] + $folders;
                 $folders = json_encode($folders);
                 $expires = empty($aToken['refresh_token']) ? $aToken['created'] + $aToken['expires_in'] - 30 : 0;
                 $json = '{"protocol": "googledrive", "mode": "done", "folders": ' . $folders . ', "expires": ' . $expires . '}';
                 $options['pass'] = '******';
                 $html = 'Google.com';
                 $html .= '<script>
                     $("#' . $options['id'] . '").elfinder("instance").trigger("netmount", ' . $json . ');
                 </script>';
                 $this->session->set('GoogleDriveAuthParams', $options);
                 return ['exit' => true, 'body' => $html];
             }
         }
     } catch (Exception $e) {
         $this->session->remove('GoogleDriveAuthParams')->remove('GoogleDriveTokens');
         if (empty($options['pass'])) {
             return ['exit' => true, 'body' => '{msg:' . elFinder::ERROR_ACCESS_DENIED . '}' . ' ' . $e->getMessage()];
         } else {
             return ['exit' => true, 'error' => [elFinder::ERROR_ACCESS_DENIED, $e->getMessage()]];
         }
     }
     if (!$aToken) {
         return ['exit' => true, 'error' => elFinder::ERROR_REAUTH_REQUIRE];
     }
     if ($options['path'] === '/') {
         $options['path'] = 'root';
     }
     try {
         $file = $service->files->get($options['path']);
         $options['alias'] = sprintf($this->options['gdAlias'], $file->getName());
     } catch (Google_Service_Exception $e) {
         $err = json_decode($e->getMessage(), true);
         if (isset($err['error']) && $err['error']['code'] == 404) {
             return ['exit' => true, 'error' => [elFinder::ERROR_TRGDIR_NOT_FOUND, $options['path']]];
         } else {
             return ['exit' => true, 'error' => $e->getMessage()];
         }
     } catch (Exception $e) {
         return ['exit' => true, 'error' => $e->getMessage()];
     }
     foreach (['host', 'user', 'pass', 'id', 'offline'] as $key) {
         unset($options[$key]);
     }
     return $options;
 }
Example #6
1
 /**
  * Processes the google callback from oauth authorize requests
  *
  * @return    void
  **/
 public function googledriveAuthorizeTask()
 {
     $pparams = \Plugin::params('filesystem', 'google');
     $app_id = \Session::get('googledrive.app_id', false);
     $app_secret = \Session::get('googledrive.app_secret', false);
     $new_connection = Session::get('googledrive.connection_to_set_up', false);
     $info = ['key' => isset($app_key) ? $app_key : $pparams->get('app_key'), 'secret' => isset($app_secret) ? $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');
     $redirectUri = trim(Request::root(), '/') . '/developer/callback/googledriveAuthorize';
     $client->setRedirectUri($redirectUri);
     $code = Request::get('code', false);
     if ($code) {
         $client->fetchAccessTokenWithAuthCode($code);
         $accessToken = $client->getAccessToken();
     } else {
         throw new \Exception("No state found", 400);
     }
     //if this is a new connection, we can save the token on the server to ensure that it is used next time
     if ($new_connection) {
         require_once PATH_CORE . DS . 'components' . DS . 'com_projects' . DS . 'models' . DS . 'orm' . DS . 'connection.php';
         $connection = \Components\Projects\Models\Orm\Connection::oneOrFail($new_connection);
         $connection_params = json_decode($connection->get('params'));
         $connection_params->app_token = $accessToken;
         $connection->set('params', json_encode($connection_params));
         $connection->save();
     }
     // Redirect to the local endpoint
     App::redirect(base64_decode(\Session::get('googledrive.state')));
 }
function authGoogle($get)
{
    require_once 'lib/vendor/autoload.php';
    # require_once 'lib/google-php-client/vendor/autoload.php';
    global $google_clientid, $google_secret, $google_config_file_path;
    /*************************************************
     * Ensure you've downloaded your oauth credentials
     ************************************************/
    if (!file_exists($google_config_file_path)) {
        return array("status" => false, "error" => "Bad config file path");
    }
    /************************************************
     * NOTICE:
     * The redirect URI is to the current page, e.g:
     * http://localhost:8080/idtoken.php
     ************************************************/
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    $client = new Google_Client();
    $client->setAuthConfig($google_config_file_path);
    $client->setRedirectUri($redirect_uri);
    $client->setScopes('email');
    /************************************************
     * If we're logging out we just need to clear our
     * local access token in this case
     ************************************************/
    if (isset($_REQUEST['logout'])) {
        unset($_SESSION['id_token']);
    }
    $token = $get["token"];
    try {
        /************************************************
         * If we have a code back from the OAuth 2.0 flow,
         * we need to exchange that with the
         * Google_Client::fetchAccessTokenWithAuthCode()
         * function. We store the resultant access token
         * bundle in the session, and redirect to ourself.
         ************************************************/
        if (!empty($token) && empty($get["tokens"])) {
            $fancyToken = array("access_token" => $token);
            $token = $client->fetchAccessTokenWithAuthCode($get["token"]);
            $client->setAccessToken($token);
            // store in the session also
            $_SESSION['id_token'] = $token;
            $token_data = $client->verifyIdToken();
        } else {
            if (!empty($get["tokens"])) {
                $tokens = base64_decode($get["tokens"]);
                $client->setAccessToken($get["tokens"]);
                $ta = json_decode($tokens, true);
                $token_data = $client->verifyIdToken($ta["id_token"]);
            } else {
                /************************************************
                  If we have an access token, we can make
                  requests, else we generate an authentication URL.
                    ************************************************/
                $authUrl = $client->createAuthUrl();
            }
        }
    } catch (Exception $e) {
        $token2 = $get['token'];
        if (is_string($token2)) {
            if ($json = json_decode($token2, true)) {
                $token2 = $json;
            } else {
                // assume $token is just the token string
                $token2 = array('access_token' => $token2);
            }
        }
        return array("status" => false, "error" => $e->getMessage(), "stack" => $e->getTraceAsString(), "token" => $token, "computed_token" => $token2, "tokens" => base64_decode($get["tokens"]));
    }
    /************************************************
      If we're signed in we can go ahead and retrieve
      the ID token, which is part of the bundle of
      data that is exchange in the authenticate step
      - we only need to do a network call if we have
      to retrieve the Google certificate to verify it,
      and that can be cached.
        ************************************************/
    $return = array("status" => true, "auth_url" => $authUrl, "token_data" => $token_data, "identifier" => $token_data["email"], "verifier" => computeUserPassword($token_data["sub"]));
    return $return;
}