github_oauthcallback.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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/github_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. /**
  40. * Create a new instance of the URI class with the current URI, stripping the query string
  41. */
  42. $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
  43. //$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
  44. //$currentUri->setQuery('');
  45. $currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/github_oauthcallback.php');
  46. /**
  47. * Load the credential for the service
  48. */
  49. /** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
  50. $serviceFactory = new \OAuth\ServiceFactory();
  51. $httpClient = new \OAuth\Common\Http\Client\CurlClient();
  52. // TODO Set options for proxy and timeout
  53. // $params=array('CURLXXX'=>value, ...)
  54. //$httpClient->setCurlParameters($params);
  55. $serviceFactory->setHttpClient($httpClient);
  56. // Dolibarr storage
  57. $storage = new DoliStorage($db, $conf, $keyforprovider);
  58. // Setup the credentials for the requests
  59. $keyforparamid = 'OAUTH_GITHUB'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
  60. $keyforparamsecret = 'OAUTH_GITHUB'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
  61. $credentials = new Credentials(
  62. getDolGlobalString($keyforparamid),
  63. getDolGlobalString($keyforparamsecret),
  64. $currentUri->getAbsoluteUri()
  65. );
  66. $requestedpermissionsarray = array();
  67. if (GETPOST('state')) {
  68. $requestedpermissionsarray = explode(',', GETPOST('state')); // Example: 'user'. 'state' parameter is standard to retrieve some parameters back
  69. }
  70. if ($action != 'delete' && empty($requestedpermissionsarray)) {
  71. print 'Error, parameter state is not defined';
  72. exit;
  73. }
  74. //var_dump($requestedpermissionsarray);exit;
  75. // Instantiate the Api service using the credentials, http client and storage mechanism for the token
  76. $apiService = $serviceFactory->createService('GitHub', $credentials, $storage, $requestedpermissionsarray);
  77. // access type needed to have oauth provider refreshing token
  78. //$apiService->setAccessType('offline');
  79. $langs->load("oauth");
  80. if (!getDolGlobalString($keyforparamid)) {
  81. accessforbidden('Setup of service is not complete. Customer ID is missing');
  82. }
  83. if (!getDolGlobalString($keyforparamsecret)) {
  84. accessforbidden('Setup of service is not complete. Secret key is missing');
  85. }
  86. /*
  87. * Actions
  88. */
  89. if ($action == 'delete') {
  90. $storage->clearToken('GitHub');
  91. setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
  92. header('Location: '.$backtourl);
  93. exit();
  94. }
  95. if (GETPOST('code')) { // We are coming from oauth provider page
  96. // We should have
  97. //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
  98. dol_syslog("We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5));
  99. // This was a callback request from service, get the token
  100. try {
  101. //var_dump($state);
  102. //var_dump($apiService); // OAuth\OAuth2\Service\GitHub
  103. //$token = $apiService->requestAccessToken(GETPOST('code'), $state);
  104. $token = $apiService->requestAccessToken(GETPOST('code'));
  105. // Github is a service that does not need state to be stored as second paramater of requestAccessToken
  106. // Into constructor of GitHub, the call
  107. // parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri)
  108. // has not the ending parameter to true like the Google class constructor.
  109. setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
  110. $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
  111. unset($_SESSION["backtourlsavedbeforeoauthjump"]);
  112. header('Location: '.$backtourl);
  113. exit();
  114. } catch (Exception $e) {
  115. print $e->getMessage();
  116. }
  117. } else { // If entry on page with no parameter, we arrive here
  118. $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
  119. $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
  120. $_SESSION['oauthstateanticsrf'] = $state;
  121. // This may create record into oauth_state before the header redirect.
  122. // Creation of record with state in this tables depend on the Provider used (see its constructor).
  123. if (GETPOST('state')) {
  124. $url = $apiService->getAuthorizationUri(array('state' => GETPOST('state')));
  125. } else {
  126. $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
  127. }
  128. // we go on oauth provider authorization page
  129. header('Location: '.$url);
  130. exit();
  131. }
  132. /*
  133. * View
  134. */
  135. // No view at all, just actions
  136. $db->close();