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';
40use OAuth\Common\Storage\DoliStorage;
41use OAuth\Common\Consumer\Credentials;
44global $dolibarr_main_url_root;
45$urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
46$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
51$action =
GETPOST(
'action',
'aZ09');
52$backtourl =
GETPOST(
'backtourl',
'alpha');
53$keyforprovider =
GETPOST(
'keyforprovider',
'aZ09');
54if (!GETPOSTISSET(
'keyforprovider') && !empty($_SESSION[
"oauthkeyforproviderbeforeoauthjump"]) && (
GETPOST(
'code') || $action ==
'delete')) {
56 $keyforprovider = $_SESSION[
"oauthkeyforproviderbeforeoauthjump"];
58$genericstring =
'GENERIC';
67$currentUri =
$uriFactory->createFromAbsolute($urlwithroot.
'/core/modules/oauth/generic_oauthcallback.php');
75$serviceFactory = new \OAuth\ServiceFactory();
76$httpClient = new \OAuth\Common\Http\Client\CurlClient();
80$serviceFactory->setHttpClient($httpClient);
83$keyforparamid =
'OAUTH_'.$genericstring.($keyforprovider ?
'-'.$keyforprovider :
'').
'_ID';
84$keyforparamsecret =
'OAUTH_'.$genericstring.($keyforprovider ?
'-'.$keyforprovider :
'').
'_SECRET';
85$credentials =
new Credentials(
88 $currentUri->getAbsoluteUri()
92$statewithscopeonly =
'';
93$statewithanticsrfonly =
'';
95$requestedpermissionsarray = array();
98 $statewithscopeonly = preg_replace(
'/\-.*$/',
'', preg_replace(
'/^forlogin-/',
'', $state));
99 $requestedpermissionsarray = explode(
',', $statewithscopeonly);
100 $statewithanticsrfonly = preg_replace(
'/^.*\-/',
'', $state);
105if ($action !=
'delete' && !
GETPOSTINT(
'afteroauthloginreturn') && (empty($statewithscopeonly) || empty($requestedpermissionsarray))) {
106 dol_syslog(
"state or statewithscopeonly and/or requestedpermissionsarray are empty");
108 if (empty($backtourl)) {
109 $backtourl = DOL_URL_ROOT.
'/';
111 header(
'Location: '.$backtourl);
119$storage =
new DoliStorage($db, $conf, $keyforprovider);
123$apiService = $serviceFactory->createService(ucfirst(strtolower($genericstring)), $credentials, $storage, $requestedpermissionsarray);
132if (empty($apiService) || !$apiService instanceof OAuth\OAuth2\Service\Generic) {
133 print
'Error, failed to create Generic serviceFactory';
136if (!$apiService->getBaseApiUri()) {
137 print
'Error, setup of OAuth entry is not complete (missing base url)';
143if (method_exists($apiService,
'setAccessType')) {
144 $apiService->setAccessType(
'offline');
148 accessforbidden(
'Setup of service '.$keyforparamid.
' is not complete. Customer ID is missing');
151 accessforbidden(
'Setup of service '.$keyforparamid.
' is not complete. Secret key is missing');
159if ($action ==
'delete' && (!empty($user->admin) || $user->id ==
GETPOSTINT(
'userid'))) {
161 $storage->clearToken($genericstring);
165 if (empty($backtourl)) {
166 $backtourl = DOL_URL_ROOT.
'/';
169 header(
'Location: '.$backtourl);
174 dol_syslog(
"Page is called without the 'code' parameter defined");
178 $_SESSION[
"backtourlsavedbeforeoauthjump"] = $backtourl;
179 $_SESSION[
"oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
180 $_SESSION[
'oauthstateanticsrf'] = $state;
188 $approval_prompt =
getDolGlobalString(
'OAUTH_'.$genericstring.
'_FORCE_PROMPT_ON_LOGIN',
'auto');
189 if (method_exists($apiService,
'setApprouvalPrompt')) {
190 $apiService->setApprouvalPrompt($approval_prompt);
193 if (method_exists($apiService,
'setApprouvalPrompt')) {
194 $apiService->setApprouvalPrompt(
'force');
201 $url = $apiService->getAuthorizationUri(array(
'client_id' =>
getDolGlobalString($keyforparamid),
'response_type' =>
'code',
'state' => $state));
203 $url = $apiService->getAuthorizationUri(array(
'client_id' =>
getDolGlobalString($keyforparamid),
'response_type' =>
'code'));
208 $url .=
'&scope='.str_replace(
',',
'+', $statewithscopeonly);
211 $url .=
'&nonce='.bin2hex(random_bytes(64 / 8));
218 $url .=
'&login_hint='.urlencode(
GETPOST(
'username'));
224 global $dolibarr_main_url_root;
225 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
226 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
229 include DOL_DOCUMENT_ROOT.
'/core/lib/geturl.lib.php';
233 if ($currentrooturl != $externalrooturl) {
234 $langs->load(
"errors");
235 setEventMessages($langs->trans(
"ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup", $currentrooturl, $externalrooturl),
null,
'errors');
243 header(
'Location: '.$url);
247 dol_syslog(basename(__FILE__).
" We are coming from the oauth provider page keyforprovider=".$keyforprovider.
" code=".
dol_trunc(
GETPOST(
'code'), 5));
250 if (isset($_SESSION[
'oauthstateanticsrf']) && $state != $_SESSION[
'oauthstateanticsrf']) {
252 print
'Value for state='.dol_escape_htmltag($state).
' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
253 unset($_SESSION[
'oauthstateanticsrf']);
266 $token = $apiService->requestAccessToken(
GETPOST(
'code'), $state);
268 '@phan-var-force OAuth\Common\Token\AbstractToken $token';
275 $extraparams = $token->getExtraParams();
323 if (!$errorincheck) {
326 dol_syslog(
"we received the login/email to log to, it is ".$useremail);
328 $tmparray = (empty($_SESSION[
'datafromloginform']) ? array() : $_SESSION[
'datafromloginform']);
329 $entitytosearchuser = (isset($tmparray[
'entity']) ? $tmparray[
'entity'] : -1);
332 $storage->clearToken($genericstring);
334 $tmpuser =
new User($db);
335 $res = $tmpuser->fetch(0,
'',
'', 0, $entitytosearchuser, $useremail, 0, 1);
338 $username = $tmpuser->login;
340 $_SESSION[
'genericoauth_receivedlogin'] =
dol_hash($conf->file->instance_unique_id.$username,
'0');
341 dol_syslog(
'We set $_SESSION[\'genericoauth_receivedlogin\']='.$_SESSION[
'genericoauth_receivedlogin']);
343 $errormessage =
"Failed to login using '.$genericstring.'. User with the Email '".$useremail.
"' was not found";
344 if ($entitytosearchuser > 0) {
345 $errormessage .=
' ('.$langs->trans(
"Entity").
' '.$entitytosearchuser.
')';
347 $_SESSION[
"dol_loginmesg"] = $errormessage;
356 $_SESSION[
"dol_loginmesg"] =
"Failed to login using '.$genericstring.'. OAuth callback URL retrieves a token with non valid data";
361 if (!$errorincheck) {
367 $backtourl = $_SESSION[
"backtourlsavedbeforeoauthjump"];
368 unset($_SESSION[
"backtourlsavedbeforeoauthjump"]);
370 if (empty($backtourl)) {
371 $backtourl = DOL_URL_ROOT.
'/';
377 $backtourl .=
'?actionlogin=login&afteroauthloginreturn=1&mainmenu=home'.($username ?
'&username='.urlencode($username) :
'').
'&token='.
newToken();
378 if (!empty($tmparray[
'entity'])) {
379 $backtourl .=
'&entity='.$tmparray[
'entity'];
383 dol_syslog(
"Redirect now on backtourl=".$backtourl);
385 header(
'Location: '.$backtourl);
388 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....
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.