Exemplo n.º 1
0
 public function actionStoreToken()
 {
     $code = $_POST['code'];
     require_once 'protected/extensions/google-api-php-client/src/Google_Client.php';
     $client = new Google_Client();
     $client->setClientId(Yii::app()->settings->googleClientId);
     $client->setClientSecret(Yii::app()->settings->googleClientSecret);
     $client->setRedirectUri('postmessage');
     $client->setAccessType('offline');
     $client->authenticate($code);
     $token = json_decode($client->getAccessToken());
     // Verify the token
     $reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' . $token->access_token;
     $req = new Google_HttpRequest($reqUrl);
     $tokenInfo = json_decode($client::getIo()->authenticatedRequest($req)->getResponseBody());
     // If there was an error in the token info, abort.
     if (isset($tokenInfo->error) && $tokenInfo->error) {
         return new Response($tokenInfo->error, 500);
     }
     // Make sure the token we got is for our app.
     if ($tokenInfo->audience != Yii::app()->settings->googleClientId) {
         return new Response("Token's client ID does not match app's.", 401);
     }
     // Store the token in the session for later use.
     $_SESSION['token'] = json_encode($token);
     $_SESSION['access_token'] = json_encode($token);
     $auth = new GoogleAuthenticator();
     $user = $auth->getUserInfo($client->getAccessToken());
     $email = filter_var($user->email, FILTER_SANITIZE_EMAIL);
     $profileRecord = Profile::model()->findByAttributes(array(), "emailAddress=:email OR googleId=:email", array(':email' => $email));
     if (isset($profileRecord)) {
         $auth->storeCredentials($profileRecord->id, $_SESSION['access_token']);
     }
     $response = 'Successfully connected with token: ' . print_r($token, true);
     echo $response;
 }