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