28if (!empty($_GET[
'state']) && preg_match(
'/^forlogin-/', $_GET[
'state'])) {
30 $_GET[
'keyforprovider'] =
'Login';
33if (!defined(
'NOLOGIN') && $forlogin) {
38require
'../../../main.inc.php';
39require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
48use OAuth\Common\Storage\DoliStorage;
49use OAuth\Common\Consumer\Credentials;
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;
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')) {
64 $keyforprovider = $_SESSION[
"oauthkeyforproviderbeforeoauthjump"];
66$genericstring =
'GENERIC';
75$currentUri =
$uriFactory->createFromAbsolute($urlwithroot.
'/core/modules/oauth/generic_oauthcallback.php');
83$serviceFactory = new \OAuth\ServiceFactory();
84$httpClient = new \OAuth\Common\Http\Client\CurlClient();
88$serviceFactory->setHttpClient($httpClient);
91$keyforparamid =
'OAUTH_'.$genericstring.($keyforprovider ?
'-'.$keyforprovider :
'').
'_ID';
92$keyforparamsecret =
'OAUTH_'.$genericstring.($keyforprovider ?
'-'.$keyforprovider :
'').
'_SECRET';
93$credentials =
new Credentials(
96 $currentUri->getAbsoluteUri()
100$statewithscopeonly =
'';
101$statewithanticsrfonly =
'';
103$requestedpermissionsarray = array();
106 $statewithscopeonly = preg_replace(
'/\-.*$/',
'', preg_replace(
'/^forlogin-/',
'', $state));
107 $requestedpermissionsarray = explode(
',', $statewithscopeonly);
108 $statewithanticsrfonly = preg_replace(
'/^.*\-/',
'', $state);
113if ($action !=
'delete' && !
GETPOSTINT(
'afteroauthloginreturn') && (empty($statewithscopeonly) || empty($requestedpermissionsarray))) {
114 dol_syslog(
"state or statewithscopeonly and/or requestedpermissionsarray are empty");
116 if (empty($backtourl)) {
117 $backtourl = DOL_URL_ROOT.
'/';
119 header(
'Location: '.$backtourl);
127$storage =
new DoliStorage($db,
$conf, $keyforprovider);
131$apiService = $serviceFactory->createService(ucfirst(strtolower($genericstring)), $credentials, $storage, $requestedpermissionsarray);
140if (empty($apiService) || !$apiService instanceof OAuth\OAuth2\Service\Generic) {
141 print
'Error, failed to create Generic serviceFactory';
144if (!$apiService->getBaseApiUri()) {
145 print
'Error, setup of OAuth entry is not complete (missing base url)';
151if (method_exists($apiService,
'setAccessType')) {
152 $apiService->setAccessType(
'offline');
156 accessforbidden(
'Setup of service '.$keyforparamid.
' is not complete. Customer ID is missing');
159 accessforbidden(
'Setup of service '.$keyforparamid.
' is not complete. Secret key is missing');
167if ($action ==
'delete' && (!empty($user->admin) || $user->id ==
GETPOSTINT(
'userid'))) {
169 $storage->clearToken($genericstring);
173 if (empty($backtourl)) {
174 $backtourl = DOL_URL_ROOT.
'/';
177 header(
'Location: '.$backtourl);
182 dol_syslog(
"Page is called without the 'code' parameter defined");
186 $_SESSION[
"backtourlsavedbeforeoauthjump"] = $backtourl;
187 $_SESSION[
"oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
188 $_SESSION[
'oauthstateanticsrf'] = $state;
196 $approval_prompt =
getDolGlobalString(
'OAUTH_'.$genericstring.
'_FORCE_PROMPT_ON_LOGIN',
'auto');
197 if (method_exists($apiService,
'setApprouvalPrompt')) {
198 $apiService->setApprouvalPrompt($approval_prompt);
201 if (method_exists($apiService,
'setApprouvalPrompt')) {
202 $apiService->setApprouvalPrompt(
'force');
209 $url = $apiService->getAuthorizationUri(array(
'client_id' =>
getDolGlobalString($keyforparamid),
'response_type' =>
'code',
'state' => $state));
211 $url = $apiService->getAuthorizationUri(array(
'client_id' =>
getDolGlobalString($keyforparamid),
'response_type' =>
'code'));
216 $url .=
'&scope='.str_replace(
',',
'+', $statewithscopeonly);
219 $url .=
'&nonce='.bin2hex(random_bytes(64 / 8));
226 $url .=
'&login_hint='.urlencode(
GETPOST(
'username'));
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;
237 include DOL_DOCUMENT_ROOT.
'/core/lib/geturl.lib.php';
241 if ($currentrooturl != $externalrooturl) {
242 $langs->load(
"errors");
243 setEventMessages($langs->trans(
"ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup", $currentrooturl, $externalrooturl),
null,
'errors');
251 header(
'Location: '.$url);
255 dol_syslog(basename(__FILE__).
" We are coming from the oauth provider page keyforprovider=".$keyforprovider.
" code=".
dol_trunc(
GETPOST(
'code'), 5));
258 if (isset($_SESSION[
'oauthstateanticsrf']) && $state != $_SESSION[
'oauthstateanticsrf']) {
260 print
'Value for state='.dol_escape_htmltag($state).
' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
261 unset($_SESSION[
'oauthstateanticsrf']);
274 $token = $apiService->requestAccessToken(
GETPOST(
'code'), $state);
276 '@phan-var-force OAuth\Common\Token\AbstractToken $token';
283 $extraparams = $token->getExtraParams();
331 if (!$errorincheck) {
334 dol_syslog(
"we received the login/email to log to, it is ".$useremail);
336 $tmparray = (empty($_SESSION[
'datafromloginform']) ? array() : $_SESSION[
'datafromloginform']);
337 $entitytosearchuser = (isset($tmparray[
'entity']) ? $tmparray[
'entity'] : -1);
340 $storage->clearToken($genericstring);
342 $tmpuser =
new User($db);
343 $res = $tmpuser->fetch(0,
'',
'', 0, $entitytosearchuser, $useremail, 0, 1);
346 $username = $tmpuser->login;
348 $_SESSION[
'genericoauth_receivedlogin'] =
dol_hash(
$conf->file->instance_unique_id.$username,
'0');
349 dol_syslog(
'We set $_SESSION[\'genericoauth_receivedlogin\']='.$_SESSION[
'genericoauth_receivedlogin']);
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.
')';
355 $_SESSION[
"dol_loginmesg"] = $errormessage;
364 $_SESSION[
"dol_loginmesg"] =
"Failed to login using '.$genericstring.'. OAuth callback URL retrieves a token with non valid data";
369 if (!$errorincheck) {
375 $backtourl = $_SESSION[
"backtourlsavedbeforeoauthjump"];
376 unset($_SESSION[
"backtourlsavedbeforeoauthjump"]);
378 if (empty($backtourl)) {
379 $backtourl = DOL_URL_ROOT.
'/';
385 $backtourl .=
'?actionlogin=login&afteroauthloginreturn=1&mainmenu=home'.($username ?
'&username='.urlencode($username) :
'').
'&token='.
newToken();
386 if (!empty($tmparray[
'entity'])) {
387 $backtourl .=
'&entity='.$tmparray[
'entity'];
391 dol_syslog(
"Redirect now on backtourl=".$backtourl);
393 header(
'Location: '.$backtourl);
396 print $e->getMessage();
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...
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.