32if (!empty($_GET[
'state']) && preg_match(
'/^forlogin-/', $_GET[
'state'])) {
34 $_GET[
'keyforprovider'] =
'Login';
37if (!defined(
'NOLOGIN') && $forlogin) {
42require
'../../../main.inc.php';
43require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
53use OAuth\Common\Storage\DoliStorage;
54use OAuth\Common\Consumer\Credentials;
58$urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
59$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
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')) {
69 $keyforprovider = $_SESSION[
"oauthkeyforproviderbeforeoauthjump"];
79$currentUri =
$uriFactory->createFromAbsolute($urlwithroot.
'/core/modules/oauth/google_oauthcallback.php');
87$serviceFactory = new \OAuth\ServiceFactory();
88$httpClient = new \OAuth\Common\Http\Client\CurlClient();
92$serviceFactory->setHttpClient($httpClient);
95$keyforparamid =
'OAUTH_GOOGLE'.($keyforprovider ?
'-'.$keyforprovider :
'').
'_ID';
96$keyforparamsecret =
'OAUTH_GOOGLE'.($keyforprovider ?
'-'.$keyforprovider :
'').
'_SECRET';
97$credentials =
new Credentials(
100 $currentUri->getAbsoluteUri()
104$statewithscopeonly =
'';
105$statewithanticsrfonly =
'';
107$requestedpermissionsarray = array();
110 $statewithscopeonly = preg_replace(
'/\-.*$/',
'', preg_replace(
'/^forlogin-/',
'', $state));
111 $requestedpermissionsarray = explode(
',', $statewithscopeonly);
112 $statewithanticsrfonly = preg_replace(
'/^.*\-/',
'', $state);
117if ($action !=
'delete' && !
GETPOST(
'afteroauthloginreturn') && (empty($statewithscopeonly) || empty($requestedpermissionsarray))) {
118 dol_syslog(
"state or statewithscopeonly and/or requestedpermissionsarray are empty");
120 if (empty($backtourl)) {
121 $backtourl = DOL_URL_ROOT.
'/';
123 header(
'Location: '.$backtourl);
131$storage =
new DoliStorage(
$db,
$conf, $keyforprovider);
137$nameofservice =
'Google';
140 $apiService = $serviceFactory->createService($nameofservice, $credentials, $storage, $requestedpermissionsarray);
141 '@phan-var-force OAuth\OAuth2\Service\Google $apiService';
143 print
'Error, failed to create service for provider '.$nameofservice.($keyforprovider ?
'-'.$keyforprovider :
'').
'. Message was: '.$e->getMessage();
148$apiService->setAccessType(
'offline');
152 accessforbidden(
'Setup of service '.$keyforparamid.
' is not complete. Customer ID is missing');
155 accessforbidden(
'Setup of service '.$keyforparamid.
' is not complete. Secret key is missing');
163if ($action ==
'delete' && (!empty($user->admin) || $user->id ==
GETPOSTINT(
'userid'))) {
165 $storage->clearToken(
'Google');
169 header(
'Location: '.$backtourl);
175 dol_syslog(
"Page is called without the 'code' parameter defined");
182 $backtourl = preg_replace(
'/token=[^&]+/',
'', $backtourl);
183 $backtourl = preg_replace(
'/action=[a-z0-9]+/i',
'', $backtourl);
184 $backtourl = preg_replace(
'/save_lastsearch_values=[a-z0-9]+/i',
'', $backtourl);
185 $backtourl = preg_replace(
'/mainmenu=[a-z0-9]+/i',
'', $backtourl);
186 $backtourl = preg_replace(
'/leftmenu=[a-z0-9]+/i',
'', $backtourl);
187 $backtourl = preg_replace(
'/#.*$/i',
'', $backtourl);
189 $_SESSION[
"backtourlsavedbeforeoauthjump"] = $backtourl;
190 $_SESSION[
"oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
191 $_SESSION[
'oauthstateanticsrf'] = $state;
200 $apiService->setApprouvalPrompt($approval_prompt);
202 $apiService->setApprouvalPrompt(
'force');
208 $url = $apiService->getAuthorizationUri(array(
'state' => $state));
210 $url = $apiService->getAuthorizationUri();
215 $url .=
'&nonce='.bin2hex(random_bytes(64 / 8));
222 $url .=
'&login_hint='.urlencode(
GETPOST(
'username'));
229 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
230 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
233 include DOL_DOCUMENT_ROOT.
'/core/lib/geturl.lib.php';
237 if ($currentrooturl != $externalrooturl) {
238 $langs->load(
"errors");
239 setEventMessages($langs->trans(
"ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup", $currentrooturl, $externalrooturl),
null,
'errors');
247 header(
'Location: '.$url);
251 dol_syslog(basename(__FILE__).
" We are coming from the oauth provider page keyforprovider=".$keyforprovider.
" code=".
dol_trunc(
GETPOST(
'code'), 5));
254 if (isset($_SESSION[
'oauthstateanticsrf']) && $state != $_SESSION[
'oauthstateanticsrf']) {
256 print
'Value for state='.dol_escape_htmltag($state).
' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
257 unset($_SESSION[
'oauthstateanticsrf']);
273 $token = $apiService->requestAccessToken(
GETPOST(
'code'), $state);
275 dol_syslog(
"Failed to get token with requestAccessToken: ".$e->getMessage(), LOG_ERR);
276 setEventMessages(
"Failed to get token with requestAccessToken: ".$e->getMessage(),
null,
'errors');
286 $extraparams = array();
288 $extraparams = $token->getExtraParams();
290 $jwt = explode(
'.', $extraparams[
'id_token']);
296 if (!empty($jwt[1])) {
297 $userinfo = json_decode(base64_decode($jwt[1]),
true);
301 $useremail = $userinfo[
'email'];
327 if ($userinfo[
'iss'] !=
'accounts.google.com' && $userinfo[
'iss'] !=
'https://accounts.google.com') {
328 setEventMessages($langs->trans(
'Bad value for returned userinfo[iss]'),
null,
'errors');
334 setEventMessages($langs->trans(
'Bad value for returned userinfo[aud]'),
null,
'errors');
339 if ($userinfo[
'exp'] <=
dol_now()) {
340 setEventMessages($langs->trans(
'Bad value for returned userinfo[exp]. Token expired.'),
null,
'errors');
349 if (!$errorincheck) {
352 dol_syslog(
"we received the login/email to log to, it is ".$useremail);
354 $tmparray = (empty($_SESSION[
'datafromloginform']) ? array() : $_SESSION[
'datafromloginform']);
355 $entitytosearchuser = ((isset($tmparray[
'entity']) && $tmparray[
'entity'] !=
'') ? $tmparray[
'entity'] : -1);
358 $storage->clearToken(
'Google');
361 $res = $tmpuser->fetch(0,
'',
'', 0, $entitytosearchuser, $useremail, 0, 1);
364 $username = $tmpuser->login;
366 $_SESSION[
'googleoauth_receivedlogin'] =
dol_hash(
$conf->file->instance_unique_id.$username,
'0');
367 dol_syslog(
'We set $_SESSION[\'googleoauth_receivedlogin\']='.$_SESSION[
'googleoauth_receivedlogin']);
369 $errormessage =
"Failed to login using Google. User with the Email '".$useremail.
"' was not found";
370 if ($entitytosearchuser > 0) {
371 $errormessage .=
' ('.$langs->trans(
"Entity").
' '.$entitytosearchuser.
')';
373 $_SESSION[
"dol_loginmesg"] = $errormessage;
384 $_SESSION[
"dol_loginmesg"] =
"Failed to login using Google. OAuth callback URL retrieves a token with non valid data";
389 if (!$errorincheck) {
395 $backtourl = $_SESSION[
"backtourlsavedbeforeoauthjump"];
396 unset($_SESSION[
"backtourlsavedbeforeoauthjump"]);
398 if (empty($backtourl)) {
399 $backtourl = DOL_URL_ROOT.
'/';
406 $backtourl = DOL_MAIN_URL_ROOT.$backtourl;
407 $backtourl .= (preg_match(
'/\?/', $backtourl) ?
'&' :
'?').
'actionlogin=login&afteroauthloginreturn=google&mainmenu=home'.($username ?
'&username='.urlencode($username) :
'').
'&token='.newToken();
408 if (!empty($tmparray[
'entity'])) {
409 $backtourl .=
'&entity='.$tmparray[
'entity'];
413 dol_syslog(
"Redirect now on backtourl=".$backtourl);
415 header(
'Location: '.$backtourl);
418 print $e->getMessage();
global $dolibarr_main_url_root
Class to manage Dolibarr users.
dol_now($mode='gmt')
Return date for now.
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
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.
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.