dolibarr  19.0.0-dev
google_oauthcallback.php
Go to the documentation of this file.
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 // This page is used as callback for token generation of an OAUTH request.
20 // This page can also be used to make the process to login and get token as described here:
21 // https://developers.google.com/identity/protocols/oauth2/openid-connect#server-flow
22 
29 // Force keyforprovider
30 $forlogin = 0;
31 if (!empty($_GET['state']) && preg_match('/^forlogin-/', $_GET['state'])) {
32  $forlogin = 1;
33  $_GET['keyforprovider'] = 'Login';
34 }
35 
36 if (!defined('NOLOGIN') && $forlogin) {
37  define("NOLOGIN", 1); // This means this output page does not require to be logged.
38 }
39 
40 // Load Dolibarr environment
41 require '../../../main.inc.php';
42 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
43 use OAuth\Common\Storage\DoliStorage;
44 use OAuth\Common\Consumer\Credentials;
45 use OAuth\OAuth2\Service\Google;
46 
47 // Define $urlwithroot
48 global $dolibarr_main_url_root;
49 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
50 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
51 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
52 
53 $langs->load("oauth");
54 
55 $action = GETPOST('action', 'aZ09');
56 $backtourl = GETPOST('backtourl', 'alpha');
57 $keyforprovider = GETPOST('keyforprovider', 'aZ09');
58 if (!GETPOSTISSET('keyforprovider') && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
59  // If we are coming from the Oauth page
60  $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
61 }
62 
63 
67 $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
68 //$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
69 //$currentUri->setQuery('');
70 $currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/google_oauthcallback.php');
71 
72 
78 $serviceFactory = new \OAuth\ServiceFactory();
79 $httpClient = new \OAuth\Common\Http\Client\CurlClient();
80 // TODO Set options for proxy and timeout
81 // $params=array('CURLXXX'=>value, ...)
82 //$httpClient->setCurlParameters($params);
83 $serviceFactory->setHttpClient($httpClient);
84 
85 // Setup the credentials for the requests
86 $keyforparamid = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
87 $keyforparamsecret = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
88 $credentials = new Credentials(
89  getDolGlobalString($keyforparamid),
90  getDolGlobalString($keyforparamsecret),
91  $currentUri->getAbsoluteUri()
92 );
93 
94 $state = GETPOST('state');
95 $statewithscopeonly = '';
96 $statewithanticsrfonly = '';
97 
98 $requestedpermissionsarray = array();
99 if ($state) {
100  // 'state' parameter is standard to store a hash value and can be used to retrieve some parameters back
101  $statewithscopeonly = preg_replace('/\-.*$/', '', preg_replace('/^forlogin-/', '', $state));
102  $requestedpermissionsarray = explode(',', $statewithscopeonly); // Example: 'userinfo_email,userinfo_profile,openid,email,profile,cloud_print'.
103  $statewithanticsrfonly = preg_replace('/^.*\-/', '', $state);
104 }
105 
106 // Add a test to check that the state parameter is provided into URL when we make the first call to ask the redirect or when we receive the callback
107 // but not when callback was ok and we recall the page
108 if ($action != 'delete' && !GETPOST('afteroauthloginreturn', 'int') && (empty($statewithscopeonly) || empty($requestedpermissionsarray))) {
109  dol_syslog("state or statewithscopeonly and/or requestedpermissionsarray are empty");
110  setEventMessages($langs->trans('ScopeUndefined'), null, 'errors');
111  if (empty($backtourl)) {
112  $backtourl = DOL_URL_ROOT.'/';
113  }
114  header('Location: '.$backtourl);
115  exit();
116 }
117 
118 //var_dump($requestedpermissionsarray);exit;
119 
120 
121 // Dolibarr storage
122 $storage = new DoliStorage($db, $conf, $keyforprovider);
123 
124 // Instantiate the Api service using the credentials, http client and storage mechanism for the token
125 // $requestedpermissionsarray contains list of scopes.
126 // Conversion into URL is done by Reflection on constant with name SCOPE_scope_in_uppercase
127 $apiService = $serviceFactory->createService('Google', $credentials, $storage, $requestedpermissionsarray);
128 
129 // access type needed to have oauth provider refreshing token
130 // also note that a refresh token is sent only after a prompt
131 $apiService->setAccessType('offline');
132 
133 
134 if (!getDolGlobalString($keyforparamid)) {
135  accessforbidden('Setup of service '.$keyforparamid.' is not complete. Customer ID is missing');
136 }
137 if (!getDolGlobalString($keyforparamsecret)) {
138  accessforbidden('Setup of service '.$keyforparamid.' is not complete. Secret key is missing');
139 }
140 
141 
142 /*
143  * Actions
144  */
145 
146 if ($action == 'delete') {
147  $storage->clearToken('Google');
148 
149  setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
150 
151  header('Location: '.$backtourl);
152  exit();
153 }
154 
155 if (!GETPOST('code')) {
156  dol_syslog("Page is called without code parameter defined");
157 
158  // 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
159  // to the OAuth provider login page.
160  $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
161  $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
162  $_SESSION['oauthstateanticsrf'] = $state;
163 
164  // Save more data into session
165  // Not required. All data are savec into $_SESSION['datafromloginform'] when form is posted with a click on Login with
166  // Google with param actionlogin=login and beforeoauthloginredirect=1, by the functions_googleoauth.php.
167  /*
168  if (!empty($_POST["tz"])) {
169  $_SESSION["tz"] = $_POST["tz"];
170  }
171  if (!empty($_POST["tz_string"])) {
172  $_SESSION["tz_string"] = $_POST["tz_string"];
173  }
174  if (!empty($_POST["dst_first"])) {
175  $_SESSION["dst_first"] = $_POST["dst_first"];
176  }
177  if (!empty($_POST["dst_second"])) {
178  $_SESSION["dst_second"] = $_POST["dst_second"];
179  }
180  */
181 
182  if ($forlogin) {
183  $apiService->setApprouvalPrompt('force');
184  }
185 
186  // This may create record into oauth_state before the header redirect.
187  // Creation of record with state in this tables depend on the Provider used (see its constructor).
188  if ($state) {
189  $url = $apiService->getAuthorizationUri(array('state' => $state));
190  } else {
191  $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
192  }
193  // The redirect_uri is included into this $url
194 
195  // Add more param
196  $url .= '&nonce='.bin2hex(random_bytes(64/8));
197 
198  if ($forlogin) {
199  // TODO Add param hd. What is it for ?
200  //$url .= 'hd=xxx';
201 
202  if (GETPOST('username')) {
203  $url .= '&login_hint='.urlencode(GETPOST('username'));
204  }
205 
206  // Check that the redirect_uri that wil be used is same than url of current domain
207 
208  // Define $urlwithroot
209  global $dolibarr_main_url_root;
210  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
211  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
212  //$urlwithroot = DOL_MAIN_URL_ROOT; // This is to use same domain name than current
213 
214  include DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
215  $currentrooturl = getRootURLFromURL(DOL_MAIN_URL_ROOT);
216  $externalrooturl = getRootURLFromURL($urlwithroot);
217 
218  if ($currentrooturl != $externalrooturl) {
219  $langs->load("errors");
220  setEventMessages($langs->trans("ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup", $currentrooturl, $externalrooturl), null, 'errors');
221  $url = DOL_URL_ROOT;
222  }
223  }
224 
225  // we go on oauth provider authorization page
226  header('Location: '.$url);
227  exit();
228 } else {
229  // We are coming from the return of an OAuth2 provider page.
230  dol_syslog("We are coming from the oauth provider page keyforprovider=".$keyforprovider." code=".dol_trunc(GETPOST('code'), 5));
231 
232  // We must validate that the $state is the same than the one into $_SESSION['oauthstateanticsrf'], return error if not.
233  if (isset($_SESSION['oauthstateanticsrf']) && $state != $_SESSION['oauthstateanticsrf']) {
234  //var_dump($_SESSION['oauthstateanticsrf']);exit;
235  print 'Value for state='.dol_escape_htmltag($state).' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
236  unset($_SESSION['oauthstateanticsrf']);
237  } else {
238  // This was a callback request from service, get the token
239  try {
240  //var_dump($state);
241  //var_dump($apiService); // OAuth\OAuth2\Service\Google
242  //dol_syslog("_GET=".var_export($_GET, true));
243 
244  $errorincheck = 0;
245 
246  $db->begin();
247 
248  // This requests the token from the received OAuth code (call of the https://oauth2.googleapis.com/token endpoint)
249  // Result is stored into object managed by class DoliStorage into includes/OAuth/Common/Storage/DoliStorage.php, so into table llx_oauth_token
250  $token = $apiService->requestAccessToken(GETPOST('code'), $state);
251 
252  // Note: The extraparams has the 'id_token' than contains a lot of information about the user.
253  $extraparams = $token->getExtraParams();
254  $jwt = explode('.', $extraparams['id_token']);
255 
256  $username = '';
257  $useremail = '';
258 
259  // Extract the middle part, base64 decode, then json_decode it
260  if (!empty($jwt[1])) {
261  $userinfo = json_decode(base64_decode($jwt[1]), true);
262 
263  dol_syslog("userinfo=".var_export($userinfo, true));
264 
265  $useremail = $userinfo['email'];
266 
267  /*
268  $useremailverified = $userinfo['email_verified'];
269  $useremailuniq = $userinfo['sub'];
270  $username = $userinfo['name'];
271  $userfamilyname = $userinfo['family_name'];
272  $usergivenname = $userinfo['given_name'];
273  $hd = $userinfo['hd'];
274  */
275 
276  // We should make the steps of validation of id_token
277 
278  // Verify that the state is the one expected
279  // TODO
280 
281  // 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.
282  // TODO
283 
284  // Verify that email is a verified email
285  /*if (empty($userinfo['email_verified'])) {
286  setEventMessages($langs->trans('Bad value for email, emai lwas not verified by Google'), null, 'errors');
287  $errorincheck++;
288  }*/
289 
290  // Verify that the value of the iss claim in the ID token is equal to https://accounts.google.com or accounts.google.com.
291  if ($userinfo['iss'] != 'accounts.google.com' && $userinfo['iss'] != 'https://accounts.google.com') {
292  setEventMessages($langs->trans('Bad value for returned userinfo[iss]'), null, 'errors');
293  $errorincheck++;
294  }
295 
296  // Verify that the value of the aud claim in the ID token is equal to your app's client ID.
297  if ($userinfo['aud'] != getDolGlobalString($keyforparamid)) {
298  setEventMessages($langs->trans('Bad value for returned userinfo[aud]'), null, 'errors');
299  $errorincheck++;
300  }
301 
302  // Verify that the expiry time (exp claim) of the ID token has not passed.
303  if ($userinfo['exp'] <= dol_now()) {
304  setEventMessages($langs->trans('Bad value for returned userinfo[exp]. Token expired.'), null, 'errors');
305  $errorincheck++;
306  }
307 
308  // 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.
309  // $userinfo['hd'] is the domain name of Gmail account.
310  // TODO
311  }
312 
313  if (!$errorincheck) {
314  // If call back to url for a OAUTH2 login
315  if ($forlogin) {
316  dol_syslog("we received the login/email to log to, it is ".$useremail);
317 
318  $tmparray = (empty($_SESSION['datafromloginform']) ? array() : $_SESSION['datafromloginform']);
319  $entitytosearchuser = (isset($tmparray['entity']) ? $tmparray['entity'] : -1);
320 
321  // Delete the token
322  $storage->clearToken('Google');
323 
324  $tmpuser = new User($db);
325  $res = $tmpuser->fetch(0, '', '', 0, $entitytosearchuser, $useremail);
326 
327  if ($res > 0) {
328  $username = $tmpuser->login;
329 
330  $_SESSION['googleoauth_receivedlogin'] = dol_hash($conf->file->instance_unique_id.$username, '0');
331  dol_syslog('We set $_SESSION[\'googleoauth_receivedlogin\']='.$_SESSION['googleoauth_receivedlogin']);
332  } else {
333  $errormessage = "Failed to login using Google. User with the Email '".$useremail."' was not found";
334  if ($entitytosearchuser > 0) {
335  $errormessage .= ' ('.$langs->trans("Entity").' '.$entitytosearchuser.')';
336  }
337  $_SESSION["dol_loginmesg"] = $errormessage;
338  $errorincheck++;
339 
340  dol_syslog($errormessage);
341  }
342  }
343  } else {
344  // If call back to url for a OAUTH2 login
345  if ($forlogin) {
346  $_SESSION["dol_loginmesg"] = "Failed to login using Google. OAuth callback URL retreives a token with non valid data";
347  $errorincheck++;
348  }
349  }
350 
351  if (!$errorincheck) {
352  $db->commit();
353  } else {
354  $db->rollback();
355  }
356 
357  $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
358  unset($_SESSION["backtourlsavedbeforeoauthjump"]);
359 
360  if (empty($backtourl)) {
361  $backtourl = DOL_URL_ROOT.'/';
362  }
363 
364  // If call back to this url was for a OAUTH2 login
365  if ($forlogin) {
366  // _SESSION['googleoauth_receivedlogin'] has been set to the key to validate the next test by function_googleoauth(), so we can make the redirect
367  $backtourl .= '?actionlogin=login&afteroauthloginreturn=1'.($username ? '&username='.urlencode($username) : '').'&token='.newToken();
368  if (!empty($tmparray['entity'])) {
369  $backtourl .= '&entity='.$tmparray['entity'];
370  }
371  }
372 
373  dol_syslog("Redirect now on backtourl=".$backtourl);
374 
375  header('Location: '.$backtourl);
376  exit();
377  } catch (Exception $e) {
378  print $e->getMessage();
379  }
380  }
381 }
382 
383 
384 /*
385  * View
386  */
387 
388 // No view at all, just actions, so we reach this line only on error.
389 
390 $db->close();
Class to manage Dolibarr users.
Definition: user.class.php:48
dol_now($mode='auto')
Return date for now.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getRootURLFromURL($url)
Function root url from a long url For example: https://www.abc.mydomain.com/dir/page....
Definition: geturl.lib.php:369
if(!GETPOSTISSET('keyforprovider') &&!empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) &&(GETPOST('code')|| $action=='delete')) $uriFactory
Create a new instance of the URI class with the current URI, stripping the query string.
dol_hash($chain, $type='0')
Returns a hash (non reversible encryption) of a string.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.