dolibarr 23.0.3
generic_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
26// Force keyforprovider
27$forlogin = 0;
28if (!empty($_GET['state']) && preg_match('/^forlogin-/', $_GET['state'])) {
29 $forlogin = 1;
30 $_GET['keyforprovider'] = 'Login';
31}
32
33if (!defined('NOLOGIN') && $forlogin) {
34 define("NOLOGIN", 1); // This means this output page does not require to be logged.
35}
36
37// Load Dolibarr environment
38require '../../../main.inc.php';
47require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
48
49use OAuth\Common\Storage\DoliStorage;
50use OAuth\Common\Consumer\Credentials;
51use OAuth\Common\Http\Uri\Uri;
52
53// Define $urlwithroot
55$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
56$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
57//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
58
59$langs->load("oauth");
60
61$action = GETPOST('action', 'aZ09');
62$backtourl = GETPOST('backtourl', 'alpha');
63$keyforprovider = GETPOST('keyforprovider', 'aZ09');
64if (!GETPOSTISSET('keyforprovider') && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
65 // If we are coming from the Oauth page
66 $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
67}
68$genericstring = 'GENERIC';
69
70
74$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
75//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
76//$currentUri->setQuery('');
77$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/generic_oauthcallback.php');
78
79
85$serviceFactory = new \OAuth\ServiceFactory();
86$httpClient = new \OAuth\Common\Http\Client\CurlClient();
87// TODO Set options for proxy and timeout
88// $params=array('CURLXXX'=>value, ...)
89//$httpClient->setCurlParameters($params);
90$serviceFactory->setHttpClient($httpClient);
91
92// Setup the credentials for the requests
93$keyforparamid = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
94$keyforparamsecret = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
95$credentials = new Credentials(
96 getDolGlobalString($keyforparamid),
97 getDolGlobalString($keyforparamsecret),
98 $currentUri->getAbsoluteUri()
99);
100
101$state = GETPOST('state');
102$statewithscopeonly = '';
103$statewithanticsrfonly = '';
104
105$requestedpermissionsarray = array();
106if ($state) {
107 // 'state' parameter is standard to store a hash value and can also be used to retrieve some parameters back
108 $statewithscopeonly = preg_replace('/\-.*$/', '', preg_replace('/^forlogin-/', '', $state));
109 if ($statewithscopeonly != 'none') {
110 $requestedpermissionsarray = explode(',', $statewithscopeonly); // Example: 'userinfo_email,userinfo_profile,openid,email,profile,cloud_print'.
111 $statewithanticsrfonly = preg_replace('/^.*\-/', '', $state);
112 } else {
113 $statewithscopeonly = '';
114 }
115}
116
117// 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,
118// but NOT when callback was ok and we recall the page
119if ($action != 'delete' && !GETPOST('afteroauthloginreturn') && (empty($statewithscopeonly) || empty($requestedpermissionsarray)) && !preg_match('/^none/', $state)) {
120 if (GETPOST('error') || GETPOST('error_description')) {
121 setEventMessages($langs->trans("Error").' '.GETPOST('error_description'), null, 'errors');
122 } else {
123 dol_syslog("state or statewithscopeonly and/or requestedpermissionsarray are empty");
124 setEventMessages($langs->trans('ScopeUndefined'), null, 'errors');
125 if (empty($backtourl)) {
126 $backtourl = DOL_URL_ROOT.'/';
127 }
128 header('Location: '.$backtourl);
129 exit();
130 }
131}
132
133
134
135// Dolibarr storage
136$storage = new DoliStorage($db, $conf, $keyforprovider);
137
138$keyforurl = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_URL';
139if (getDolGlobalString($keyforurl)) {
140 $baseApiUriInt = new Uri(getDolGlobalString($keyforurl));
141} else {
142 print 'Error, failed to get value for constant '.$keyforurl;
143 exit;
144}
145
146$apiService = null;
147$nameofservice = ucfirst(strtolower($genericstring));
148try {
149 // Instantiate the Api service using the credentials, http client and storage mechanism for the token
150 // ucfirst(strtolower($genericstring)) must be the name of a class into OAuth/OAuth2/Services/Xxxx
151 $apiService = $serviceFactory->createService($nameofservice, $credentials, $storage, $requestedpermissionsarray, $baseApiUriInt);
152 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService'; // createService is only ServiceInterface
153} catch (Exception $e) {
154 print 'Error, failed to create service for provider '.$nameofservice.($keyforprovider ? '-'.$keyforprovider : '').'. Message was: '.$e->getMessage();
155 exit;
156}
157/*
158var_dump($genericstring.($keyforprovider ? '-'.$keyforprovider : ''));
159var_dump($credentials);
160var_dump($storage);
161var_dump($requestedpermissionsarray);
162*/
163
164
165if (empty($apiService) || !$apiService instanceof OAuth\OAuth2\Service\Generic) {
166 print 'Error, failed to create Generic serviceFactory';
167 exit;
168}
169if (!$apiService->getBaseApiUri()) {
170 print 'Error, setup of OAuth entry is not complete (missing base url)';
171 exit;
172}
173
174// access type needed to have oauth provider refreshing token
175// also note that a refresh token is sent only after a prompt
176if (method_exists($apiService, 'setAccessType')) {
177 $apiService->setAccessType('offline'); // Most generic OAUTH provider does not provide AccessType online/offline. They are mostly offline. // @phan-suppress-current-line PhanUndeclaredMethod
178}
179
180if (!getDolGlobalString($keyforparamid)) {
181 accessforbidden('Setup of service '.$keyforparamid.' is not complete. Customer ID is missing');
182}
183if (!getDolGlobalString($keyforparamsecret)) {
184 accessforbidden('Setup of service '.$keyforparamid.' is not complete. Secret key is missing');
185}
186
187
188/*
189 * Actions
190 */
191
192if ($action == 'delete' && (!empty($user->admin) || $user->id == GETPOSTINT('userid'))) {
193 $storage->userid = GETPOSTINT('userid');
194 $storage->clearToken($genericstring);
195
196 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
197
198 if (empty($backtourl)) {
199 $backtourl = DOL_URL_ROOT.'/';
200 }
201
202 header('Location: '.$backtourl);
203 exit();
204}
205
206if (!GETPOST('code') && !GETPOST('error')) {
207 dol_syslog("Page is called without the 'code' parameter defined");
208
209 if (empty($state) || $state == 'none') {
210 // Generate a random state value to prevent CSRF attack. Store it into session juste after to check it when we will receive the callback from provider.
211 $state = 'none-'.bin2hex(random_bytes(16));
212 }
213
214 // 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
215 // to the OAuth provider login page.
216 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
217 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
218 $_SESSION['oauthstateanticsrf'] = $state;
219
220 // Save more data into session
221 // No need to save more data in sessions. We have several info into $_SESSION['datafromloginform'], saved when form is posted with a click
222 // on "Login with Generic" with param actionlogin=login and beforeoauthloginredirect=generic, by the functions_genericoauth.php.
223
224 // Set approval_prompt. Note: A refresh token will be provided only if prompt is done.
225 if ($forlogin) {
226 $approval_prompt = getDolGlobalString('OAUTH_'.$genericstring.'_FORCE_PROMPT_ON_LOGIN', 'auto'); // Can be 'force'
227 if (method_exists($apiService, 'setApprouvalPrompt')) {
228 $apiService->setApprouvalPrompt($approval_prompt); // @phan-suppress-current-line PhanUndeclaredMethod
229 }
230 } else {
231 if (method_exists($apiService, 'setApprouvalPrompt')) {
232 $apiService->setApprouvalPrompt('force'); // @phan-suppress-current-line PhanUndeclaredMethod
233 }
234 }
235
236 // This may create record into oauth_state before the header redirect.
237 // 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).
238 //if ($state && $state != 'none') {
239 $url = $apiService->getAuthorizationUri(array('client_id' => getDolGlobalString($keyforparamid), 'response_type' => 'code', 'state' => $state));
240 //} else {
241 // $url = $apiService->getAuthorizationUri(array('client_id' => getDolGlobalString($keyforparamid), 'response_type' => 'code')); // Parameter state will be randomly generated
242 //}
243 // The redirect_uri is included into this $url
244
245 // Add scopes
246 if ($statewithscopeonly) {
247 $url .= '&scope='.str_replace(',', '+', $statewithscopeonly);
248 }
249
250 // Add more param
251 $url .= '&nonce='.bin2hex(random_bytes(64 / 8));
252
253 if ($forlogin) {
254 // TODO Add param hd. What is it for ?
255 //$url .= 'hd=xxx';
256
257 if (GETPOST('username')) {
258 $url .= '&login_hint='.urlencode(GETPOST('username'));
259 }
260
261 // Check that the redirect_uri that will be used is same than url of current domain
262
263 // Define $urlwithroot
265 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
266 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
267 //$urlwithroot = DOL_MAIN_URL_ROOT; // This is to use same domain name than current
268
269 include DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
270 $currentrooturl = getRootURLFromURL(DOL_MAIN_URL_ROOT);
271 $externalrooturl = getRootURLFromURL($urlwithroot);
272
273 if ($currentrooturl != $externalrooturl) {
274 $langs->load("errors");
275 setEventMessages($langs->trans("ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup", $currentrooturl, $externalrooturl), null, 'errors');
276 $url = DOL_URL_ROOT;
277 }
278 }
279
280 //var_dump($keyforurl, $url, $statewithscopeonly);exit;
281
282 // 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'))
283 header('Location: '.$url);
284 exit();
285} else {
286 // We are coming from the return of an OAuth2 provider page.
287 dol_syslog(basename(__FILE__)." We are coming from the oauth provider page keyforprovider=".$keyforprovider." code=".dol_trunc(GETPOST('code'), 5));
288
289 // We must validate that the $state is the same than the one into $_SESSION['oauthstateanticsrf'], return error if not.
290 if (isset($_SESSION['oauthstateanticsrf']) && $state != $_SESSION['oauthstateanticsrf']) {
291 //var_dump($_SESSION['oauthstateanticsrf']);exit;
292 print 'Value for state='.dol_escape_htmltag($state).' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
293 unset($_SESSION['oauthstateanticsrf']);
294 } else {
295 // This was a callback request from service, get the token
296 try {
297 //var_dump($apiService); // OAuth\OAuth2\Service\Generic
298 //dol_syslog("_GET=".var_export($_GET, true));
299
300 $errorincheck = 0;
301
302 $db->begin();
303
304 $token = null;
305 $last_insert_id = 0;
306 try {
307 // This requests the token from the received OAuth code (call of the endpoint)
308 // Result is stored into object managed by class DoliStorage into includes/OAuth/Common/Storage/DoliStorage.php and into database table llx_oauth_token
309 $token = $apiService->requestAccessToken(GETPOST('code'), $state);
310 '@phan-var-force OAuth\Common\Token\AbstractToken $token';
311
312 $storage = $apiService->getStorage();
313 if (property_exists($storage, 'last_insert_id')) {
314 $last_insert_id = $storage->last_insert_id;
315 }
316 } catch (Exception $e) {
317 dol_syslog("Failed to get token with requestAccessToken: ".$e->getMessage(), LOG_ERR);
318 setEventMessages("Failed to get token with requestAccessToken: ".$e->getMessage(), null, 'errors');
319 $errorincheck++;
320 }
321
322 // The refresh token is inside the object token if the prompt was forced only. Otherwise, it may be found into extraParams section.
323 //$refreshtoken = $token->getRefreshToken();
324 //var_dump($refreshtoken);
325 dol_syslog("requestAccessToken complete");
326
327 // The refresh token is inside the object token if the prompt was forced only.
328 //$refreshtoken = $token->getRefreshToken();
329 //var_dump($refreshtoken);
330
331 // Note: The extraparams has the 'id_token' than contains a lot of information about the user.
332 if ($token) {
333 $extraparams = $token->getExtraParams();
334
335 $scope = empty($extraparams['scope']) ? '' : $extraparams['scope'];
336 $tokenstring = $token->getAccessToken();
337 // Update entry in llx_oauth_token to store the scope associated to the token into field "state" (field should be renamed).
338 // It is not stored by default by DoliStorage.
339 // TODO Update using $scope and $tokenstring and $last_insert_id
340 $refreshtoken = empty($extraparams['refresh_token']) ? '' : $extraparams['refresh_token'];
341 if (empty($refreshtoken)) {
342 $refreshtoken = $token->getRefreshToken();
343 }
344
345 if ($last_insert_id) {
346 $sqlupdate = "UPDATE ".MAIN_DB_PREFIX."oauth_token";
347 $sqlupdate .= " SET state = '".(empty($scope) ? '' : $db->escape($scope))."', tokenstring = '".$db->escape($tokenstring)."', tokenstring_refresh = '".$db->escape($refreshtoken)."'";
348 $sqlupdate .= " WHERE rowid = ".((int) $last_insert_id);
349
350 $db->query($sqlupdate);
351
352 //var_dump($scope, $token, $refreshtoken, $last_insert_id, $sqlupdate);exit;
353 }
354 }
355
356 $username = '';
357 $useremail = '';
358
359 // Extract the middle part, base64 decode, then json_decode it
360 /*
361 $jwt = explode('.', $extraparams['id_token']);
362
363 if (!empty($jwt[1])) {
364 $userinfo = json_decode(base64_decode($jwt[1]), true);
365
366 dol_syslog("userinfo=".var_export($userinfo, true));
367
368 $useremail = $userinfo['email'];
369
370 // We should make the steps of validation of id_token
371
372 // Verify that the state is the one expected
373 // TODO
374
375 // Verify that the ID token is properly signed by the issuer.
376 // TODO
377
378 // Verify that the value of the iss claim in the ID token is equal to https://accounts.google.com or accounts.google.com.
379 if ($userinfo['iss'] != 'accounts.google.com' && $userinfo['iss'] != 'https://accounts.google.com') {
380 setEventMessages($langs->trans('Bad value for returned userinfo[iss]'), null, 'errors');
381 $errorincheck++;
382 }
383
384 // Verify that the value of the aud claim in the ID token is equal to your app's client ID.
385 if ($userinfo['aud'] != getDolGlobalString($keyforparamid)) {
386 setEventMessages($langs->trans('Bad value for returned userinfo[aud]'), null, 'errors');
387 $errorincheck++;
388 }
389
390 // Verify that the expiry time (exp claim) of the ID token has not passed.
391 if ($userinfo['exp'] <= dol_now()) {
392 setEventMessages($langs->trans('Bad value for returned userinfo[exp]. Token expired.'), null, 'errors');
393 $errorincheck++;
394 }
395
396 // 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.
397 // $userinfo['hd'] is the domain name of Gmail account.
398 // TODO
399 }
400 */
401
402 if (!$errorincheck) {
403 // If call back to url for a OAUTH2 login
404 if ($forlogin) {
405 dol_syslog("we received the login/email to log to, it is ".$useremail);
406
407 $tmparray = (empty($_SESSION['datafromloginform']) ? array() : $_SESSION['datafromloginform']);
408 $entitytosearchuser = ((isset($tmparray['entity']) && $tmparray['entity'] != '') ? $tmparray['entity'] : -1);
409
410 // Delete the old token
411 $storage->clearToken($genericstring); // Delete the token called ("Generic-".$storage->keyforprovider)
412
413 $tmpuser = new User($db);
414 $res = $tmpuser->fetch(0, '', '', 0, $entitytosearchuser, $useremail, 0, 1); // Load user. Can load with email_oauth2.
415
416 if ($res > 0) {
417 $username = $tmpuser->login;
418
419 $_SESSION['genericoauth_receivedlogin'] = dol_hash($conf->file->instance_unique_id.$username, '0');
420 dol_syslog('We set $_SESSION[\'genericoauth_receivedlogin\']='.$_SESSION['genericoauth_receivedlogin']);
421 } else {
422 $errormessage = "Failed to login using '.$genericstring.'. User with the Email '".$useremail."' was not found";
423 if ($entitytosearchuser > 0) {
424 $errormessage .= ' ('.$langs->trans("Entity").' '.$entitytosearchuser.')';
425 }
426 $_SESSION["dol_loginmesg"] = $errormessage;
427 $errorincheck++;
428
429 dol_syslog($errormessage);
430 }
431 }
432 } else {
433 // If call back to url for a OAUTH2 login
434 if ($forlogin) {
435 $_SESSION["dol_loginmesg"] = "Failed to login using '.$genericstring.'. OAuth callback URL retrieves a token with non valid data";
436 $errorincheck++;
437 }
438 }
439
440 if (!$errorincheck) {
441 $db->commit();
442 } else {
443 $db->rollback();
444 }
445
446 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
447 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
448
449 if (empty($backtourl)) {
450 $backtourl = DOL_URL_ROOT.'/';
451 }
452
453 // If call back to this url was for a OAUTH2 login
454 if ($forlogin) {
455 // _SESSION['genericoauth_receivedlogin'] has been set to the key to validate the next test by function_genericoauth(), so we can make the redirect
456 $backtourl .= '?actionlogin=login&afteroauthloginreturn=generic&mainmenu=home'.($username ? '&username='.urlencode($username) : '').'&token='.newToken();
457 if (!empty($tmparray['entity'])) {
458 $backtourl .= '&entity='.$tmparray['entity'];
459 }
460 }
461
462 dol_syslog("Redirect now on backtourl=".$backtourl);
463
464 header('Location: '.$backtourl);
465 exit();
466 } catch (Exception $e) {
467 print $e->getMessage();
468 }
469 }
470}
471
472
473/*
474 * View
475 */
476
477// No view at all, just actions
478
479$db->close();
global $dolibarr_main_url_root
Class to manage Dolibarr users.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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.
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.
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.
$uriFactory
Create a new instance of the URI class with the current URI, stripping the query string.
getRootURLFromURL($url)
Function root url from a long url For example: https://www.abc.mydomain.com/dir/page....
dol_hash($chain, $type='0', $nosalt=0, $mode=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.