generic_oauthcallback.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. /**
  19. * \file htdocs/core/modules/oauth/generic_oauthcallback.php
  20. * \ingroup oauth
  21. * \brief Page to get oauth callback
  22. */
  23. // Load Dolibarr environment
  24. require '../../../main.inc.php';
  25. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  26. use OAuth\Common\Storage\DoliStorage;
  27. use OAuth\Common\Consumer\Credentials;
  28. use OAuth\OAuth2\Service\GitHub;
  29. // Define $urlwithroot
  30. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  31. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  32. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  33. $action = GETPOST('action', 'aZ09');
  34. $backtourl = GETPOST('backtourl', 'alpha');
  35. $keyforprovider = GETPOST('keyforprovider', 'aZ09');
  36. if (empty($keyforprovider) && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
  37. $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
  38. }
  39. $genericstring = 'OTHER';
  40. /**
  41. * Create a new instance of the URI class with the current URI, stripping the query string
  42. */
  43. $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
  44. //$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
  45. //$currentUri->setQuery('');
  46. $currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/generic_oauthcallback.php');
  47. /**
  48. * Load the credential for the service
  49. */
  50. /** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
  51. $serviceFactory = new \OAuth\ServiceFactory();
  52. $httpClient = new \OAuth\Common\Http\Client\CurlClient();
  53. // TODO Set options for proxy and timeout
  54. // $params=array('CURLXXX'=>value, ...)
  55. //$httpClient->setCurlParameters($params);
  56. $serviceFactory->setHttpClient($httpClient);
  57. // Dolibarr storage
  58. $storage = new DoliStorage($db, $conf, $keyforprovider);
  59. // Setup the credentials for the requests
  60. $keyforparamid = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
  61. $keyforparamsecret = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
  62. $credentials = new Credentials(
  63. getDolGlobalString($keyforparamid),
  64. getDolGlobalString($keyforparamsecret),
  65. $currentUri->getAbsoluteUri()
  66. );
  67. $state = GETPOST('state');
  68. $requestedpermissionsarray = array();
  69. if ($state) {
  70. $requestedpermissionsarray = explode(',', $state); // Example: 'user'. 'state' parameter is standard to retrieve some parameters back
  71. }
  72. if ($action != 'delete' && empty($requestedpermissionsarray)) {
  73. print 'Error, parameter state is not defined';
  74. exit;
  75. }
  76. //var_dump($requestedpermissionsarray);exit;
  77. // Instantiate the Api service using the credentials, http client and storage mechanism for the token
  78. // ucfirst(strtolower($genericstring)) must be the name of a class into OAuth/OAuth2/Services/Xxxx
  79. $apiService = $serviceFactory->createService(ucfirst(strtolower($genericstring)), $credentials, $storage, $requestedpermissionsarray);
  80. /*
  81. var_dump($genericstring.($keyforprovider ? '-'.$keyforprovider : ''));
  82. var_dump($credentials);
  83. var_dump($storage);
  84. var_dump($requestedpermissionsarray);
  85. */
  86. if (empty($apiService)) {
  87. print 'Error, failed to create serviceFactory';
  88. exit;
  89. }
  90. // access type needed to have oauth provider refreshing token
  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($genericstring);
  104. setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
  105. header('Location: '.$backtourl);
  106. exit();
  107. }
  108. if (GETPOST('code') || GETPOST('error')) { // We are coming from oauth provider page
  109. // We should have
  110. //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
  111. dol_syslog("We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5)." error=".GETPOST('error'));
  112. // This was a callback request from service, get the token
  113. try {
  114. //var_dump($state);
  115. //var_dump($apiService); // OAuth\OAuth2\Service\Xxx
  116. if (GETPOST('error')) {
  117. setEventMessages(GETPOST('error').' '.GETPOST('error_description'), null, 'errors');
  118. } else {
  119. //$token = $apiService->requestAccessToken(GETPOST('code'), $state);
  120. $token = $apiService->requestAccessToken(GETPOST('code'));
  121. setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
  122. }
  123. $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
  124. unset($_SESSION["backtourlsavedbeforeoauthjump"]);
  125. header('Location: '.$backtourl);
  126. exit();
  127. } catch (Exception $e) {
  128. print $e->getMessage();
  129. }
  130. } else {
  131. // If we enter this page without 'code' parameter, we arrive here. This is the case when we want to get the redirect
  132. // to the OAuth provider login page.
  133. $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
  134. $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
  135. $_SESSION['oauthstateanticsrf'] = $state;
  136. // This may create record into oauth_state before the header redirect.
  137. // Creation of record with state in this tables depend on the Provider used (see its constructor).
  138. if ($state) {
  139. $url = $apiService->getAuthorizationUri(array('state' => $state));
  140. } else {
  141. $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
  142. }
  143. // we go on oauth provider authorization page
  144. header('Location: '.$url);
  145. exit();
  146. }
  147. /*
  148. * View
  149. */
  150. // No view at all, just actions
  151. $db->close();