google_oauthcallback.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. <?php
  2. /*
  3. * Copyright (C) 2015 Frederic France <frederic.france@free.fr>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. // This page should make the process to login and get token as described here:
  19. // https://developers.google.com/identity/protocols/oauth2/openid-connect#server-flow
  20. /**
  21. * \file htdocs/core/modules/oauth/google_oauthcallback.php
  22. * \ingroup oauth
  23. * \brief Page to get oauth callback
  24. */
  25. require '../../../main.inc.php';
  26. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  27. use OAuth\Common\Storage\DoliStorage;
  28. use OAuth\Common\Consumer\Credentials;
  29. use OAuth\OAuth2\Service\Google;
  30. // Define $urlwithroot
  31. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  32. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  33. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  34. $action = GETPOST('action', 'aZ09');
  35. $backtourl = GETPOST('backtourl', 'alpha');
  36. /**
  37. * Create a new instance of the URI class with the current URI, stripping the query string
  38. */
  39. $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
  40. //$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
  41. //$currentUri->setQuery('');
  42. $currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/google_oauthcallback.php');
  43. /**
  44. * Load the credential for the service
  45. */
  46. /** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
  47. $serviceFactory = new \OAuth\ServiceFactory();
  48. $httpClient = new \OAuth\Common\Http\Client\CurlClient();
  49. // TODO Set options for proxy and timeout
  50. // $params=array('CURLXXX'=>value, ...)
  51. //$httpClient->setCurlParameters($params);
  52. $serviceFactory->setHttpClient($httpClient);
  53. // Dolibarr storage
  54. $storage = new DoliStorage($db, $conf);
  55. // Setup the credentials for the requests
  56. $credentials = new Credentials(
  57. $conf->global->OAUTH_GOOGLE_ID,
  58. $conf->global->OAUTH_GOOGLE_SECRET,
  59. $currentUri->getAbsoluteUri()
  60. );
  61. $state = GETPOST('state');
  62. $requestedpermissionsarray = array();
  63. if ($state) {
  64. // 'state' parameter is standard to store a hash value and can be used to retrieve some parameters back
  65. $statewithscopeonly = preg_replace('/\-.*$/', '', $state);
  66. $requestedpermissionsarray = explode(',', $statewithscopeonly); // Example: 'userinfo_email,userinfo_profile,openid,email,profile,cloud_print'.
  67. }
  68. if ($action != 'delete' && empty($requestedpermissionsarray)) {
  69. print 'Error, parameter state is not defined';
  70. exit;
  71. }
  72. //var_dump($requestedpermissionsarray);exit;
  73. // Instantiate the Api service using the credentials, http client and storage mechanism for the token
  74. // $requestedpermissionsarray contains list of scopes.
  75. // Conversion into URL is done by Reflection on constant with name SCOPE_scope_in_uppercase
  76. $apiService = $serviceFactory->createService('Google', $credentials, $storage, $requestedpermissionsarray);
  77. // access type needed to have oauth provider refreshing token
  78. // also note that a refresh token is sent only after a prompt
  79. $apiService->setAccessType('offline');
  80. $langs->load("oauth");
  81. /*
  82. * Actions
  83. */
  84. if ($action == 'delete') {
  85. $storage->clearToken('Google');
  86. setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
  87. header('Location: '.$backtourl);
  88. exit();
  89. }
  90. if (GETPOST('code')) { // We are coming from oauth provider page.
  91. dol_syslog("We are coming from the oauth provider page");
  92. // We must validate that the $state is the same than the one into $_SESSION['oauthstateanticsrf'], return error if not.
  93. if (isset($_SESSION['oauthstateanticsrf']) && $state != $_SESSION['oauthstateanticsrf']) {
  94. print 'Value for state = '.dol_escape_htmltag($state).' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
  95. unset($_SESSION['oauthstateanticsrf']);
  96. } else {
  97. // This was a callback request from service, get the token
  98. try {
  99. //var_dump($_GET['code']);
  100. //var_dump($state);
  101. //var_dump($apiService); // OAuth\OAuth2\Service\Google
  102. // This request the token
  103. // Result is stored into object managed by class DoliStorage into includes/OAuth/Common/Storage/DoliStorage.php, so into table llx_oauth_token
  104. $token = $apiService->requestAccessToken(GETPOST('code'), $state);
  105. // Note: The extraparams has the 'id_token' than contains a lot of information about the user.
  106. $extraparams = $token->getExtraParams();
  107. $jwt = explode('.', $extraparams['id_token']);
  108. // Extract the middle part, base64 decode, then json_decode it
  109. if (!empty($jwt[1])) {
  110. $userinfo = json_decode(base64_decode($jwt[1]), true);
  111. // TODO
  112. // We should make the 5 steps of validation of id_token
  113. // Verify that the ID token is properly signed by the issuer. Google-issued tokens are signed using one of the certificates found at the URI specified in the jwks_uri metadata value of the Discovery document.
  114. // Verify that the value of the iss claim in the ID token is equal to https://accounts.google.com or accounts.google.com.
  115. // Verify that the value of the aud claim in the ID token is equal to your app's client ID.
  116. // Verify that the expiry time (exp claim) of the ID token has not passed.
  117. // If you specified a hd parameter value in the request, verify that the ID token has a hd claim that matches an accepted G Suite hosted domain.
  118. /*
  119. $useremailuniq = $userinfo['sub'];
  120. $useremail = $userinfo['email'];
  121. $useremailverified = $userinfo['email_verified'];
  122. $username = $userinfo['name'];
  123. $userfamilyname = $userinfo['family_name'];
  124. $usergivenname = $userinfo['given_name'];
  125. $hd = $userinfo['hd'];
  126. */
  127. }
  128. setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs');
  129. $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
  130. unset($_SESSION["backtourlsavedbeforeoauthjump"]);
  131. header('Location: '.$backtourl);
  132. exit();
  133. } catch (Exception $e) {
  134. print $e->getMessage();
  135. }
  136. }
  137. } else {
  138. // If we enter this page without 'code' parameter, we arrive here. this is the case when we want to get the redirect
  139. // to the OAuth provider login page
  140. $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
  141. if (!preg_match('/^forlogin/', $state)) {
  142. $apiService->setApprouvalPrompt('force');
  143. }
  144. // This may create record into oauth_state before the header redirect.
  145. // Creation of record with state in this tables depend on the Provider used (see its constructor).
  146. if ($state) {
  147. $url = $apiService->getAuthorizationUri(array('state' => $state));
  148. } else {
  149. $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
  150. }
  151. // Add more param
  152. $url .= '&nonce='.bin2hex(random_bytes(64/8));
  153. // TODO Add param hd and/or login_hint
  154. if (!preg_match('/^forlogin/', $state)) {
  155. //$url .= 'hd=xxx';
  156. }
  157. // we go on oauth provider authorization page
  158. header('Location: '.$url);
  159. exit();
  160. }
  161. /*
  162. * View
  163. */
  164. // No view at all, just actions, so we never reach this line.
  165. $db->close();