PageRenderTime 57ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/chrome/common/extensions/docs/examples/apps/hello-php/index.php

https://gitlab.com/jonnialva90/iridium-browser
PHP | 288 lines | 219 code | 25 blank | 44 comment | 25 complexity | 461fbd69642c250660a42a226a25091f MD5 | raw file
  1. <?php
  2. /**
  3. * Copyright (c) 2012 The Chromium Authors. All rights reserved.
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. *
  7. * A "Hello world!" for the Chrome Web Store Licensing API, in PHP. This
  8. * program logs the user in with Google's Federated Login API (OpenID), fetches
  9. * their license state with OAuth, and prints one of these greetings as
  10. * appropriate:
  11. *
  12. * 1. This user has FREE_TRIAL access to this application ( appId: 1 )
  13. * 2. This user has FULL access to this application ( appId: 1 )
  14. * 3. This user has NO access to this application ( appId: 1 )
  15. *
  16. * This code makes use of a popup ui extension to the OpenID protocol. Instead
  17. * of the user being redirected to the Google login page, a popup window opens
  18. * to the login page, keeping the user on the main application page. See
  19. * popuplib.js
  20. *
  21. * Eric Bidelman <ericbidelman@chromium.org>
  22. */
  23. session_start();
  24. require_once 'lib/oauth/OAuth.php';
  25. require_once 'lib/lightopenid/openid.php';
  26. // Full URL of the current application is running under.
  27. $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') ? 'http' :
  28. 'https';
  29. $selfUrl = "$scheme://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}";
  30. /**
  31. * Wrapper class to make calls to the Chrome Web Store License Server.
  32. */
  33. class LicenseServerClient {
  34. const LICENSE_SERVER_HOST = 'https://www.googleapis.com';
  35. const CONSUMER_KEY = 'anonymous';
  36. const CONSUMER_SECRET = 'anonymous';
  37. const APP_ID = '1'; // Change to the correct id of your application.
  38. const TOKEN = '[REPLACE THIS WITH YOUR OAUTH TOKEN]';
  39. const TOKEN_SECRET = '[REPLACE THIS WITH YOUR OAUTH TOKEN SECRET]';
  40. public $consumer;
  41. public $token;
  42. public $signatureMethod;
  43. public function __construct() {
  44. $this->consumer = new OAuthConsumer(
  45. self::CONSUMER_KEY, self::CONSUMER_SECRET, NULL);
  46. $this->token = new OAuthToken(self::TOKEN, self::TOKEN_SECRET);
  47. $this->signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
  48. }
  49. /**
  50. * Makes an HTTP GET request to the specified URL.
  51. *
  52. * @param string $url Full URL of the resource to access
  53. * @param string $request OAuthRequest containing the signed request to make.
  54. * @param array $extraHeaders (optional) Array of headers.
  55. * @param bool $returnResponseHeaders True if resp headers should be returned.
  56. * @return string Response body from the server.
  57. */
  58. protected function send_signed_get($request, $extraHeaders=NULL,
  59. $returnRequestHeaders=false,
  60. $returnResponseHeaders=false) {
  61. $url = explode('?', $request->to_url());
  62. $curl = curl_init($url[0]);
  63. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  64. curl_setopt($curl, CURLOPT_FAILONERROR, false);
  65. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  66. // Return request headers in the response.
  67. curl_setopt($curl, CURLINFO_HEADER_OUT, $returnRequestHeaders);
  68. // Return response headers in the response?
  69. if ($returnResponseHeaders) {
  70. curl_setopt($curl, CURLOPT_HEADER, true);
  71. }
  72. $headers = array($request->to_header());
  73. if (is_array($extraHeaders)) {
  74. $headers = array_merge($headers, $extraHeaders);
  75. }
  76. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  77. // Execute the request. If an error occurs fill the response body with it.
  78. $response = curl_exec($curl);
  79. if (!$response) {
  80. $response = curl_error($curl);
  81. }
  82. // Add server's response headers to our response body
  83. $response = curl_getinfo($curl, CURLINFO_HEADER_OUT) . $response;
  84. curl_close($curl);
  85. return $response;
  86. }
  87. public function checkLicense($userId) {
  88. $url = self::LICENSE_SERVER_HOST . '/chromewebstore/v1/licenses/' .
  89. self::APP_ID . '/' . urlencode($userId);
  90. $request = OAuthRequest::from_consumer_and_token(
  91. $this->consumer, $this->token, 'GET', $url, array());
  92. $request->sign_request($this->signatureMethod, $this->consumer,
  93. $this->token);
  94. return $this->send_signed_get($request);
  95. }
  96. }
  97. try {
  98. $openid = new LightOpenID();
  99. $userId = $openid->identity;
  100. if (!isset($_GET['openid_mode'])) {
  101. // This section performs the OpenID dance with the normal redirect. Use it
  102. // if you want an alternative to the popup UI.
  103. if (isset($_GET['login'])) {
  104. $openid->identity = 'https://www.google.com/accounts/o8/id';
  105. $openid->required = array('namePerson/first', 'namePerson/last',
  106. 'contact/email');
  107. header('Location: ' . $openid->authUrl());
  108. }
  109. } else if ($_GET['openid_mode'] == 'cancel') {
  110. echo 'User has canceled authentication!';
  111. } else {
  112. $userId = $openid->validate() ? $openid->identity : '';
  113. $_SESSION['userId'] = $userId;
  114. $attributes = $openid->getAttributes();
  115. $_SESSION['attributes'] = $attributes;
  116. }
  117. } catch(ErrorException $e) {
  118. echo $e->getMessage();
  119. exit;
  120. }
  121. if (isset($_REQUEST['popup']) && !isset($_SESSION['redirect_to'])) {
  122. $_SESSION['redirect_to'] = $selfUrl;
  123. echo '<script type = "text/javascript">window.close();</script>';
  124. exit;
  125. } else if (isset($_SESSION['redirect_to'])) {
  126. $redirect = $_SESSION['redirect_to'];
  127. unset($_SESSION['redirect_to']);
  128. header('Location: ' . $redirect);
  129. } else if (isset($_REQUEST['queryLicenseServer'])) {
  130. $ls = new LicenseServerClient();
  131. echo $ls->checkLicense($_REQUEST['user_id']);
  132. exit;
  133. } else if (isset($_GET['logout'])) {
  134. unset($_SESSION['attributes']);
  135. unset($_SESSION['userId']);
  136. header('Location: ' . $selfUrl);
  137. }
  138. ?>
  139. <!DOCTYPE html>
  140. <html>
  141. <head>
  142. <meta charset="utf-8" />
  143. <link href="main.css" type="text/css" rel="stylesheet" />
  144. <script type="text/javascript" src="popuplib.js"></script>
  145. <script type="text/html" id="ls_tmpl">
  146. <div id="access-level">
  147. <% if (result.toLowerCase() == 'yes') { %>
  148. This user has <span class="<%= accessLevel.toLowerCase() %>"><%= accessLevel %></span> access to this application ( appId: <%= appId %> )
  149. <% } else { %>
  150. This user has <span class="<%= result.toLowerCase() %>"><%= result %></span> access to this application ( appId: <%= appId %> )
  151. <% } %>
  152. </div>
  153. </script>
  154. </head>
  155. <body>
  156. <nav>
  157. <?php if (!isset($_SESSION['userId'])): ?>
  158. <a href="javascript:" onclick="openPopup(450, 500, this);">Sign in</a>
  159. <?php else: ?>
  160. <span>Welcome <?php echo @$_SESSION['attributes']['namePerson/first'] ?> <?php echo @$_SESSION['attributes']['namePerson/last'] ?> ( <?php echo $_SESSION['attributes']['contact/email'] ?> )</span>
  161. <a href="?logout">Sign out</a>
  162. <?php endif; ?>
  163. </nav>
  164. <?php if (isset($_SESSION['attributes'])): ?>
  165. <div id="container">
  166. <form action="<?php echo "$selfUrl?queryLicenseServer" ?>" onsubmit="return queryLicenseServer(this);">
  167. <input type="hidden" id="user_id" name="user_id" value="<?php echo $_SESSION['userId'] ?>" />
  168. <input type="submit" value="Check user's access" />
  169. </form>
  170. <div id="license-server-response"></div>
  171. </div>
  172. <?php endif; ?>
  173. <script>
  174. // Simple JavaScript Templating
  175. // John Resig - http://ejohn.org/ - MIT Licensed
  176. (function(){
  177. var cache = {};
  178. this.tmpl = function tmpl(str, data){
  179. // Figure out if we're getting a template, or if we need to
  180. // load the template - and be sure to cache the result.
  181. var fn = !/\W/.test(str) ?
  182. cache[str] = cache[str] ||
  183. tmpl(document.getElementById(str).innerHTML) :
  184. // Generate a reusable function that will serve as a template
  185. // generator (and which will be cached).
  186. new Function("obj",
  187. "var p=[],print=function(){p.push.apply(p,arguments);};" +
  188. // Introduce the data as local variables using with(){}
  189. "with(obj){p.push('" +
  190. // Convert the template into pure JavaScript
  191. str
  192. .replace(/[\r\t\n]/g, " ")
  193. .split("<%").join("\t")
  194. .replace(/((^|%>)[^\t]*)'/g, "$1\r")
  195. .replace(/\t=(.*?)%>/g, "',$1,'")
  196. .split("\t").join("');")
  197. .split("%>").join("p.push('")
  198. .split("\r").join("\\'")
  199. + "');}return p.join('');");
  200. // Provide some basic currying to the user
  201. return data ? fn( data ) : fn;
  202. };
  203. })();
  204. function queryLicenseServer(form) {
  205. var userId = form.user_id.value;
  206. if (!userId) {
  207. alert('No OpenID specified!');
  208. return false;
  209. }
  210. var req = new XMLHttpRequest();
  211. req.onreadystatechange = function(e) {
  212. if (this.readyState == 4) {
  213. var resp = JSON.parse(this.responseText);
  214. var el = document.getElementById('license-server-response');
  215. if (resp.error) {
  216. el.innerHTML = ['<div class="error">Error ', resp.error.code,
  217. ': ', resp.error.message, '</div>'].join('');
  218. } else {
  219. el.innerHTML = tmpl('ls_tmpl', resp);
  220. }
  221. }
  222. };
  223. var url =
  224. [form.action, '&user_id=', encodeURIComponent(userId)].join('');
  225. req.open('GET', url, true);
  226. req.send(null);
  227. return false;
  228. }
  229. function openPopup(w, h, link) {
  230. var extensions = {
  231. 'openid.ns.ext1': 'http://openid.net/srv/ax/1.0',
  232. 'openid.ext1.mode': 'fetch_request',
  233. 'openid.ext1.type.email': 'http://axschema.org/contact/email',
  234. 'openid.ext1.type.first': 'http://axschema.org/namePerson/first',
  235. 'openid.ext1.type.last': 'http://axschema.org/namePerson/last',
  236. 'openid.ext1.required': 'email,first,last',
  237. 'openid.ui.icon': 'true'
  238. };
  239. var googleOpener = popupManager.createPopupOpener({
  240. opEndpoint: 'https://www.google.com/accounts/o8/ud',
  241. returnToUrl: '<?php echo "$selfUrl?popup=true" ?>',
  242. onCloseHandler: function() {
  243. window.location = '<?php echo $selfUrl ?>';
  244. },
  245. shouldEncodeUrls: false,
  246. extensions: extensions
  247. });
  248. link.parentNode.appendChild(
  249. document.createTextNode('Authenticating...'));
  250. link.parentNode.removeChild(link);
  251. googleOpener.popup(w, h);
  252. }
  253. </script>
  254. </body>
  255. </html>