google_oauthcallback.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 is used as callback for token generation of an OAUTH request.
  19. // This page can also be used to make the process to login and get token as described here:
  20. // https://developers.google.com/identity/protocols/oauth2/openid-connect#server-flow
  21. /**
  22. * \file htdocs/core/modules/oauth/google_oauthcallback.php
  23. * \ingroup oauth
  24. * \brief Page to get oauth callback
  25. */
  26. // Force keyforprovider
  27. $forlogin = 0;
  28. if (!empty($_GET['state']) && preg_match('/^forlogin-/', $_GET['state'])) {
  29. $forlogin = 1;
  30. $_GET['keyforprovider'] = 'Login';
  31. }
  32. if (!defined('NOLOGIN') && $forlogin) {
  33. define("NOLOGIN", 1); // This means this output page does not require to be logged.
  34. }
  35. // Load Dolibarr environment
  36. require '../../../main.inc.php';
  37. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  38. use OAuth\Common\Storage\DoliStorage;
  39. use OAuth\Common\Consumer\Credentials;
  40. use OAuth\OAuth2\Service\Google;
  41. // Define $urlwithroot
  42. global $dolibarr_main_url_root;
  43. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  44. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  45. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  46. $langs->load("oauth");
  47. $action = GETPOST('action', 'aZ09');
  48. $backtourl = GETPOST('backtourl', 'alpha');
  49. $keyforprovider = GETPOST('keyforprovider', 'aZ09');
  50. if (!GETPOSTISSET('keyforprovider') && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
  51. // If we are coming from the Oauth page
  52. $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
  53. }
  54. /**
  55. * Create a new instance of the URI class with the current URI, stripping the query string
  56. */
  57. $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
  58. //$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
  59. //$currentUri->setQuery('');
  60. $currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/google_oauthcallback.php');
  61. /**
  62. * Load the credential for the service
  63. */
  64. /** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
  65. $serviceFactory = new \OAuth\ServiceFactory();
  66. $httpClient = new \OAuth\Common\Http\Client\CurlClient();
  67. // TODO Set options for proxy and timeout
  68. // $params=array('CURLXXX'=>value, ...)
  69. //$httpClient->setCurlParameters($params);
  70. $serviceFactory->setHttpClient($httpClient);
  71. // Setup the credentials for the requests
  72. $keyforparamid = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
  73. $keyforparamsecret = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
  74. $credentials = new Credentials(
  75. getDolGlobalString($keyforparamid),
  76. getDolGlobalString($keyforparamsecret),
  77. $currentUri->getAbsoluteUri()
  78. );
  79. $state = GETPOST('state');
  80. $statewithscopeonly = '';
  81. $statewithanticsrfonly = '';
  82. $requestedpermissionsarray = array();
  83. if ($state) {
  84. // 'state' parameter is standard to store a hash value and can be used to retrieve some parameters back
  85. $statewithscopeonly = preg_replace('/\-.*$/', '', preg_replace('/^forlogin-/', '', $state));
  86. $requestedpermissionsarray = explode(',', $statewithscopeonly); // Example: 'userinfo_email,userinfo_profile,openid,email,profile,cloud_print'.
  87. $statewithanticsrfonly = preg_replace('/^.*\-/', '', $state);
  88. }
  89. if ($action != 'delete' && (empty($statewithscopeonly) || empty($requestedpermissionsarray))) {
  90. setEventMessages($langs->trans('ScopeUndefined'), null, 'errors');
  91. header('Location: '.$backtourl);
  92. exit();
  93. }
  94. //var_dump($requestedpermissionsarray);exit;
  95. // Dolibarr storage
  96. $storage = new DoliStorage($db, $conf, $keyforprovider);
  97. // Instantiate the Api service using the credentials, http client and storage mechanism for the token
  98. // $requestedpermissionsarray contains list of scopes.
  99. // Conversion into URL is done by Reflection on constant with name SCOPE_scope_in_uppercase
  100. $apiService = $serviceFactory->createService('Google', $credentials, $storage, $requestedpermissionsarray);
  101. // access type needed to have oauth provider refreshing token
  102. // also note that a refresh token is sent only after a prompt
  103. $apiService->setAccessType('offline');
  104. if (!getDolGlobalString($keyforparamid)) {
  105. accessforbidden('Setup of service '.$keyforparamid.' is not complete. Customer ID is missing');
  106. }
  107. if (!getDolGlobalString($keyforparamsecret)) {
  108. accessforbidden('Setup of service '.$keyforparamid.' is not complete. Secret key is missing');
  109. }
  110. /*
  111. * Actions
  112. */
  113. if ($action == 'delete') {
  114. $storage->clearToken('Google');
  115. setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
  116. header('Location: '.$backtourl);
  117. exit();
  118. }
  119. if (!GETPOST('code')) {
  120. // If we enter this page without 'code' parameter, it means we click on the link from login page and we want to get the redirect
  121. // to the OAuth provider login page.
  122. $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
  123. $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
  124. $_SESSION['oauthstateanticsrf'] = $state;
  125. // Save more data into session
  126. // Not required. All data are savec into $_SESSION['datafromloginform'] when form is posted with a click on Login with
  127. // Google with param actionlogin=login and beforeoauthloginredirect=1, by the functions_googleoauth.php.
  128. /*
  129. if (!empty($_POST["tz"])) {
  130. $_SESSION["tz"] = $_POST["tz"];
  131. }
  132. if (!empty($_POST["tz_string"])) {
  133. $_SESSION["tz_string"] = $_POST["tz_string"];
  134. }
  135. if (!empty($_POST["dst_first"])) {
  136. $_SESSION["dst_first"] = $_POST["dst_first"];
  137. }
  138. if (!empty($_POST["dst_second"])) {
  139. $_SESSION["dst_second"] = $_POST["dst_second"];
  140. }
  141. */
  142. if ($forlogin) {
  143. $apiService->setApprouvalPrompt('force');
  144. }
  145. // This may create record into oauth_state before the header redirect.
  146. // Creation of record with state in this tables depend on the Provider used (see its constructor).
  147. if ($state) {
  148. $url = $apiService->getAuthorizationUri(array('state' => $state));
  149. } else {
  150. $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
  151. }
  152. // The redirect_uri is included into this $url
  153. // Add more param
  154. $url .= '&nonce='.bin2hex(random_bytes(64/8));
  155. if ($forlogin) {
  156. // TODO Add param hd. What is it for ?
  157. //$url .= 'hd=xxx';
  158. if (GETPOST('username')) {
  159. $url .= '&login_hint='.urlencode(GETPOST('username'));
  160. }
  161. // Check that the redirect_uri that wil be used is same than url of current domain
  162. // Define $urlwithroot
  163. global $dolibarr_main_url_root;
  164. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  165. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  166. //$urlwithroot = DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  167. include DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
  168. $currentrooturl = getRootURLFromURL(DOL_MAIN_URL_ROOT);
  169. $externalrooturl = getRootURLFromURL($urlwithroot);
  170. if ($currentrooturl != $externalrooturl) {
  171. $langs->load("errors");
  172. setEventMessages($langs->trans("ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup", $currentrooturl, $externalrooturl), null, 'errors');
  173. $url = DOL_URL_ROOT;
  174. }
  175. }
  176. // we go on oauth provider authorization page
  177. header('Location: '.$url);
  178. exit();
  179. } else {
  180. // We are coming from the return of an OAuth2 provider page.
  181. dol_syslog("We are coming from the oauth provider page keyforprovider=".$keyforprovider." code=".dol_trunc(GETPOST('code'), 5));
  182. // We must validate that the $state is the same than the one into $_SESSION['oauthstateanticsrf'], return error if not.
  183. if (isset($_SESSION['oauthstateanticsrf']) && $state != $_SESSION['oauthstateanticsrf']) {
  184. //var_dump($_SESSION['oauthstateanticsrf']);exit;
  185. print 'Value for state='.dol_escape_htmltag($state).' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
  186. unset($_SESSION['oauthstateanticsrf']);
  187. } else {
  188. // This was a callback request from service, get the token
  189. try {
  190. //var_dump($state);
  191. //var_dump($apiService); // OAuth\OAuth2\Service\Google
  192. //dol_syslog("_GET=".var_export($_GET, true));
  193. $errorincheck = 0;
  194. $db->begin();
  195. // This requests the token from the received OAuth code (call of the https://oauth2.googleapis.com/token endpoint)
  196. // Result is stored into object managed by class DoliStorage into includes/OAuth/Common/Storage/DoliStorage.php, so into table llx_oauth_token
  197. $token = $apiService->requestAccessToken(GETPOST('code'), $state);
  198. // Note: The extraparams has the 'id_token' than contains a lot of information about the user.
  199. $extraparams = $token->getExtraParams();
  200. $jwt = explode('.', $extraparams['id_token']);
  201. $username = '';
  202. $useremail = '';
  203. // Extract the middle part, base64 decode, then json_decode it
  204. if (!empty($jwt[1])) {
  205. $userinfo = json_decode(base64_decode($jwt[1]), true);
  206. dol_syslog("userinfo=".var_export($userinfo, true));
  207. $useremail = $userinfo['email'];
  208. /*
  209. $useremailverified = $userinfo['email_verified'];
  210. $useremailuniq = $userinfo['sub'];
  211. $username = $userinfo['name'];
  212. $userfamilyname = $userinfo['family_name'];
  213. $usergivenname = $userinfo['given_name'];
  214. $hd = $userinfo['hd'];
  215. */
  216. // We should make the steps of validation of id_token
  217. // Verify that the state is the one expected
  218. // TODO
  219. // 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.
  220. // TODO
  221. // Verify that the value of the iss claim in the ID token is equal to https://accounts.google.com or accounts.google.com.
  222. if ($userinfo['iss'] != 'accounts.google.com' && $userinfo['iss'] != 'https://accounts.google.com') {
  223. setEventMessages($langs->trans('Bad value for returned userinfo[iss]'), null, 'errors');
  224. $errorincheck++;
  225. }
  226. // Verify that the value of the aud claim in the ID token is equal to your app's client ID.
  227. if ($userinfo['aud'] != getDolGlobalString($keyforparamid)) {
  228. setEventMessages($langs->trans('Bad value for returned userinfo[aud]'), null, 'errors');
  229. $errorincheck++;
  230. }
  231. // Verify that the expiry time (exp claim) of the ID token has not passed.
  232. if ($userinfo['exp'] <= dol_now()) {
  233. setEventMessages($langs->trans('Bad value for returned userinfo[exp]. Token expired.'), null, 'errors');
  234. $errorincheck++;
  235. }
  236. // 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.
  237. // TODO
  238. }
  239. if (!$errorincheck) {
  240. // If call back to url for a OAUTH2 login
  241. if ($forlogin) {
  242. dol_syslog("we received the login/email to log to, it is ".$useremail);
  243. $tmparray = (empty($_SESSION['datafromloginform']) ? array() : $_SESSION['datafromloginform']);
  244. $entitytosearchuser = (isset($tmparray['entity']) ? $tmparray['entity'] : -1);
  245. // Delete the token
  246. $storage->clearToken('Google');
  247. $tmpuser = new User($db);
  248. $res = $tmpuser->fetch(0, '', '', 0, $entitytosearchuser, $useremail);
  249. if ($res > 0) {
  250. $username = $tmpuser->login;
  251. $_SESSION['googleoauth_receivedlogin'] = dol_hash($conf->file->instance_unique_id.$username, '0');
  252. dol_syslog('$_SESSION[\'googleoauth_receivedlogin\']='.$_SESSION['googleoauth_receivedlogin']);
  253. } else {
  254. $errormessage = "Failed to login using Google. User with the Email '".$useremail."' was not found";
  255. if ($entitytosearchuser > 0) {
  256. $errormessage .= ' ('.$langs->trans("Entity").' '.$entitytosearchuser.')';
  257. }
  258. $_SESSION["dol_loginmesg"] = $errormessage;
  259. $errorincheck++;
  260. }
  261. }
  262. } else {
  263. // If call back to url for a OAUTH2 login
  264. if ($forlogin) {
  265. $_SESSION["dol_loginmesg"] = "Failed to login using Google. OAuth callback URL retreives a token with non valid data";
  266. $errorincheck++;
  267. }
  268. }
  269. if (!$errorincheck) {
  270. $db->commit();
  271. } else {
  272. $db->rollback();
  273. }
  274. $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
  275. unset($_SESSION["backtourlsavedbeforeoauthjump"]);
  276. if (empty($backtourl)) {
  277. $backtourl = DOL_URL_ROOT;
  278. }
  279. // If call back to url for a OAUTH2 login
  280. if ($forlogin) {
  281. $backtourl .= '?actionlogin=login&afteroauthloginreturn=1'.($username ? '&username='.urlencode($username) : '').'&token='.newToken();
  282. if (!empty($tmparray['entity'])) {
  283. $backtourl .= '&entity='.$tmparray['entity'];
  284. }
  285. }
  286. dol_syslog("Redirect now on backtourl=".$backtourl);
  287. header('Location: '.$backtourl);
  288. exit();
  289. } catch (Exception $e) {
  290. print $e->getMessage();
  291. }
  292. }
  293. }
  294. /*
  295. * View
  296. */
  297. // No view at all, just actions, so we reach this line only on error.
  298. $db->close();