dolibarr 25.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-2024 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20// This page is used as callback for token generation of an OAUTH request.
21// This page can also be used to make the process to login and get token as described here:
22// https://developers.google.com/identity/protocols/oauth2/openid-connect#server-flow
23
30// Force keyforprovider
31$forlogin = 0;
32if (!empty($_GET['state']) && preg_match('/^forlogin-/', $_GET['state'])) {
33 $forlogin = 1;
34 $_GET['keyforprovider'] = 'Login';
35}
36
37if (!defined('NOLOGIN') && $forlogin) {
38 define("NOLOGIN", 1); // This means this output page does not require to be logged.
39}
40
41// Load Dolibarr environment
42require '../../../main.inc.php';
43require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
53use OAuth\Common\Storage\DoliStorage;
54use OAuth\Common\Consumer\Credentials;
55
56// Define $urlwithroot
58$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
59$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
60//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
61
62$langs->load("oauth");
63
64$action = GETPOST('action', 'aZ09');
65$backtourl = GETPOST('backtourl', 'alpha');
66$keyforprovider = GETPOST('keyforprovider', 'aZ09');
67if (!GETPOSTISSET('keyforprovider') && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
68 // If we are coming from the Oauth page
69 $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
70}
71
72
76$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
77//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
78//$currentUri->setQuery('');
79$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/google_oauthcallback.php');
80
81
87$serviceFactory = new \OAuth\ServiceFactory();
88$httpClient = new \OAuth\Common\Http\Client\CurlClient();
89// TODO Set options for proxy and timeout
90// $params=array('CURLXXX'=>value, ...)
91//$httpClient->setCurlParameters($params);
92$serviceFactory->setHttpClient($httpClient);
93
94// Setup the credentials for the requests
95$keyforparamid = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
96$keyforparamsecret = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
97$credentials = new Credentials(
98 getDolGlobalString($keyforparamid),
99 getDolGlobalString($keyforparamsecret),
100 $currentUri->getAbsoluteUri()
101);
102
103$state = GETPOST('state');
104$statewithscopeonly = '';
105$statewithanticsrfonly = '';
106
107$requestedpermissionsarray = array();
108if ($state) {
109 // 'state' parameter is standard to store a hash value and can be used to retrieve some parameters back
110 $statewithscopeonly = preg_replace('/\-.*$/', '', preg_replace('/^forlogin-/', '', $state));
111 $requestedpermissionsarray = explode(',', $statewithscopeonly); // Example: 'userinfo_email,userinfo_profile,openid,email,profile,cloud_print'.
112 $statewithanticsrfonly = preg_replace('/^.*\-/', '', $state);
113}
114
115// 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
116// but not when callback was ok and we recall the page
117if ($action != 'delete' && !GETPOST('afteroauthloginreturn') && (empty($statewithscopeonly) || empty($requestedpermissionsarray))) {
118 dol_syslog("state or statewithscopeonly and/or requestedpermissionsarray are empty");
119 setEventMessages($langs->trans('ScopeUndefined'), null, 'errors');
120 if (empty($backtourl)) {
121 $backtourl = DOL_URL_ROOT.'/';
122 }
123 header('Location: '.$backtourl);
124 exit();
125}
126
127//var_dump($requestedpermissionsarray);exit;
128
129
130// Dolibarr storage
131$storage = new DoliStorage($db, $conf, $keyforprovider);
132
133// Instantiate the Api service using the credentials, http client and storage mechanism for the token
134// $requestedpermissionsarray contains list of scopes.
135// Conversion into URL is done by Reflection on constant with name SCOPE_scope_in_uppercase
136$apiService = null;
137$nameofservice = 'Google';
138try {
139 //$nameofservice = ucfirst(strtolower($genericstring));
140 $apiService = $serviceFactory->createService($nameofservice, $credentials, $storage, $requestedpermissionsarray);
141 '@phan-var-force OAuth\OAuth2\Service\Google $apiService'; // createService is only ServiceInterface
142} catch (Exception $e) {
143 print 'Error, failed to create service for provider '.$nameofservice.($keyforprovider ? '-'.$keyforprovider : '').'. Message was: '.$e->getMessage();
144 exit;
145}
146// access type needed to have oauth provider refreshing token
147// also note that a refresh token is sent only after a prompt
148// For login, no refresh token is needed (token is deleted once the email is read), so we use online.
149$apiService->setAccessType($forlogin ? 'online' : 'offline');
150
151
152if (!getDolGlobalString($keyforparamid)) {
153 accessforbidden('Setup of service '.$keyforparamid.' is not complete. Customer ID is missing');
154}
155if (!getDolGlobalString($keyforparamsecret)) {
156 accessforbidden('Setup of service '.$keyforparamid.' is not complete. Secret key is missing');
157}
158
159
160/*
161 * Actions
162 */
163
164if ($action == 'delete' && (!empty($user->admin) || $user->id == GETPOSTINT('userid'))) {
165 $storage->userid = GETPOSTINT('userid');
166 $storage->clearToken('Google');
167
168 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
169
170 header('Location: '.$backtourl);
171 exit();
172}
173
174
175if (!GETPOST('code')) {
176 dol_syslog("Page is called without the 'code' parameter defined");
177
178 // If we enter this page without 'code' parameter, it means we click on the link from login page ($forlogin is set) or from setup page and we want to get the redirect
179 // to the OAuth provider login page.
180 // $backtourl should be a relative url like /mypage.php?param1=value1 but without param token and action. Part after the # should also have been removed by caller.
181
182 // Clean the backtourl we can use after an OAuth authentication
183 $backtourl = preg_replace('/token=[^&]+/', '', $backtourl); // We remove any token into url so we are sure only url with no action are qualified as call back urls.
184 $backtourl = preg_replace('/action=[a-z0-9]+/i', '', $backtourl); // We remove any token into url so we are sure only url with no action are qualified as call back urls.
185 $backtourl = preg_replace('/save_lastsearch_values=[a-z0-9]+/i', '', $backtourl);
186 $backtourl = preg_replace('/mainmenu=[a-z0-9]+/i', '', $backtourl);
187 $backtourl = preg_replace('/leftmenu=[a-z0-9]+/i', '', $backtourl);
188 $backtourl = preg_replace('/#.*$/i', '', $backtourl); // We remove part after the #...
189
190 // TODO Try enable this section
191 /*
192 // Optimization: If this is for login and we already have a valid OAuth token, we can reuse it instead of redirecting to Google again
193 if ($forlogin && $storage->hasAccessToken('Google')) {
194 global $db, $conf;
195 $existingToken = $storage->retrieveAccessToken('Google');
196 if (!$existingToken->isExpired()) {
197 dol_syslog("Reusing existing valid Google OAuth token for login, skipping Google redirect");
198
199 // Extract email from existing token's extraParams (which contains the id_token JWT)
200 $extraparams = $existingToken->getExtraParams();
201 $useremail = '';
202 if (!empty($extraparams['id_token'])) {
203 $jwt = explode('.', $extraparams['id_token']);
204 if (!empty($jwt[1])) {
205 $userinfo = json_decode(base64_decode($jwt[1]), true);
206 $useremail = $userinfo['email'];
207 }
208 }
209
210 if (!empty($useremail)) {
211 // Find the user in Dolibarr
212 $entitytosearchuser = -1; // Search in all entities
213 $tmparray = (empty($_SESSION['datafromloginform']) ? array() : $_SESSION['datafromloginform']);
214 if (!empty($tmparray['entity'])) {
215 $entitytosearchuser = $tmparray['entity'];
216 }
217
218 $tmpuser = new User($db);
219 $res = $tmpuser->fetch(0, '', '', 0, $entitytosearchuser, $useremail, 0, 1);
220
221 if ($res > 0) {
222 $username = $tmpuser->login;
223 $_SESSION['googleoauth_receivedlogin'] = dol_hash($conf->file->instance_unique_id.$username, '0');
224 dol_syslog('Reused existing token - set $_SESSION["googleoauth_receivedlogin"]='.$_SESSION['googleoauth_receivedlogin']);
225
226 // Redirect back to login page with afteroauthloginreturn flag
227 $backtourl = DOL_MAIN_URL_ROOT.$backtourl;
228 $backtourl .= (preg_match('/\?/', $backtourl) ? '&' : '?').'actionlogin=login&afteroauthloginreturn=google&mainmenu=home&username='.urlencode($username).'&token='.newToken();
229 if (!empty($tmparray['entity'])) {
230 $backtourl .= '&entity='.$tmparray['entity'];
231 }
232
233 dol_syslog("Redirecting to backtourl with reused token: ".$backtourl);
234 header('Location: '.$backtourl);
235 exit();
236 } else {
237 // User not found, fall back to normal OAuth flow
238 dol_syslog("User with email '".$useremail."' was not found, falling back to Google OAuth");
239 }
240 } else {
241 dol_syslog("Existing token has no id_token in extraParams, falling back to Google OAuth");
242 }
243 } else {
244 dol_syslog("Existing token is expired, falling back to Google OAuth");
245 }
246 }
247 */
248
249 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
250 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
251 $_SESSION['oauthstateanticsrf'] = $state;
252
253 // Save more data into session
254 // No need to save more data in sessions. We have several info into $_SESSION['datafromloginform'], saved when form is posted with a click
255 // on "Login with Google" with param actionlogin=login and beforeoauthloginredirect=google, by the functions_googleoauth.php.
256
257 // Set approval_prompt. Note: A refresh token will be provided only if prompt is done.
258 if ($forlogin) {
259 $approval_prompt = getDolGlobalString('OAUTH_GOOGLE_FORCE_PROMPT_ON_LOGIN', 'auto'); // Can be 'force'
260 $apiService->setApprouvalPrompt($approval_prompt);
261 } else {
262 $apiService->setApprouvalPrompt('force');
263 }
264
265 // This may create record into oauth_state before the header redirect.
266 // Creation of record with state, create record or just update column state of table llx_oauth_token (and create/update entry in llx_oauth_state) depending on the Provider used (see its constructor).
267 if ($state) {
268 $url = $apiService->getAuthorizationUri(array('state' => $state));
269 } else {
270 $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
271 }
272 // The redirect_uri is included into this $url
273
274 // Add more param
275 $url .= '&nonce='.bin2hex(random_bytes(64 / 8));
276
277 if ($forlogin) {
278 // TODO Add param hd. What is it for ?
279 //$url .= 'hd=xxx';
280
281 if (GETPOST('username')) {
282 $url .= '&login_hint='.urlencode(GETPOST('username'));
283 }
284
285 // Check that the redirect_uri that will be used is same than url of current domain
286
287 // Define $urlwithroot
289 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
290 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
291 //$urlwithroot = DOL_MAIN_URL_ROOT; // This is to use same domain name than current
292
293 include DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
294 $currentrooturl = getRootURLFromURL(DOL_MAIN_URL_ROOT);
295 $externalrooturl = getRootURLFromURL($urlwithroot);
296
297 if ($currentrooturl != $externalrooturl) {
298 $langs->load("errors");
299 setEventMessages($langs->trans("ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup", $currentrooturl, $externalrooturl), null, 'errors');
300 $url = DOL_URL_ROOT;
301 }
302 }
303
304 //var_dump($url);exit;
305
306 // we go on oauth provider authorization page, we will then go back on this page but into the other branch of the if (!GETPOST('code'))
307 header('Location: '.$url);
308 exit();
309} else {
310 // We are coming from the return of an OAuth2 provider page.
311 dol_syslog(basename(__FILE__)." We are coming from the oauth provider page keyforprovider=".$keyforprovider." code=".dol_trunc(GETPOST('code'), 5));
312
313 // We must validate that the $state is the same than the one into $_SESSION['oauthstateanticsrf'], return error if not.
314 if (isset($_SESSION['oauthstateanticsrf']) && $state != $_SESSION['oauthstateanticsrf']) {
315 //var_dump($_SESSION['oauthstateanticsrf']);exit;
316 print 'Value for state='.dol_escape_htmltag($state).' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
317 unset($_SESSION['oauthstateanticsrf']);
318 } else {
319 // This was a callback request from service, get the token
320 try {
321 //var_dump($state);
322 //var_dump($apiService); // OAuth\OAuth2\Service\Google
323 //dol_syslog("_GET=".var_export($_GET, true));
324
325 $errorincheck = 0;
326
327 $db->begin();
328
329 $token = null;
330 try {
331 // This requests the token from the received OAuth code (call of the https://oauth2.googleapis.com/token endpoint)
332 // Result is stored into object managed by class DoliStorage into includes/OAuth/Common/Storage/DoliStorage.php and into database table llx_oauth_token
333 $token = $apiService->requestAccessToken(GETPOST('code'), $state);
334 } catch (Exception $e) {
335 dol_syslog("Failed to get token with requestAccessToken: ".$e->getMessage(), LOG_ERR);
336 setEventMessages("Failed to get token with requestAccessToken: ".$e->getMessage(), null, 'errors');
337 $errorincheck++;
338 }
339
340 // The refresh token is inside the object token if the prompt was forced only.
341 //$refreshtoken = $token->getRefreshToken();
342 //var_dump($refreshtoken);
343 dol_syslog("requestAccessToken complete");
344
345 // Note: The extraparams has the 'id_token' than contains a lot of information about the user.
346 $extraparams = array();
347 if ($token) {
348 $extraparams = $token->getExtraParams();
349 }
350 $jwt = explode('.', $extraparams['id_token']);
351
352 $username = '';
353 $useremail = '';
354
355 // Extract the middle part, base64 decode, then json_decode it
356 if (!empty($jwt[1])) {
357 $userinfo = json_decode(base64_decode($jwt[1]), true);
358
359 dol_syslog("userinfo=".formatLogObject($userinfo));
360
361 $useremail = $userinfo['email'];
362
363 /*
364 $useremailverified = $userinfo['email_verified'];
365 $useremailuniq = $userinfo['sub'];
366 $username = $userinfo['name'];
367 $userfamilyname = $userinfo['family_name'];
368 $usergivenname = $userinfo['given_name'];
369 $hd = $userinfo['hd'];
370 */
371
372 // We should make the steps of validation of id_token
373
374 // Verify that the state is the one expected
375 // TODO
376
377 // 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.
378 // TODO
379
380 // Verify that email is a verified email
381 /*if (empty($userinfo['email_verified'])) {
382 setEventMessages($langs->trans('Bad value for email, email was not verified by Google'), null, 'errors');
383 $errorincheck++;
384 }*/
385
386 // Verify that the value of the iss claim in the ID token is equal to https://accounts.google.com or accounts.google.com.
387 if ($userinfo['iss'] != 'accounts.google.com' && $userinfo['iss'] != 'https://accounts.google.com') {
388 setEventMessages($langs->trans('Bad value for returned userinfo[iss]'), null, 'errors');
389 $errorincheck++;
390 }
391
392 // Verify that the value of the aud claim in the ID token is equal to your app's client ID.
393 if ($userinfo['aud'] != getDolGlobalString($keyforparamid)) {
394 setEventMessages($langs->trans('Bad value for returned userinfo[aud]'), null, 'errors');
395 $errorincheck++;
396 }
397
398 // Verify that the expiry time (exp claim) of the ID token has not passed.
399 if ($userinfo['exp'] <= dol_now()) {
400 setEventMessages($langs->trans('Bad value for returned userinfo[exp]. Token expired.'), null, 'errors');
401 $errorincheck++;
402 }
403
404 // 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.
405 // $userinfo['hd'] is the domain name of Gmail account.
406 // TODO
407 }
408
409 if (!$errorincheck) {
410 // If call back to url for a OAUTH2 login
411 if ($forlogin) {
412 dol_syslog("we received the login/email to log to, it is ".$useremail);
413
414 $tmparray = (empty($_SESSION['datafromloginform']) ? array() : $_SESSION['datafromloginform']);
415 $entitytosearchuser = ((isset($tmparray['entity']) && $tmparray['entity'] != '') ? $tmparray['entity'] : -1);
416
417 // Delete the old token
418 // TODO Try remove this line
419 $storage->clearToken('Google'); // Delete the token called ("Google-".$storage->keyforprovider)
420
421 $tmpuser = new User($db);
422 $res = $tmpuser->fetch(0, '', '', 0, $entitytosearchuser, $useremail, 0, 1); // Load user. Can load with email_oauth2.
423
424 if ($res > 0) {
425 $username = $tmpuser->login;
426
427 $_SESSION['googleoauth_receivedlogin'] = dol_hash($conf->file->instance_unique_id.$username, '0');
428 dol_syslog('We set $_SESSION[\'googleoauth_receivedlogin\']='.$_SESSION['googleoauth_receivedlogin']);
429 } else {
430 $errormessage = "Failed to login using Google. User with the Email '".$useremail."' was not found";
431 if ($entitytosearchuser > 0) {
432 $errormessage .= ' ('.$langs->trans("Entity").' '.$entitytosearchuser.')';
433 }
434 $_SESSION["dol_loginmesg"] = $errormessage;
435 $errorincheck++;
436
437 dol_syslog($errormessage);
438 }
439 } else {
440 setEventMessages("TokenSaved", null);
441 }
442 } else {
443 // If call back to url for a OAUTH2 login
444 if ($forlogin) {
445 $_SESSION["dol_loginmesg"] = "Failed to login using Google. OAuth callback URL retrieves a token with non valid data";
446 $errorincheck++;
447 }
448 }
449
450 if (!$errorincheck) {
451 $db->commit();
452 } else {
453 $db->rollback();
454 }
455
456 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
457 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
458
459 if (empty($backtourl)) {
460 $backtourl = DOL_URL_ROOT.'/';
461 }
462
463 // If call back to this url was for a OAUTH2 login
464 if ($forlogin) {
465 // Define $urlwithroot
466 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
467 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
468 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
469
470 // _SESSION['googleoauth_receivedlogin'] has been set to the key to validate the next test by function_googleoauth(), so we can make the redirect
471 // $backtourl is a relative url like /mypage.php?param1=value1 but without param token and action. Part after the # should also have been removed when saving it.
472 // $backtourl comes from $_SERVER['REQUEST_URI'], so it already contains DOL_URL_ROOT.
473 $backtourl = rtrim($urlwithouturlroot, '/').$backtourl;
474 $backtourl .= (preg_match('/\?/', $backtourl) ? '&' : '?').'actionlogin=login&afteroauthloginreturn=google&mainmenu=home'.($username ? '&username='.urlencode($username) : '').'&token='.newToken();
475 if (!empty($tmparray['entity'])) {
476 $backtourl .= '&entity='.$tmparray['entity'];
477 }
478 }
479
480 dol_syslog("Redirect now on backtourl=".$backtourl);
481
482 header('Location: '.$backtourl);
483 exit();
484 } catch (Exception $e) {
485 print $e->getMessage();
486 }
487 }
488}
489
490
491/*
492 * View
493 */
494
495// No view at all, just actions, so we reach this line only on error.
496
497$db->close();
global $dolibarr_main_url_root
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage Dolibarr users.
dol_now($mode='gmt')
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, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) formatLogObject($data)
Return a string serialized to be output on log with dol_syslog() An option allow to output log in one...
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 a 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....
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.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.