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