31if (!empty($_GET[
'state']) && preg_match(
'/^forlogin-/', $_GET[
'state'])) {
33 $_GET[
'keyforprovider'] =
'Login';
36if (!defined(
'NOLOGIN') && $forlogin) {
41require
'../../../main.inc.php';
42require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
43use OAuth\Common\Storage\DoliStorage;
44use OAuth\Common\Consumer\Credentials;
45use OAuth\OAuth2\Service\Google;
48global $dolibarr_main_url_root;
49$urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
50$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
55$action =
GETPOST(
'action',
'aZ09');
56$backtourl =
GETPOST(
'backtourl',
'alpha');
57$keyforprovider =
GETPOST(
'keyforprovider',
'aZ09');
58if (!GETPOSTISSET(
'keyforprovider') && !empty($_SESSION[
"oauthkeyforproviderbeforeoauthjump"]) && (
GETPOST(
'code') || $action ==
'delete')) {
60 $keyforprovider = $_SESSION[
"oauthkeyforproviderbeforeoauthjump"];
70$currentUri =
$uriFactory->createFromAbsolute($urlwithroot.
'/core/modules/oauth/google_oauthcallback.php');
78$serviceFactory = new \OAuth\ServiceFactory();
79$httpClient = new \OAuth\Common\Http\Client\CurlClient();
83$serviceFactory->setHttpClient($httpClient);
86$keyforparamid =
'OAUTH_GOOGLE'.($keyforprovider ?
'-'.$keyforprovider :
'').
'_ID';
87$keyforparamsecret =
'OAUTH_GOOGLE'.($keyforprovider ?
'-'.$keyforprovider :
'').
'_SECRET';
88$credentials =
new Credentials(
91 $currentUri->getAbsoluteUri()
95$statewithscopeonly =
'';
96$statewithanticsrfonly =
'';
98$requestedpermissionsarray = array();
101 $statewithscopeonly = preg_replace(
'/\-.*$/',
'', preg_replace(
'/^forlogin-/',
'', $state));
102 $requestedpermissionsarray = explode(
',', $statewithscopeonly);
103 $statewithanticsrfonly = preg_replace(
'/^.*\-/',
'', $state);
108if ($action !=
'delete' && !
GETPOST(
'afteroauthloginreturn',
'int') && (empty($statewithscopeonly) || empty($requestedpermissionsarray))) {
109 dol_syslog(
"state or statewithscopeonly and/or requestedpermissionsarray are empty");
111 if (empty($backtourl)) {
112 $backtourl = DOL_URL_ROOT.
'/';
114 header(
'Location: '.$backtourl);
122$storage =
new DoliStorage($db, $conf, $keyforprovider);
127$apiService = $serviceFactory->createService(
'Google', $credentials, $storage, $requestedpermissionsarray);
131$apiService->setAccessType(
'offline');
135 accessforbidden(
'Setup of service '.$keyforparamid.
' is not complete. Customer ID is missing');
138 accessforbidden(
'Setup of service '.$keyforparamid.
' is not complete. Secret key is missing');
146if ($action ==
'delete') {
147 $storage->clearToken(
'Google');
151 header(
'Location: '.$backtourl);
156 dol_syslog(
"Page is called without the 'code' parameter defined");
160 $_SESSION[
"backtourlsavedbeforeoauthjump"] = $backtourl;
161 $_SESSION[
"oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
162 $_SESSION[
'oauthstateanticsrf'] = $state;
183 $apiService->setApprouvalPrompt(
'force');
189 $url = $apiService->getAuthorizationUri(array(
'state' => $state));
191 $url = $apiService->getAuthorizationUri();
196 $url .=
'&nonce='.bin2hex(random_bytes(64/8));
203 $url .=
'&login_hint='.urlencode(
GETPOST(
'username'));
209 global $dolibarr_main_url_root;
210 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
211 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
214 include DOL_DOCUMENT_ROOT.
'/core/lib/geturl.lib.php';
218 if ($currentrooturl != $externalrooturl) {
219 $langs->load(
"errors");
220 setEventMessages($langs->trans(
"ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup", $currentrooturl, $externalrooturl),
null,
'errors');
226 header(
'Location: '.$url);
230 dol_syslog(
"We are coming from the oauth provider page keyforprovider=".$keyforprovider.
" code=".
dol_trunc(
GETPOST(
'code'), 5));
233 if (isset($_SESSION[
'oauthstateanticsrf']) && $state != $_SESSION[
'oauthstateanticsrf']) {
235 print
'Value for state='.dol_escape_htmltag($state).
' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
236 unset($_SESSION[
'oauthstateanticsrf']);
250 $token = $apiService->requestAccessToken(
GETPOST(
'code'), $state);
253 $extraparams = $token->getExtraParams();
254 $jwt = explode(
'.', $extraparams[
'id_token']);
260 if (!empty($jwt[1])) {
261 $userinfo = json_decode(base64_decode($jwt[1]),
true);
263 dol_syslog(
"userinfo=".var_export($userinfo,
true));
265 $useremail = $userinfo[
'email'];
291 if ($userinfo[
'iss'] !=
'accounts.google.com' && $userinfo[
'iss'] !=
'https://accounts.google.com') {
292 setEventMessages($langs->trans(
'Bad value for returned userinfo[iss]'),
null,
'errors');
298 setEventMessages($langs->trans(
'Bad value for returned userinfo[aud]'),
null,
'errors');
303 if ($userinfo[
'exp'] <=
dol_now()) {
304 setEventMessages($langs->trans(
'Bad value for returned userinfo[exp]. Token expired.'),
null,
'errors');
313 if (!$errorincheck) {
316 dol_syslog(
"we received the login/email to log to, it is ".$useremail);
318 $tmparray = (empty($_SESSION[
'datafromloginform']) ? array() : $_SESSION[
'datafromloginform']);
319 $entitytosearchuser = (isset($tmparray[
'entity']) ? $tmparray[
'entity'] : -1);
322 $storage->clearToken(
'Google');
324 $tmpuser =
new User($db);
325 $res = $tmpuser->fetch(0,
'',
'', 0, $entitytosearchuser, $useremail, 0, 1);
328 $username = $tmpuser->login;
330 $_SESSION[
'googleoauth_receivedlogin'] =
dol_hash($conf->file->instance_unique_id.$username,
'0');
331 dol_syslog(
'We set $_SESSION[\'googleoauth_receivedlogin\']='.$_SESSION[
'googleoauth_receivedlogin']);
333 $errormessage =
"Failed to login using Google. User with the Email '".$useremail.
"' was not found";
334 if ($entitytosearchuser > 0) {
335 $errormessage .=
' ('.$langs->trans(
"Entity").
' '.$entitytosearchuser.
')';
337 $_SESSION[
"dol_loginmesg"] = $errormessage;
346 $_SESSION[
"dol_loginmesg"] =
"Failed to login using Google. OAuth callback URL retreives a token with non valid data";
351 if (!$errorincheck) {
357 $backtourl = $_SESSION[
"backtourlsavedbeforeoauthjump"];
358 unset($_SESSION[
"backtourlsavedbeforeoauthjump"]);
360 if (empty($backtourl)) {
361 $backtourl = DOL_URL_ROOT.
'/';
367 $backtourl .=
'?actionlogin=login&afteroauthloginreturn=1'.($username ?
'&username='.urlencode($username) :
'').
'&token='.newToken();
368 if (!empty($tmparray[
'entity'])) {
369 $backtourl .=
'&entity='.$tmparray[
'entity'];
373 dol_syslog(
"Redirect now on backtourl=".$backtourl);
375 header(
'Location: '.$backtourl);
378 print $e->getMessage();
Class to manage Dolibarr users.
dol_now($mode='auto')
Return date for now.
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.
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....
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.