google_oauthcallback.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. /* Copyright (C) 2022 Laurent Destailleur <eldy@users.sourceforge.net>
  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. // Load Dolibarr environment
  26. require '../../../main.inc.php';
  27. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  28. use OAuth\Common\Storage\DoliStorage;
  29. use OAuth\Common\Consumer\Credentials;
  30. use OAuth\OAuth2\Service\Google;
  31. // Define $urlwithroot
  32. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  33. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  34. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  35. $action = GETPOST('action', 'aZ09');
  36. $backtourl = GETPOST('backtourl', 'alpha');
  37. $keyforprovider = GETPOST('keyforprovider', 'aZ09');
  38. if (!GETPOSTISSET('keyforprovider') && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
  39. // If we are coming from the Oauth page
  40. $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
  41. }
  42. /**
  43. * Create a new instance of the URI class with the current URI, stripping the query string
  44. */
  45. $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
  46. //$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
  47. //$currentUri->setQuery('');
  48. $currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/google_oauthcallback.php');
  49. /**
  50. * Load the credential for the service
  51. */
  52. /** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
  53. $serviceFactory = new \OAuth\ServiceFactory();
  54. $httpClient = new \OAuth\Common\Http\Client\CurlClient();
  55. // TODO Set options for proxy and timeout
  56. // $params=array('CURLXXX'=>value, ...)
  57. //$httpClient->setCurlParameters($params);
  58. $serviceFactory->setHttpClient($httpClient);
  59. // Setup the credentials for the requests
  60. $keyforparamid = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
  61. $keyforparamsecret = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
  62. $credentials = new Credentials(
  63. getDolGlobalString($keyforparamid),
  64. getDolGlobalString($keyforparamsecret),
  65. $currentUri->getAbsoluteUri()
  66. );
  67. $state = GETPOST('state');
  68. $statewithscopeonly = '';
  69. $statewithanticsrfonly = '';
  70. $requestedpermissionsarray = array();
  71. if ($state) {
  72. // 'state' parameter is standard to store a hash value and can be used to retrieve some parameters back
  73. $statewithscopeonly = preg_replace('/\-.*$/', '', $state);
  74. $requestedpermissionsarray = explode(',', $statewithscopeonly); // Example: 'userinfo_email,userinfo_profile,openid,email,profile,cloud_print'.
  75. $statewithanticsrfonly = preg_replace('/^.*\-/', '', $state);
  76. }
  77. if ($action != 'delete' && (empty($statewithscopeonly) || empty($requestedpermissionsarray))) {
  78. setEventMessages($langs->trans('ScopeUndefined'), null, 'errors');
  79. header('Location: '.$backtourl);
  80. exit();
  81. }
  82. //var_dump($requestedpermissionsarray);exit;
  83. // Dolibarr storage
  84. $storage = new DoliStorage($db, $conf, $keyforprovider);
  85. // Instantiate the Api service using the credentials, http client and storage mechanism for the token
  86. // $requestedpermissionsarray contains list of scopes.
  87. // Conversion into URL is done by Reflection on constant with name SCOPE_scope_in_uppercase
  88. $apiService = $serviceFactory->createService('Google', $credentials, $storage, $requestedpermissionsarray);
  89. // access type needed to have oauth provider refreshing token
  90. // also note that a refresh token is sent only after a prompt
  91. $apiService->setAccessType('offline');
  92. $langs->load("oauth");
  93. if (!getDolGlobalString($keyforparamid)) {
  94. accessforbidden('Setup of service is not complete. Customer ID is missing');
  95. }
  96. if (!getDolGlobalString($keyforparamsecret)) {
  97. accessforbidden('Setup of service is not complete. Secret key is missing');
  98. }
  99. /*
  100. * Actions
  101. */
  102. if ($action == 'delete') {
  103. $storage->clearToken('Google');
  104. setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
  105. header('Location: '.$backtourl);
  106. exit();
  107. }
  108. if (GETPOST('code')) { // We are coming from oauth provider page.
  109. dol_syslog("We are coming from the oauth provider page keyforprovider=".$keyforprovider." code=".dol_trunc(GETPOST('code'), 5));
  110. // We must validate that the $state is the same than the one into $_SESSION['oauthstateanticsrf'], return error if not.
  111. if (isset($_SESSION['oauthstateanticsrf']) && $state != $_SESSION['oauthstateanticsrf']) {
  112. print 'Value for state = '.dol_escape_htmltag($state).' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
  113. unset($_SESSION['oauthstateanticsrf']);
  114. } else {
  115. // This was a callback request from service, get the token
  116. try {
  117. //var_dump($state);
  118. //var_dump($apiService); // OAuth\OAuth2\Service\Google
  119. // This request the token
  120. // Result is stored into object managed by class DoliStorage into includes/OAuth/Common/Storage/DoliStorage.php, so into table llx_oauth_token
  121. $token = $apiService->requestAccessToken(GETPOST('code'), $state);
  122. // Note: The extraparams has the 'id_token' than contains a lot of information about the user.
  123. $extraparams = $token->getExtraParams();
  124. $jwt = explode('.', $extraparams['id_token']);
  125. // Extract the middle part, base64 decode, then json_decode it
  126. if (!empty($jwt[1])) {
  127. $userinfo = json_decode(base64_decode($jwt[1]), true);
  128. // TODO
  129. // We should make the 5 steps of validation of id_token
  130. // 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.
  131. // Verify that the value of the iss claim in the ID token is equal to https://accounts.google.com or accounts.google.com.
  132. // Verify that the value of the aud claim in the ID token is equal to your app's client ID.
  133. // Verify that the expiry time (exp claim) of the ID token has not passed.
  134. // 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.
  135. /*
  136. $useremailuniq = $userinfo['sub'];
  137. $useremail = $userinfo['email'];
  138. $useremailverified = $userinfo['email_verified'];
  139. $username = $userinfo['name'];
  140. $userfamilyname = $userinfo['family_name'];
  141. $usergivenname = $userinfo['given_name'];
  142. $hd = $userinfo['hd'];
  143. */
  144. }
  145. setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs');
  146. $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
  147. unset($_SESSION["backtourlsavedbeforeoauthjump"]);
  148. header('Location: '.$backtourl);
  149. exit();
  150. } catch (Exception $e) {
  151. print $e->getMessage();
  152. }
  153. }
  154. } else {
  155. // If we enter this page without 'code' parameter, we arrive here. This is the case when we want to get the redirect
  156. // to the OAuth provider login page.
  157. $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
  158. $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
  159. $_SESSION['oauthstateanticsrf'] = $state;
  160. if (!preg_match('/^forlogin/', $state)) {
  161. $apiService->setApprouvalPrompt('force');
  162. }
  163. // This may create record into oauth_state before the header redirect.
  164. // Creation of record with state in this tables depend on the Provider used (see its constructor).
  165. if ($state) {
  166. $url = $apiService->getAuthorizationUri(array('state' => $state));
  167. } else {
  168. $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
  169. }
  170. // Add more param
  171. $url .= '&nonce='.bin2hex(random_bytes(64/8));
  172. // TODO Add param hd and/or login_hint
  173. if (!preg_match('/^forlogin/', $state)) {
  174. //$url .= 'hd=xxx';
  175. }
  176. //var_dump($url);exit;
  177. // we go on oauth provider authorization page
  178. header('Location: '.$url);
  179. exit();
  180. }
  181. /*
  182. * View
  183. */
  184. // No view at all, just actions, so we never reach this line.
  185. $db->close();