2022-08-04 13:58:00 +00:00
< ? php
2026-03-14 18:35:11 +00:00
/* Copyright ( C ) 2022 - 2026 Laurent Destailleur < eldy @ users . sourceforge . net >
* Copyright ( C ) 2015 - 2024 Frédéric France < frederic . france @ free . fr >
* Copyright ( C ) 2024 - 2026 MDW < mdeweerd @ users . noreply . github . com >
2022-08-04 13:58:00 +00:00
*
* This program is free software ; you can redistribute it and / or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation ; either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < https :// www . gnu . org / licenses />.
*/
/**
* \file htdocs / core / modules / oauth / generic_oauthcallback . php
* \ingroup oauth
* \brief Page to get oauth callback
*/
2024-08-13 16:36:33 +00:00
// Force keyforprovider
$forlogin = 0 ;
if ( ! empty ( $_GET [ 'state' ]) && preg_match ( '/^forlogin-/' , $_GET [ 'state' ])) {
$forlogin = 1 ;
$_GET [ 'keyforprovider' ] = 'Login' ;
}
if ( ! defined ( 'NOLOGIN' ) && $forlogin ) {
define ( " NOLOGIN " , 1 ); // This means this output page does not require to be logged.
}
2022-09-07 18:08:59 +00:00
// Load Dolibarr environment
2022-08-04 13:58:00 +00:00
require '../../../main.inc.php' ;
2024-11-06 18:39:46 +00:00
/**
* @ var Conf $conf
* @ var DoliDB $db
* @ var Translate $langs
* @ var User $user
*
2024-12-01 22:15:27 +00:00
* @ var string $dolibarr_main_url_root
2024-11-06 18:39:46 +00:00
*/
2026-02-25 18:38:55 +00:00
require_once DOL_DOCUMENT_ROOT . '/includes/OAuth/bootstrap.php' ;
2022-08-04 13:58:00 +00:00
use OAuth\Common\Storage\DoliStorage ;
use OAuth\Common\Consumer\Credentials ;
2026-02-25 18:38:55 +00:00
use OAuth\Common\Http\Uri\Uri ;
2022-08-04 13:58:00 +00:00
// Define $urlwithroot
2024-08-13 16:36:33 +00:00
global $dolibarr_main_url_root ;
2022-08-04 13:58:00 +00:00
$urlwithouturlroot = preg_replace ( '/' . preg_quote ( DOL_URL_ROOT , '/' ) . '$/i' , '' , trim ( $dolibarr_main_url_root ));
$urlwithroot = $urlwithouturlroot . DOL_URL_ROOT ; // This is to use external domain name found into config file
//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
2024-08-13 16:36:33 +00:00
$langs -> load ( " oauth " );
2022-08-04 13:58:00 +00:00
$action = GETPOST ( 'action' , 'aZ09' );
$backtourl = GETPOST ( 'backtourl' , 'alpha' );
$keyforprovider = GETPOST ( 'keyforprovider' , 'aZ09' );
2024-08-13 16:36:33 +00:00
if ( ! GETPOSTISSET ( 'keyforprovider' ) && ! empty ( $_SESSION [ " oauthkeyforproviderbeforeoauthjump " ]) && ( GETPOST ( 'code' ) || $action == 'delete' )) {
// If we are coming from the Oauth page
2022-08-04 13:58:00 +00:00
$keyforprovider = $_SESSION [ " oauthkeyforproviderbeforeoauthjump " ];
}
2024-08-13 16:36:33 +00:00
$genericstring = 'GENERIC' ;
2022-08-04 13:58:00 +00:00
/**
* Create a new instance of the URI class with the current URI , stripping the query string
*/
$uriFactory = new \OAuth\Common\Http\Uri\UriFactory ();
//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
//$currentUri->setQuery('');
$currentUri = $uriFactory -> createFromAbsolute ( $urlwithroot . '/core/modules/oauth/generic_oauthcallback.php' );
/**
* Load the credential for the service
*/
2023-12-07 19:03:24 +00:00
/** @var \OAuth\ServiceFactory $serviceFactory An OAuth service factory. */
2022-08-04 13:58:00 +00:00
$serviceFactory = new \OAuth\ServiceFactory ();
$httpClient = new \OAuth\Common\Http\Client\CurlClient ();
// TODO Set options for proxy and timeout
// $params=array('CURLXXX'=>value, ...)
//$httpClient->setCurlParameters($params);
$serviceFactory -> setHttpClient ( $httpClient );
// Setup the credentials for the requests
$keyforparamid = 'OAUTH_' . $genericstring . ( $keyforprovider ? '-' . $keyforprovider : '' ) . '_ID' ;
$keyforparamsecret = 'OAUTH_' . $genericstring . ( $keyforprovider ? '-' . $keyforprovider : '' ) . '_SECRET' ;
$credentials = new Credentials (
getDolGlobalString ( $keyforparamid ),
getDolGlobalString ( $keyforparamsecret ),
$currentUri -> getAbsoluteUri ()
);
2023-02-07 19:12:53 +00:00
$state = GETPOST ( 'state' );
2024-08-13 16:36:33 +00:00
$statewithscopeonly = '' ;
$statewithanticsrfonly = '' ;
2023-02-07 19:12:53 +00:00
2022-08-04 13:58:00 +00:00
$requestedpermissionsarray = array ();
2023-02-07 19:12:53 +00:00
if ( $state ) {
2026-02-25 18:38:55 +00:00
// 'state' parameter is standard to store a hash value and can also be used to retrieve some parameters back
2024-08-13 16:36:33 +00:00
$statewithscopeonly = preg_replace ( '/\-.*$/' , '' , preg_replace ( '/^forlogin-/' , '' , $state ));
2026-02-25 18:38:55 +00:00
if ( $statewithscopeonly != 'none' ) {
$requestedpermissionsarray = explode ( ',' , $statewithscopeonly ); // Example: 'userinfo_email,userinfo_profile,openid,email,profile,cloud_print'.
$statewithanticsrfonly = preg_replace ( '/^.*\-/' , '' , $state );
} else {
$statewithscopeonly = '' ;
}
2022-08-04 13:58:00 +00:00
}
2024-08-13 16:36:33 +00:00
2026-02-25 21:46:27 +00:00
// 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,
// but NOT when callback was ok and we recall the page
if ( $action != 'delete' && ! GETPOST ( 'afteroauthloginreturn' ) && ( empty ( $statewithscopeonly ) || empty ( $requestedpermissionsarray )) && ! preg_match ( '/^none/' , $state )) {
2026-02-25 18:38:55 +00:00
if ( GETPOST ( 'error' ) || GETPOST ( 'error_description' )) {
setEventMessages ( $langs -> trans ( " Error " ) . ' ' . GETPOST ( 'error_description' ), null , 'errors' );
} else {
dol_syslog ( " state or statewithscopeonly and/or requestedpermissionsarray are empty " );
setEventMessages ( $langs -> trans ( 'ScopeUndefined' ), null , 'errors' );
if ( empty ( $backtourl )) {
$backtourl = DOL_URL_ROOT . '/' ;
}
header ( 'Location: ' . $backtourl );
exit ();
2024-08-13 16:36:33 +00:00
}
2022-08-04 13:58:00 +00:00
}
2024-08-13 16:36:33 +00:00
2022-08-04 13:58:00 +00:00
2024-08-13 16:36:33 +00:00
// Dolibarr storage
$storage = new DoliStorage ( $db , $conf , $keyforprovider );
2026-02-25 18:38:55 +00:00
$keyforurl = 'OAUTH_' . $genericstring . ( $keyforprovider ? '-' . $keyforprovider : '' ) . '_URL' ;
2026-03-14 17:47:51 +00:00
if ( getDolGlobalString ( $keyforurl )) {
2026-02-25 18:38:55 +00:00
$baseApiUriInt = new Uri ( getDolGlobalString ( $keyforurl ));
} else {
print 'Error, failed to get value for constant ' . $keyforurl ;
exit ;
}
2022-08-04 13:58:00 +00:00
2026-02-25 18:38:55 +00:00
$apiService = null ;
$nameofservice = ucfirst ( strtolower ( $genericstring ));
try {
// Instantiate the Api service using the credentials, http client and storage mechanism for the token
// ucfirst(strtolower($genericstring)) must be the name of a class into OAuth/OAuth2/Services/Xxxx
$apiService = $serviceFactory -> createService ( $nameofservice , $credentials , $storage , $requestedpermissionsarray , $baseApiUriInt );
'@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService' ; // createService is only ServiceInterface
} catch ( Exception $e ) {
print 'Error, failed to create service for provider ' . $nameofservice . ( $keyforprovider ? '-' . $keyforprovider : '' ) . '. Message was: ' . $e -> getMessage ();
exit ;
}
2022-08-04 13:58:00 +00:00
/*
var_dump ( $genericstring . ( $keyforprovider ? '-' . $keyforprovider : '' ));
var_dump ( $credentials );
var_dump ( $storage );
var_dump ( $requestedpermissionsarray );
*/
2026-02-25 18:38:55 +00:00
2024-08-19 00:05:27 +00:00
if ( empty ( $apiService ) || ! $apiService instanceof OAuth\OAuth2\Service\Generic ) {
print 'Error, failed to create Generic serviceFactory' ;
2022-08-04 13:58:00 +00:00
exit ;
}
2024-08-13 16:36:33 +00:00
if ( ! $apiService -> getBaseApiUri ()) {
print 'Error, setup of OAuth entry is not complete (missing base url)' ;
exit ;
}
2022-08-04 13:58:00 +00:00
// access type needed to have oauth provider refreshing token
2024-08-13 16:36:33 +00:00
// also note that a refresh token is sent only after a prompt
if ( method_exists ( $apiService , 'setAccessType' )) {
2024-08-19 00:05:27 +00:00
$apiService -> setAccessType ( 'offline' ); // Most generic OAUTH provider does not provide AccessType online/offline. They are mostly offline. // @phan-suppress-current-line PhanUndeclaredMethod
2024-08-13 16:36:33 +00:00
}
2022-08-04 13:58:00 +00:00
if ( ! getDolGlobalString ( $keyforparamid )) {
2024-08-13 16:36:33 +00:00
accessforbidden ( 'Setup of service ' . $keyforparamid . ' is not complete. Customer ID is missing' );
2022-08-04 13:58:00 +00:00
}
if ( ! getDolGlobalString ( $keyforparamsecret )) {
2024-08-13 16:36:33 +00:00
accessforbidden ( 'Setup of service ' . $keyforparamid . ' is not complete. Secret key is missing' );
2022-08-04 13:58:00 +00:00
}
/*
* Actions
*/
2024-08-31 17:26:46 +00:00
if ( $action == 'delete' && ( ! empty ( $user -> admin ) || $user -> id == GETPOSTINT ( 'userid' ))) {
$storage -> userid = GETPOSTINT ( 'userid' );
2022-08-04 13:58:00 +00:00
$storage -> clearToken ( $genericstring );
setEventMessages ( $langs -> trans ( 'TokenDeleted' ), null , 'mesgs' );
2023-06-05 13:20:59 +00:00
if ( empty ( $backtourl )) {
$backtourl = DOL_URL_ROOT . '/' ;
}
2022-08-04 13:58:00 +00:00
header ( 'Location: ' . $backtourl );
exit ();
}
2024-08-13 16:36:33 +00:00
if ( ! GETPOST ( 'code' ) && ! GETPOST ( 'error' )) {
dol_syslog ( " Page is called without the 'code' parameter defined " );
2022-08-04 13:58:00 +00:00
2026-02-25 18:38:55 +00:00
if ( empty ( $state ) || $state == 'none' ) {
// Generate a random state value to prevent CSRF attack. Store it into session juste after to check it when we will receive the callback from provider.
2026-02-25 21:46:27 +00:00
$state = 'none-' . bin2hex ( random_bytes ( 16 ));
2026-02-25 18:38:55 +00:00
}
2024-08-13 16:36:33 +00:00
// 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
2023-02-07 19:12:53 +00:00
// to the OAuth provider login page.
2022-08-04 13:58:00 +00:00
$_SESSION [ " backtourlsavedbeforeoauthjump " ] = $backtourl ;
$_SESSION [ " oauthkeyforproviderbeforeoauthjump " ] = $keyforprovider ;
$_SESSION [ 'oauthstateanticsrf' ] = $state ;
2024-08-13 16:36:33 +00:00
// Save more data into session
// No need to save more data in sessions. We have several info into $_SESSION['datafromloginform'], saved when form is posted with a click
2024-08-13 18:25:01 +00:00
// on "Login with Generic" with param actionlogin=login and beforeoauthloginredirect=generic, by the functions_genericoauth.php.
2024-08-13 16:36:33 +00:00
// Set approval_prompt. Note: A refresh token will be provided only if prompt is done.
if ( $forlogin ) {
$approval_prompt = getDolGlobalString ( 'OAUTH_' . $genericstring . '_FORCE_PROMPT_ON_LOGIN' , 'auto' ); // Can be 'force'
if ( method_exists ( $apiService , 'setApprouvalPrompt' )) {
2024-08-19 00:05:27 +00:00
$apiService -> setApprouvalPrompt ( $approval_prompt ); // @phan-suppress-current-line PhanUndeclaredMethod
2024-08-13 16:36:33 +00:00
}
} else {
if ( method_exists ( $apiService , 'setApprouvalPrompt' )) {
2024-08-19 00:05:27 +00:00
$apiService -> setApprouvalPrompt ( 'force' ); // @phan-suppress-current-line PhanUndeclaredMethod
2024-08-13 16:36:33 +00:00
}
}
2022-08-04 13:58:00 +00:00
// This may create record into oauth_state before the header redirect.
2024-08-13 16:36:33 +00:00
// 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).
2026-02-25 18:38:55 +00:00
//if ($state && $state != 'none') {
2026-03-14 18:35:11 +00:00
$url = $apiService -> getAuthorizationUri ( array ( 'client_id' => getDolGlobalString ( $keyforparamid ), 'response_type' => 'code' , 'state' => $state ));
2026-02-25 18:38:55 +00:00
//} else {
// $url = $apiService->getAuthorizationUri(array('client_id' => getDolGlobalString($keyforparamid), 'response_type' => 'code')); // Parameter state will be randomly generated
//}
2024-08-13 16:36:33 +00:00
// The redirect_uri is included into this $url
2024-08-13 18:25:01 +00:00
// Add scopes
2026-02-25 18:38:55 +00:00
if ( $statewithscopeonly ) {
$url .= '&scope=' . str_replace ( ',' , '+' , $statewithscopeonly );
}
2024-08-13 18:25:01 +00:00
2024-08-13 16:36:33 +00:00
// Add more param
2024-08-17 17:32:52 +00:00
$url .= '&nonce=' . bin2hex ( random_bytes ( 64 / 8 ));
2024-08-13 16:36:33 +00:00
if ( $forlogin ) {
// TODO Add param hd. What is it for ?
//$url .= 'hd=xxx';
2022-08-04 13:58:00 +00:00
2024-08-13 16:36:33 +00:00
if ( GETPOST ( 'username' )) {
$url .= '&login_hint=' . urlencode ( GETPOST ( 'username' ));
}
// Check that the redirect_uri that will be used is same than url of current domain
// Define $urlwithroot
global $dolibarr_main_url_root ;
$urlwithouturlroot = preg_replace ( '/' . preg_quote ( DOL_URL_ROOT , '/' ) . '$/i' , '' , trim ( $dolibarr_main_url_root ));
$urlwithroot = $urlwithouturlroot . DOL_URL_ROOT ; // This is to use external domain name found into config file
//$urlwithroot = DOL_MAIN_URL_ROOT; // This is to use same domain name than current
include DOL_DOCUMENT_ROOT . '/core/lib/geturl.lib.php' ;
$currentrooturl = getRootURLFromURL ( DOL_MAIN_URL_ROOT );
$externalrooturl = getRootURLFromURL ( $urlwithroot );
if ( $currentrooturl != $externalrooturl ) {
$langs -> load ( " errors " );
setEventMessages ( $langs -> trans ( " ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup " , $currentrooturl , $externalrooturl ), null , 'errors' );
$url = DOL_URL_ROOT ;
}
}
2026-02-25 18:38:55 +00:00
//var_dump($keyforurl, $url, $statewithscopeonly);exit;
2024-08-13 16:36:33 +00:00
// 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'))
2022-08-04 13:58:00 +00:00
header ( 'Location: ' . $url );
exit ();
2024-08-13 16:36:33 +00:00
} else {
// We are coming from the return of an OAuth2 provider page.
2024-10-02 15:31:42 +00:00
dol_syslog ( basename ( __FILE__ ) . " We are coming from the oauth provider page keyforprovider= " . $keyforprovider . " code= " . dol_trunc ( GETPOST ( 'code' ), 5 ));
2024-08-13 16:36:33 +00:00
// We must validate that the $state is the same than the one into $_SESSION['oauthstateanticsrf'], return error if not.
if ( isset ( $_SESSION [ 'oauthstateanticsrf' ]) && $state != $_SESSION [ 'oauthstateanticsrf' ]) {
//var_dump($_SESSION['oauthstateanticsrf']);exit;
print 'Value for state=' . dol_escape_htmltag ( $state ) . ' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.' ;
unset ( $_SESSION [ 'oauthstateanticsrf' ]);
} else {
// This was a callback request from service, get the token
try {
2024-08-13 18:25:01 +00:00
//var_dump($apiService); // OAuth\OAuth2\Service\Generic
2024-08-13 16:36:33 +00:00
//dol_syslog("_GET=".var_export($_GET, true));
$errorincheck = 0 ;
$db -> begin ();
2026-02-25 21:46:27 +00:00
$token = null ;
$last_insert_id = 0 ;
try {
// This requests the token from the received OAuth code (call of the endpoint)
// Result is stored into object managed by class DoliStorage into includes/OAuth/Common/Storage/DoliStorage.php and into database table llx_oauth_token
$token = $apiService -> requestAccessToken ( GETPOST ( 'code' ), $state );
'@phan-var-force OAuth\Common\Token\AbstractToken $token' ;
$storage = $apiService -> getStorage ();
2026-03-14 18:35:11 +00:00
/** @var OAuth\Common\Storage\DoliStorage $storage */
2026-02-27 13:42:17 +00:00
if ( property_exists ( $storage , 'last_insert_id' )) { // @phan-suppress-current-line PhanUndeclaredProperty
$last_insert_id = $storage -> last_insert_id ; // @phan-suppress-current-line PhanUndeclaredProperty
2026-02-25 21:46:27 +00:00
}
} catch ( Exception $e ) {
dol_syslog ( " Failed to get token with requestAccessToken: " . $e -> getMessage (), LOG_ERR );
setEventMessages ( " Failed to get token with requestAccessToken: " . $e -> getMessage (), null , 'errors' );
$errorincheck ++ ;
}
// The refresh token is inside the object token if the prompt was forced only. Otherwise, it may be found into extraParams section.
//$refreshtoken = $token->getRefreshToken();
//var_dump($refreshtoken);
dol_syslog ( " requestAccessToken complete " );
2024-08-17 17:32:52 +00:00
2024-08-13 16:36:33 +00:00
// The refresh token is inside the object token if the prompt was forced only.
//$refreshtoken = $token->getRefreshToken();
//var_dump($refreshtoken);
// Note: The extraparams has the 'id_token' than contains a lot of information about the user.
2026-03-14 18:35:11 +00:00
if ( $token ) {
2026-02-25 21:46:27 +00:00
$extraparams = $token -> getExtraParams ();
$scope = empty ( $extraparams [ 'scope' ]) ? '' : $extraparams [ 'scope' ];
$tokenstring = $token -> getAccessToken ();
// Update entry in llx_oauth_token to store the scope associated to the token into field "state" (field should be renamed).
// It is not stored by default by DoliStorage.
// TODO Update using $scope and $tokenstring and $last_insert_id
$refreshtoken = empty ( $extraparams [ 'refresh_token' ]) ? '' : $extraparams [ 'refresh_token' ];
if ( empty ( $refreshtoken )) {
$refreshtoken = $token -> getRefreshToken ();
}
if ( $last_insert_id ) {
$sqlupdate = " UPDATE " . MAIN_DB_PREFIX . " oauth_token " ;
$sqlupdate .= " SET state = ' " . ( empty ( $scope ) ? '' : $db -> escape ( $scope )) . " ', tokenstring = ' " . $db -> escape ( $tokenstring ) . " ', tokenstring_refresh = ' " . $db -> escape ( $refreshtoken ) . " ' " ;
$sqlupdate .= " WHERE rowid = " . (( int ) $last_insert_id );
$db -> query ( $sqlupdate );
//var_dump($scope, $token, $refreshtoken, $last_insert_id, $sqlupdate);exit;
}
}
2026-02-25 18:38:55 +00:00
2024-08-13 16:36:33 +00:00
$username = '' ;
$useremail = '' ;
// Extract the middle part, base64 decode, then json_decode it
/*
2024-08-13 18:25:01 +00:00
$jwt = explode ( '.' , $extraparams [ 'id_token' ]);
2024-08-13 16:36:33 +00:00
if ( ! empty ( $jwt [ 1 ])) {
$userinfo = json_decode ( base64_decode ( $jwt [ 1 ]), true );
2026-02-11 00:44:21 +00:00
dol_syslog ( " userinfo= " . formatLogObject ( $userinfo ));
2024-08-13 16:36:33 +00:00
$useremail = $userinfo [ 'email' ];
// We should make the steps of validation of id_token
// Verify that the state is the one expected
// TODO
2024-08-13 18:25:01 +00:00
// Verify that the ID token is properly signed by the issuer.
2024-08-13 16:36:33 +00:00
// TODO
// Verify that the value of the iss claim in the ID token is equal to https://accounts.google.com or accounts.google.com.
if ( $userinfo [ 'iss' ] != 'accounts.google.com' && $userinfo [ 'iss' ] != 'https://accounts.google.com' ) {
setEventMessages ( $langs -> trans ( 'Bad value for returned userinfo[iss]' ), null , 'errors' );
$errorincheck ++ ;
}
// Verify that the value of the aud claim in the ID token is equal to your app's client ID.
if ( $userinfo [ 'aud' ] != getDolGlobalString ( $keyforparamid )) {
setEventMessages ( $langs -> trans ( 'Bad value for returned userinfo[aud]' ), null , 'errors' );
$errorincheck ++ ;
}
// Verify that the expiry time (exp claim) of the ID token has not passed.
if ( $userinfo [ 'exp' ] <= dol_now ()) {
setEventMessages ( $langs -> trans ( 'Bad value for returned userinfo[exp]. Token expired.' ), null , 'errors' );
$errorincheck ++ ;
}
// 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.
// $userinfo['hd'] is the domain name of Gmail account.
// TODO
}
*/
if ( ! $errorincheck ) {
// If call back to url for a OAUTH2 login
if ( $forlogin ) {
dol_syslog ( " we received the login/email to log to, it is " . $useremail );
$tmparray = ( empty ( $_SESSION [ 'datafromloginform' ]) ? array () : $_SESSION [ 'datafromloginform' ]);
2024-12-04 09:31:48 +00:00
$entitytosearchuser = (( isset ( $tmparray [ 'entity' ]) && $tmparray [ 'entity' ] != '' ) ? $tmparray [ 'entity' ] : - 1 );
2024-08-13 16:36:33 +00:00
// Delete the old token
2024-08-13 18:25:01 +00:00
$storage -> clearToken ( $genericstring ); // Delete the token called ("Generic-".$storage->keyforprovider)
2024-08-13 16:36:33 +00:00
$tmpuser = new User ( $db );
2024-12-04 09:22:28 +00:00
$res = $tmpuser -> fetch ( 0 , '' , '' , 0 , $entitytosearchuser , $useremail , 0 , 1 ); // Load user. Can load with email_oauth2.
2024-08-13 16:36:33 +00:00
if ( $res > 0 ) {
$username = $tmpuser -> login ;
2024-08-13 18:25:01 +00:00
$_SESSION [ 'genericoauth_receivedlogin' ] = dol_hash ( $conf -> file -> instance_unique_id . $username , '0' );
dol_syslog ( 'We set $_SESSION[\'genericoauth_receivedlogin\']=' . $_SESSION [ 'genericoauth_receivedlogin' ]);
2024-08-13 16:36:33 +00:00
} else {
$errormessage = " Failed to login using '. $genericstring .'. User with the Email ' " . $useremail . " ' was not found " ;
if ( $entitytosearchuser > 0 ) {
$errormessage .= ' (' . $langs -> trans ( " Entity " ) . ' ' . $entitytosearchuser . ')' ;
}
$_SESSION [ " dol_loginmesg " ] = $errormessage ;
$errorincheck ++ ;
dol_syslog ( $errormessage );
}
}
} else {
// If call back to url for a OAUTH2 login
if ( $forlogin ) {
$_SESSION [ " dol_loginmesg " ] = " Failed to login using '. $genericstring .'. OAuth callback URL retrieves a token with non valid data " ;
$errorincheck ++ ;
}
}
if ( ! $errorincheck ) {
$db -> commit ();
} else {
$db -> rollback ();
}
$backtourl = $_SESSION [ " backtourlsavedbeforeoauthjump " ];
unset ( $_SESSION [ " backtourlsavedbeforeoauthjump " ]);
if ( empty ( $backtourl )) {
$backtourl = DOL_URL_ROOT . '/' ;
}
// If call back to this url was for a OAUTH2 login
if ( $forlogin ) {
2024-08-13 18:25:01 +00:00
// _SESSION['genericoauth_receivedlogin'] has been set to the key to validate the next test by function_genericoauth(), so we can make the redirect
2025-03-10 00:13:08 +00:00
$backtourl .= '?actionlogin=login&afteroauthloginreturn=generic&mainmenu=home' . ( $username ? '&username=' . urlencode ( $username ) : '' ) . '&token=' . newToken ();
2024-08-13 16:36:33 +00:00
if ( ! empty ( $tmparray [ 'entity' ])) {
$backtourl .= '&entity=' . $tmparray [ 'entity' ];
}
}
dol_syslog ( " Redirect now on backtourl= " . $backtourl );
header ( 'Location: ' . $backtourl );
exit ();
} catch ( Exception $e ) {
print $e -> getMessage ();
}
}
2022-08-04 13:58:00 +00:00
}
/*
* View
*/
// No view at all, just actions
$db -> close ();