/examples/adsensehost/AdSenseHostAuth.php

https://bitbucket.org/insigngmbh/googlephpapi · PHP · 133 lines · 59 code · 11 blank · 63 comment · 8 complexity · c1608e56842109f2cd726005fde9cda8 MD5 · raw file

  1. <?php
  2. /*
  3. * Copyright 2012 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. // Error if PDO and PDO_SQLITE not present
  18. if (!extension_loaded('pdo') || !extension_loaded('pdo_sqlite')) {
  19. throw new Exception('The sample code needs PDO and PDO_SQLITE PHP extension');
  20. }
  21. /**
  22. * Include the library files for the api client and AdSense service class.
  23. */
  24. require_once "../../src/Google_Client.php";
  25. require_once "../../src/contrib/Google_AdsensehostService.php";
  26. /**
  27. * Handles authentication and OAuth token storing.
  28. * Assumes the presence of a sqlite database called './examples.sqlite'
  29. * containing a table called 'auth' composed of two VARCHAR(255) fields called
  30. * 'user' and 'token'.
  31. *
  32. * @author Sérgio Gomes <sgomes@google.com>
  33. * @author Silvano Luciani <silvano.luciani@gmail.com>
  34. */
  35. class AdSenseHostAuth {
  36. protected $apiClient;
  37. protected $adSenseHostService;
  38. private $user;
  39. /**
  40. * Create the dependencies.
  41. * (Inject them in a real world app!!)
  42. */
  43. public function __construct() {
  44. // Create the Google_Client instance.
  45. // You can set your credentials in the config.php file, included under the
  46. // src/ folder in your client library install.
  47. $this->apiClient = new Google_Client();
  48. // Create the api AdsensehostService instance.
  49. $this->adSenseHostService = new Google_AdsensehostService($this->apiClient);
  50. }
  51. /**
  52. * Check if a token for the user is already in the db, otherwise perform
  53. * authentication.
  54. * @param string $user The user to authenticate
  55. */
  56. public function authenticate($user) {
  57. $this->user = $user;
  58. $dbh = new PDO('sqlite:examples.sqlite');
  59. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  60. $stmt = $dbh->prepare('CREATE TABLE IF NOT EXISTS auth ' .
  61. '(user VARCHAR(255), token VARCHAR(255))');
  62. $stmt->execute();
  63. $token = $this->getToken($dbh);
  64. if (isset($token)) {
  65. // I already have the token.
  66. $this->apiClient->setAccessToken($token);
  67. } else {
  68. // Override the scope to use the readonly one
  69. $this->apiClient->setScopes(
  70. array("https://www.googleapis.com/auth/adsensehost"));
  71. // Go get the token
  72. $this->apiClient->setAccessToken($this->apiClient->authenticate());
  73. $this->saveToken($dbh, false, $this->apiClient->getAccessToken());
  74. }
  75. $dbh = null;
  76. }
  77. /**
  78. * Return the AdsenseService instance (to be used to retrieve data).
  79. * @return apiAdsenseService the authenticated apiAdsenseService instance
  80. */
  81. public function getAdSenseHostService() {
  82. return $this->adSenseHostService;
  83. }
  84. /**
  85. * During the request, the access code might have been changed for another.
  86. * This function updates the token in the db.
  87. */
  88. public function refreshToken() {
  89. if ($this->apiClient->getAccessToken() != null) {
  90. $dbh = new PDO('sqlite:examples.sqlite');
  91. $this->saveToken($dbh, true, $this->apiClient->getAccessToken());
  92. }
  93. }
  94. /**
  95. * Insert/update the auth token for the user.
  96. * @param PDO $dbh a PDO object for the local authentication db
  97. * @param bool $userExists true if the user already exists in the db
  98. * @param string $token the auth token to be saved
  99. */
  100. private function saveToken($dbh, $userExists, $token) {
  101. if ($userExists) {
  102. $stmt = $dbh->prepare('UPDATE auth SET token=:token WHERE user=:user');
  103. } else {
  104. $stmt = $dbh
  105. ->prepare('INSERT INTO auth (user, token) VALUES (:user, :token)');
  106. }
  107. $stmt->bindParam(':user', $this->user);
  108. $stmt->bindParam(':token', $this->apiClient->getAccessToken());
  109. $stmt->execute();
  110. }
  111. /**
  112. * Retrieves token for use.
  113. * @param PDO $dbh a PDO object for the local authentication db
  114. * @return string a JSON object representing the token
  115. */
  116. private function getToken($dbh) {
  117. $stmt = $dbh->prepare('SELECT token FROM auth WHERE user= ?');
  118. $stmt->execute(array($this->user));
  119. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  120. return $row['token'];
  121. }
  122. }