TASK-207 Merge for ldap and ldapAdvanced

This commit is contained in:
Brayan Pereyra
2025-09-12 16:21:53 +00:00
parent 9cb66f4a4e
commit ea87d8aac6
20 changed files with 1011 additions and 121 deletions

View File

@@ -0,0 +1,727 @@
<?php
use ProcessMaker\Model\RbacAuthenticationSource;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
class AuthSources
{
private $authSourceUid;
private $arrayObjectClassFilter = [
"user" => "|(objectclass=inetorgperson)(objectclass=organizationalperson)(objectclass=person)(objectclass=user)",
"group" => "|(objectclass=posixgroup)(objectclass=group)(objectclass=groupofuniquenames)",
"department" => "|(objectclass=organizationalunit)"
];
private $arrayAttributes = [
"ldap" => ["uid" => "uid", "member" => "memberuid"], //OpenLDAP
"ad" => ["uid" => "samaccountname", "member" => "member"], //Active Directory
"ds" => ["uid" => "uid", "member" => "uniquemember"] //389 DS
];
private $arrayAttributesForUser = ["dn", "uid", "samaccountname", "givenname", "sn", "cn", "mail", "userprincipalname", "useraccountcontrol", "accountexpires", "manager"];
public function getListAuthSources($userUid, $start = 0, $limit = 0, $orderBy = '', $ascending = '' , $filter = '') {
try {
if ($limit == 0) {
$limit = $this->getConfigurationUser($userUid);
}
global $RBAC;
$criterias = $RBAC->getAuthenticationSources($start, $limit, $filter);
$dataSourceAuthentication = AuthenticationSourcePeer::doSelectRS($criterias['COUNTER']);
$dataSourceAuthentication->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$dataSourceAuthentication->next();
$row = $dataSourceAuthentication->getRow();
$total_sources = $row['CNT'];
if (!empty($orderBy) && ($ascending !== '') && defined("AuthenticationSourcePeer::" . $orderBy)) {
if ($ascending === '1') {
$criterias['LIST']->addAscendingOrderByColumn(constant("AuthenticationSourcePeer::" . $orderBy));
}
if ($ascending === '0') {
$criterias['LIST']->addDescendingOrderByColumn(constant("AuthenticationSourcePeer::" . $orderBy));
}
} else {
$criterias['LIST']->addAscendingOrderByColumn(AuthenticationSourcePeer::AUTH_SOURCE_NAME);
}
$dataset = AuthenticationSourcePeer::doSelectRS($criterias['LIST']);
$dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
global $RBAC;
$auth = $RBAC->getAllUsersByAuthSource();
$sources = [];
while ($dataset->next()) {
$row = $dataset->getRow();
$values = explode("_", $row["AUTH_SOURCE_PASSWORD"]);
foreach ($values as $value) {
if ($value == "2NnV3ujj3w") {
$row["AUTH_SOURCE_PASSWORD"] = G::decrypt($values[0], $row["AUTH_SOURCE_SERVER_NAME"]);
}
}
$label = G::LoadTranslation('ID_DISABLE');
if ($row['AUTH_SOURCE_ENABLED_TLS'] === "1") {
$label = G::LoadTranslation('ID_ENABLE');
}
$row['AUTH_SOURCE_ENABLED_TLS_LABEL'] = $label;
//additional information
$authSourceData = unserialize($row['AUTH_SOURCE_DATA']);
if (is_array($authSourceData)) {
$row = array_merge($row, $authSourceData);
}
$sources[] = $row;
$index = sizeof($sources) - 1;
$sources[$index]['CURRENT_USERS'] = isset($auth[$sources[$index]['AUTH_SOURCE_UID']]) ? $auth[$sources[$index]['AUTH_SOURCE_UID']] : 0;
}
$response = [
'success' => true,
'sources' => $sources,
'total_sources' => $total_sources
];
return $response;
} catch (Exception $exception) {
return ['success' => false, 'message' => $exception->getMessage()];
}
}
public function removeAuthSource($authSourceUid) {
try {
global $RBAC;
$RBAC->removeAuthSource($authSourceUid);
return ['success' => true];
} catch (Exception $exception) {
return ['success' => false, 'message' => $exception->getMessage()];
}
}
public function verifyAuthSourceName($authSourceName) {
try {
$authenticationSource = RbacAuthenticationSource::query()
->select(['AUTH_SOURCE_UID', 'AUTH_SOURCE_NAME'])
->where('AUTH_SOURCE_NAME', '=', $authSourceName)
->first();
$row = false;
$suggestName = '';
if (!empty($authenticationSource)) {
$row = $authenticationSource;
$lastAuthenticationSource = RbacAuthenticationSource::query()
->select(['AUTH_SOURCE_NAME'])
->where('AUTH_SOURCE_NAME', 'LIKE', "%{$authSourceName}%")
->orderBy('AUTH_SOURCE_NAME', 'desc')
->first();
if (!empty($lastAuthenticationSource)) {
$name = $lastAuthenticationSource->AUTH_SOURCE_NAME;
//get suggest name
$pieces = explode( ' ', $name);
$last = array_pop($pieces);
$number = trim($last, "()");
if ("({$number})" === $last) {
$number = intval($number) + 1;
$suggestName = implode('', $pieces) . " ({$number})";
} else {
$suggestName = $name . " (1)";
}
}
}
return ['success' => true, 'row' => $row, 'suggestName' => $suggestName];
} catch (Exception $exception) {
return ['success' => false, 'message' => $exception->getMessage()];
}
}
public function testConnection($authSourceData) {
try {
$authSourceConnectionData = $this->ldapConnection($authSourceData);
$response = ['success' => true, 'status' => 'OK'];
if ($authSourceConnectionData['startTLS'] === false) {
$response["message"] = G::LoadTranslation("ID_TLS_CERTIFICATE_IS_NOT_INSTALLED_IN_THE_SERVER");
}
return $response;
} catch (Exception $exception) {
return ['success' => false, 'message' => $exception->getMessage()];
}
}
public function saveAuthSource($authSourceData) {
try {
global $RBAC;
$arrayAuthenticationSourceData = $authSourceData;
$arrayAuthenticationSourceData['AUTH_SOURCE_VERSION'] = 3;
$ldapconection = $this->ldapConnection($arrayAuthenticationSourceData);
$authSourceData['AUTH_SOURCE_DATA']['LDAP_PAGE_SIZE_LIMIT'] = $this->getPageSizeLimit(
$ldapconection['connection'],
$arrayAuthenticationSourceData['AUTH_SOURCE_BASE_DN']
);
$authSourceData['AUTH_SOURCE_DATA']['LDAP_PAGE_SIZE_LIMIT'] = $this->getPageSizeLimit(false);
if ($authSourceData['AUTH_SOURCE_UID'] == '') {
$RBAC->createAuthSource($authSourceData);
} else {
$RBAC->updateAuthSource($authSourceData);
}
return ['success' => true];
} catch (Exception $exception) {
return ['success' => false, 'message' => $exception->getMessage()];
}
}
public function searchUsers($authSourceUid, $filters) {
try {
$listUsers = array();
$criteria = new Criteria("workflow");
$criteria->addSelectColumn(UsersPeer::USR_USERNAME);
$criteria->addSelectColumn(RbacUsersPeer::UID_AUTH_SOURCE);
$criteria->addJoin(UsersPeer::USR_UID, RbacUsersPeer::USR_UID);
$criteria->add(UsersPeer::USR_STATUS, "CLOSED", Criteria::NOT_EQUAL);
$rsCriteria = UsersPeer::doSelectRS($criteria);
$rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);
while ($rsCriteria->next()) {
$row = $rsCriteria->getRow();
$listUsers[strtolower($row["USR_USERNAME"])] = $row['UID_AUTH_SOURCE'];
}
//Get data
$arrayData = array();
$this->authSourceUid = $authSourceUid;
$result = $this->searchUsersLdap($filters['text'], $filters['start'], $filters['limit']);
/*
$ldapAdvanced = new LdapAdvanced();
$ldapAdvanced->sAuthSource = $authSourceUid;
$result = $ldapAdvanced->searchUsers($filters['text'], $filters['start'], $filters['limit']);
*/
foreach ($result['data'] as $value) {
$listUsersData = $value;
if (!isset($listUsers[strtolower($listUsersData['sUsername'])])) {
$listUsersData['STATUS'] = G::LoadTranslation('ID_NOT_IMPORTED');
$listUsersData['IMPORT'] = 1;
} elseif ($authSourceUid === $listUsers[strtolower($listUsersData['sUsername'])]) {
$listUsersData['STATUS'] = G::LoadTranslation('ID_IMPORTED');
$listUsersData['IMPORT'] = 0;
} else {
$listUsersData['STATUS'] = G::LoadTranslation('ID_CANNOT_IMPORT');
$listUsersData['IMPORT'] = 0;
}
$arrayData[] = $listUsersData;
}
return ['success' => true, 'status' => 'OK', 'resultTotal' => $result['numRecTotal'], 'resultRoot' => $arrayData];
} catch (Exception $exception) {
return ['success' => false, 'message' => $exception->getMessage()];
}
}
public function importUsers($authSourceUid, $usersImport) {
try {
global $RBAC;
$aFields = $RBAC->getAuthSource($authSourceUid);
$aAttributes = array();
if (isset($aFields['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE'])) {
$aAttributes = $aFields['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE'];
}
$usersCreated = '';
$countUsers = 0;
foreach ($usersImport as $sUser) {
$aUser = (array) $sUser;
$matches = array();
$aData = array();
$aData['USR_USERNAME'] = str_replace("*", "'", $aUser['sUsername']);
$aData["USR_PASSWORD"] = "00000000000000000000000000000000";
// note added by gustavo gustavo-at-colosa.com
// asign the FirstName and LastName variables
// add replace to change D*Souza to D'Souza by krlos
$aData['USR_FIRSTNAME'] = str_replace("*", "'", $aUser['sFirstname']);
$aData['USR_FIRSTNAME'] = ($aData['USR_FIRSTNAME'] == '') ? $aData['USR_USERNAME'] : $aData['USR_FIRSTNAME'];
$aData['USR_LASTNAME'] = str_replace("*", "'", $aUser['sLastname']);
$aData['USR_EMAIL'] = $aUser['sEmail'];
$aData['USR_DUE_DATE'] = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y') + 2));
$aData['USR_CREATE_DATE'] = date('Y-m-d H:i:s');
$aData['USR_UPDATE_DATE'] = date('Y-m-d H:i:s');
$aData['USR_BIRTHDAY'] = date('Y-m-d');
$aData['USR_STATUS'] = (isset($aUser['USR_STATUS'])) ? (($aUser['USR_STATUS'] == 'ACTIVE') ? 1 : 0) : 1;
$aData['USR_AUTH_TYPE'] = strtolower($aFields['AUTH_SOURCE_PROVIDER']);
$aData['UID_AUTH_SOURCE'] = $aFields['AUTH_SOURCE_UID'];
// validating with regexp if there are some missing * inside the DN string
// if it's so the is changed to the ' character
preg_match('/[a-zA-Z]\*[a-zA-Z]/', $aUser['sDN'], $matches);
foreach ($matches as $key => $match) {
$newMatch = str_replace('*', '\'', $match);
$aUser['sDN'] = str_replace($match, $newMatch, $aUser['sDN']);
}
$aData['USR_AUTH_USER_DN'] = $aUser['sDN'];
$usrRole = 'LURANA_OPERATOR';
if (!empty($aFields['AUTH_SOURCE_DATA']['USR_ROLE'])) {
//$usrRole = $aFields['AUTH_SOURCE_DATA']['USR_ROLE'];
}
$sUserUID = $RBAC->createUser($aData, $usrRole, $aFields['AUTH_SOURCE_NAME']);
$usersCreated .= $aData['USR_USERNAME'] . ' ';
$countUsers++;
$aData['USR_STATUS'] = (isset($aUser['USR_STATUS'])) ? $aUser['USR_STATUS'] : 'ACTIVE';
$aData['USR_UID'] = $sUserUID;
$aData['USR_ROLE'] = $usrRole;
$calendarObj = new Calendar();
$calendarObj->assignCalendarTo($sUserUID, '00000000000000000000000000000001', 'USER');
if (count($aAttributes)) {
foreach ($aAttributes as $value) {
if (isset($aUser[$value['attributeUser']])) {
$aData[$value['attributeUser']] = str_replace("*", "'", $aUser[$value['attributeUser']]);
if ($value['attributeUser'] == 'USR_STATUS') {
$evalValue = $aData[$value['attributeUser']];
$statusValue = $aData['USR_STATUS'];
$aData[$value['attributeUser']] = $statusValue;
}
}
}
}
$oUser = new Users();
$oUser->create($aData);
}
return ['success' => true];
} catch (Exception $exception) {
return ['success' => false, 'message' => $exception->getMessage()];
}
}
///=====================================================================================
///==== PRIVATE FUNCTIONS
///=====================================================================================
private function getPageSizeLimit($ldapcnn, $baseDn = '')
{
try {
$limit = 1000;
if ($ldapcnn === false) {
return $limit;
}
$searchResult = @ldap_search($ldapcnn, $baseDn, '(|(objectclass=*))', ['dn']);
$context = [
'baseDN' => $baseDn,
'filter' => '(|(objectclass=*))',
'attributes' => ['dn']
];
$this->stdLog($ldapcnn, 'ldap_search', $context);
if ($searchResult) {
$countEntries = ldap_count_entries($ldapcnn, $searchResult);
$this->stdLog($ldapcnn, 'ldap_count_entries');
if ($countEntries > 0) {
$limit = ($countEntries > $limit) ? $limit : $countEntries;
}
}
return $limit;
} catch (Exception $e) {
throw $e;
}
}
private function searchUsersLdap($keyword, $start = null, $limit = null) {
$arrayUser = [];
$totalUser = 0;
$countUser = 0;
$paged = !is_null($start) && !is_null($limit);
$rbac = RBAC::getSingleton();
if (is_null($rbac->authSourcesObj)) {
$rbac->authSourcesObj = new AuthenticationSource();
}
$arrayAuthenticationSourceData = $rbac->authSourcesObj->load($this->authSourceUid);
$attributeUserSet = [];
$attributeSetAdd = [];
if (
isset($arrayAuthenticationSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE']) && !empty($arrayAuthenticationSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE'])
) {
foreach ($arrayAuthenticationSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE'] as $value) {
$attributeSetAdd[] = $value['attributeLdap'];
$attributeUserSet[$value['attributeUser']] = $value['attributeLdap'];
}
}
$ldapcnn = $this->ldapConnection($arrayAuthenticationSourceData);
$ldapcnn = $ldapcnn['connection'];
//Get Users
if (!isset($arrayAuthenticationSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_USERS_FILTER'])) {
$arrayAuthenticationSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_USERS_FILTER'] = '';
}
$uidUserIdentifier = (isset($arrayAuthenticationSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_IDENTIFIER_FOR_USER'])) ? $arrayAuthenticationSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_IDENTIFIER_FOR_USER'] : 'uid';
$filterUsers = trim($arrayAuthenticationSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_USERS_FILTER']);
$filter = ($filterUsers != '') ? $filterUsers : '(' . $this->arrayObjectClassFilter['user'] . ')';
$filter = "(&$filter(|(dn=$keyword)(uid=$keyword)(samaccountname=$keyword)(givenname=$keyword)(sn=$keyword)(cn=$keyword)(mail=$keyword)(userprincipalname=$keyword)))";
$oSearch = @ldap_search($ldapcnn, $arrayAuthenticationSourceData['AUTH_SOURCE_BASE_DN'], $filter, array_merge($this->arrayAttributesForUser, $attributeSetAdd));
$context = [
'baseDN' => $arrayAuthenticationSourceData['AUTH_SOURCE_BASE_DN'],
'filter' => $filter,
'attribute' => array_merge($this->arrayAttributesForUser, $attributeSetAdd)
];
$this->stdLog($ldapcnn, 'ldap_search', $context);
if ($oError = ldap_errno($ldapcnn)) {
$this->log($ldapcnn, 'Error in Search users');
} else {
if ($oSearch) {
$entries = ldap_count_entries($ldapcnn, $oSearch);
$this->stdLog($ldapcnn, 'ldap_count_entries');
$totalUser = $entries;
if ($entries > 0) {
$oEntry = ldap_first_entry($ldapcnn, $oSearch);
$this->stdLog($ldapcnn, 'ldap_first_entry');
$countEntries = 0;
$flagNextRecord = true;
do {
$aAttr = $this->ldapGetAttributes($ldapcnn, $oEntry);
$sUsername = (isset($aAttr[$uidUserIdentifier])) ? $aAttr[$uidUserIdentifier] : '';
if ((is_array($sUsername) && !empty($sUsername)) || trim($sUsername) != '') {
$countUser++;
/* Active Directory userAccountControl Values
Normal Day to Day Values:
512 - Enable Account
514 - Disable account
544 - Account Enabled - Require user to change password at first logon
4096 - Workstation/server
66048 - Enabled, password never expires
66050 - Disabled, password never expires
262656 - Smart Card Logon Required
532480 - Domain controller
1 - script
2 - accountdisable
8 - homedir_required
16 - lockout
32 - passwd_notreqd
64 - passwd_cant_change
128 - encrypted_text_pwd_allowed
256 - temp_duplicate_account
512 - normal_account
2048 - interdomain_trust_account
4096 - workstation_trust_account
8192 - server_trust_account
65536 - dont_expire_password
131072 - mns_logon_account
262144 - smartcard_required
524288 - trusted_for_delegation
1048576 - not_delegated
2097152 - use_des_key_only
4194304 - dont_req_preauth
8388608 - password_expired
16777216 - trusted_to_auth_for_delegation
*/
$userCountControl = '';
//Active Directory, openLdap
if (isset($aAttr['useraccountcontrol'])) {
switch ($aAttr['useraccountcontrol']) {
case '512':
case '544':
case '66048':
case '66080':
$userCountControl = 'ACTIVE';
break;
case '514':
case '546':
case '66050':
case '66082':
case '2':
case '16':
case '8388608':
default:
$userCountControl = 'INACTIVE';
break;
}
}
//apache ldap
if (isset($aAttr['status'])) {
$userCountControl = strtoupper($aAttr['status']);
}
$aUserAttributes = [];
foreach ($attributeUserSet as $key => $value) {
if ($key == 'USR_STATUS') {
$aUserAttributes[$key] = ($userCountControl != '') ? $userCountControl : 'ACTIVE';
} elseif (isset($aAttr[$value])) {
$aUserAttributes[$key] = $aAttr[$value];
}
}
if ($paged) {
if ($countUser - 1 <= $start + $limit - 1) {
if ($start <= $countUser - 1) {
$arrayUser[] = array_merge($this->getUserDataFromAttribute($sUsername, $aAttr), $aUserAttributes);
}
} else {
$flagNextRecord = false;
}
} else {
$arrayUser[] = array_merge($this->getUserDataFromAttribute($sUsername, $aAttr), $aUserAttributes);
}
$countEntries++;
}
} while (($oEntry = ldap_next_entry($ldapcnn, $oEntry)) && $flagNextRecord);
}
}
}
return ($paged) ? ['numRecTotal' => $totalUser, 'data' => $arrayUser] : $arrayUser;
}
private function getUserDataFromAttribute($username, array $arrayAttributes)
{
try {
$keyMail = (isset($arrayAttributes['mail'])) ? 'mail' : ((isset($arrayAttributes['userprincipalname'])) ? 'userprincipalname' : 'nomail');
return [
'sUsername' => trim((is_array($username)) ? $username[0] : $username),
'sPassword' => trim((isset($arrayAttributes['userpassword'])) ? ((is_array($arrayAttributes['userpassword'])) ? $arrayAttributes['userpassword'][0] : $arrayAttributes['userpassword']) : ''),
'sFullname' => trim((isset($arrayAttributes['cn'])) ? ((is_array($arrayAttributes['cn'])) ? $arrayAttributes['cn'][0] : $arrayAttributes['cn']) : ''),
'sFirstname' => trim((isset($arrayAttributes['givenname'])) ? ((is_array($arrayAttributes['givenname'])) ? $arrayAttributes['givenname'][0] : $arrayAttributes['givenname']) : ''),
'sLastname' => trim((isset($arrayAttributes['sn'])) ? ((is_array($arrayAttributes['sn'])) ? $arrayAttributes['sn'][0] : $arrayAttributes['sn']) : ''),
'sEmail' => trim((isset($arrayAttributes[$keyMail])) ? ((is_array($arrayAttributes[$keyMail])) ? $arrayAttributes[$keyMail][0] : $arrayAttributes[$keyMail]) : ''),
'sDN' => trim($arrayAttributes['dn']),
'sManagerDN' => trim((isset($arrayAttributes['manager'])) ? ((is_array($arrayAttributes['manager'])) ? $arrayAttributes['manager'][0] : $arrayAttributes['manager']) : '')
];
} catch (Exception $e) {
throw $e;
}
}
private function ldapGetAttributes($ldapcnn, $entry)
{
try {
$arrayAttributes = [];
$arrayAttributes['dn'] = ldap_get_dn($ldapcnn, $entry);
$this->stdLog($ldapcnn, 'ldap_get_dn');
$arrayAux = ldap_get_attributes($ldapcnn, $entry);
$this->stdLog($ldapcnn, 'ldap_get_attributes');
for ($i = 0; $i <= $arrayAux['count'] - 1; $i++) {
$key = strtolower($arrayAux[$i]);
switch ($arrayAux[$arrayAux[$i]]['count']) {
case 0:
$arrayAttributes[$key] = '';
break;
case 1:
$arrayAttributes[$key] = $arrayAux[$arrayAux[$i]][0];
break;
default:
$arrayAttributes[$key] = $arrayAux[$arrayAux[$i]];
unset($arrayAttributes[$key]['count']);
break;
}
}
if (!isset($arrayAttributes['mail']) && isset($arrayAttributes['userprincipalname'])) {
$arrayAttributes['mail'] = $arrayAttributes['userprincipalname'];
}
return $arrayAttributes;
} catch (Exception $e) {
throw $e;
}
}
private function ldapConnection($authSourceData) {
$pass = explode('_', $authSourceData['AUTH_SOURCE_PASSWORD']);
// Removing sensitive data
$loggableAuthSource = $authSourceData;
unset($loggableAuthSource['AUTH_SOURCE_PASSWORD']);
foreach ($pass as $index => $value) {
if ($value == '2NnV3ujj3w') {
$authSourceData['AUTH_SOURCE_PASSWORD'] = G::decrypt($pass[0], $authSourceData['AUTH_SOURCE_SERVER_NAME']);
}
}
$ldapcnn = ldap_connect($authSourceData['AUTH_SOURCE_SERVER_NAME'], $authSourceData['AUTH_SOURCE_PORT']);
$this->stdLog($ldapcnn, 'ldap_connect', $loggableAuthSource);
$ldapServer = $authSourceData['AUTH_SOURCE_SERVER_NAME'] . ':' . $authSourceData['AUTH_SOURCE_PORT'];
ldap_set_option($ldapcnn, LDAP_OPT_PROTOCOL_VERSION, 3);
$this->stdLog($ldapcnn, 'ldap_set_option', $loggableAuthSource);
ldap_set_option($ldapcnn, LDAP_OPT_REFERRALS, 0);
$this->stdLog($ldapcnn, 'ldap_set_option', $loggableAuthSource);
$resultLDAPStartTLS = true;
if (isset($authSourceData['AUTH_SOURCE_ENABLED_TLS']) && $authSourceData['AUTH_SOURCE_ENABLED_TLS']) {
$resultLDAPStartTLS = @ldap_start_tls($ldapcnn);
$this->stdLog($ldapcnn, 'ldap_start_tls', $loggableAuthSource);
$ldapServer = 'TLS ' . $ldapServer;
}
if ($authSourceData['AUTH_ANONYMOUS'] == '1') {
$bBind = ldap_bind($ldapcnn);
$this->log($ldapcnn, 'bind $ldapServer like anonymous user');
} else {
$bBind = ldap_bind($ldapcnn, $authSourceData['AUTH_SOURCE_SEARCH_USER'], $authSourceData['AUTH_SOURCE_PASSWORD']);
$this->log($ldapcnn, 'bind $ldapServer with user ' . $loggableAuthSource['AUTH_SOURCE_SEARCH_USER']);
}
$this->stdLog($ldapcnn, 'ldap_bind', $loggableAuthSource);
$this->getDiagnosticMessage($ldapcnn);
if (!$bBind) {
$message = 'Unable to bind to server: ' . $ldapServer . 'LDAP-Errno: ' . ldap_errno($ldapcnn) . ' : ' . ldap_error($ldapcnn) . " \n";
throw new Exception($message);
}
return ['connection' =>$ldapcnn, 'startTLS' => $resultLDAPStartTLS];
}
private function getDiagnosticMessage($linkIdentifier)
{
//specific message
$keysError = [
[
'key' => 'USER_NOT_FOUND',
'code' => 525,
'message' => G::LoadTranslation('ID_LDAP_USER_NOT_FOUND_INVALID'),
], [
'key' => 'NOT_PERMITTED_TO_LOGON_AT_THIS_TIME',
'code' => 530,
'message' => G::LoadTranslation('ID_LDAP_NOT_PERMITTED_TO_LOGON_AT_THIS_TIME'),
], [
'key' => 'RESTRICTED_TO_SPECIFIC_MACHINES',
'code' => 531,
'message' => G::LoadTranslation('ID_LDAP_RESTRICTED_TO_SPECIFIC_MACHINES'),
], [
'key' => 'PASSWORD_EXPIRED',
'code' => 532,
'message' => G::LoadTranslation('ID_LDAP_PASSWORD_EXPIRED'),
], [
'key' => 'ACCOUNT_DISABLED',
'code' => 533,
'message' => G::LoadTranslation('ID_LDAP_ACCOUNT_DISABLED'),
], [
'key' => 'ACCOUNT_EXPIRED',
'code' => 701,
'message' => G::LoadTranslation('ID_LDAP_ACCOUNT_EXPIRED'),
], [
'key' => 'USER_MUST_RESET_PASSWORD',
'code' => 773,
'message' => G::LoadTranslation('ID_LDAP_USER_MUST_RESET_PASSWORD'),
]
];
$message = '';
ldap_get_option($linkIdentifier, LDAP_OPT_DIAGNOSTIC_MESSAGE, $messageError);
$this->stdLog($linkIdentifier, 'ldap_get_option', ['error' => $messageError]);
foreach ($keysError as $key => $value) {
if (strpos($messageError, (string) $value['code']) !== false) {
$message = $value['message'];
break;
}
}
//standard message
if (empty($message)) {
$errorNumber = ldap_errno($linkIdentifier);
$message = ldap_err2str($errorNumber) . '.';
}
if (empty($message)) {
$message = G::LoadTranslation('ID_LDAP_ERROR_CONNECTION');
}
Cache::put('ldapMessageError', $message, 120); //laravel 8.x the time parameter is in seconds.
$this->log($linkIdentifier, $messageError);
}
private function log($link, $text)
{
$logFile = PATH_DATA . 'logs/ldapAdvanced.log';
// Validate log file exists and is writable
if (!file_exists($logFile)) {
error_log('Log file does not exist: ' . $logFile);
throw new Exception('Log file does not exist: ' . $logFile);
}
if (!is_writable($logFile)) {
error_log('Log file is not writable: ' . $logFile);
throw new Exception('Log file is not writable: ' . $logFile);
}
$fpt = fopen($logFile, 'a');
$ldapErrorMsg = '';
$ldapErrorNr = 0;
if ($link != null) {
$ldapErrorNr = ldap_errno($link);
if ($ldapErrorNr != 0) {
$ldapErrorMsg = ldap_error($link);
$text = $ldapErrorMsg . ' : ' . $text;
}
}
// Log format: date hour ipaddress workspace ldapErrorNr
fwrite($fpt, sprintf("%s %s %s %s %s \n", date('Y-m-d H:i:s'), getenv('REMOTE_ADDR'), config('system.workspace'), $ldapErrorNr, $text));
fclose($fpt);
}
private function stdLog($link, $message = "", $context = [], $level = "info")
{
try {
if (empty($link)) {
switch ($level) {
case "error":
Log::channel(':ldapAdvanced')->error($message, Bootstrap::context($context));
break;
case "info":
default:
Log::channel(':ldapAdvanced')->info($message, Bootstrap::context($context));
break;
}
return;
}
$code = ldap_errno($link);
$detail = ldap_err2str($code);
$context["detail"] = $detail;
if ($code === 0) {
Log::channel(':ldapAdvanced')->info($message, Bootstrap::context($context));
} else {
Log::channel(':ldapAdvanced')->error($message, Bootstrap::context($context));
}
} catch (Exception $exception) {
return ['success' => false, 'message' => $exception->getMessage()];
}
}
private function getConfigurationUser($userUid) {
try {
$configurations = new Configurations();
$configurationData = $configurations->getConfiguration('authSourcesList', 'pageSize', '', $userUid);
return $configurationData['pageSize'] ?? 20;
} catch (Exception $exception) {
return ['success' => false, 'message' => $exception->getMessage()];
}
}
}

View File

@@ -443,9 +443,19 @@ class LdapAdvanced
*/
public function log($link, $text)
{
$logFile = PATH_DATA . "log/ldapAdvanced.log";
$logFile = PATH_DATA . 'logs/ldapAdvanced.log';
// Validate log file exists and is writable
if (!file_exists($logFile)) {
error_log("Log file does not exist: $logFile");
throw new Exception("Log file does not exist: $logFile");
}
if (!is_writable($logFile)) {
error_log("Log file is not writable: $logFile");
throw new Exception("Log file is not writable: $logFile");
}
if (!file_exists($logFile) || is_writable($logFile)) {
$fpt = fopen($logFile, "a");
$ldapErrorMsg = "";
$ldapErrorNr = 0;
@@ -462,9 +472,6 @@ class LdapAdvanced
// Log format: date hour ipaddress workspace ldapErrorNr
fwrite($fpt, sprintf("%s %s %s %s %s \n", date("Y-m-d H:i:s"), getenv("REMOTE_ADDR"), config("system.workspace"), $ldapErrorNr, $text));
fclose($fpt);
} else {
error_log("file $logFile is not writable ");
}
}
/**
@@ -1638,7 +1645,7 @@ class LdapAdvanced
$attributes = $authSource['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE'];
}
$usrRole = 'PROCESSMAKER_OPERATOR';
$usrRole = 'LURANA_OPERATOR';
if (!empty($authSource['AUTH_SOURCE_DATA']['USR_ROLE'])) {
$usrRole = $authSource['AUTH_SOURCE_DATA']['USR_ROLE'];
}
@@ -2272,7 +2279,7 @@ class LdapAdvanced
$sLastname = $user['sLastname'];
$sEmail = $user['sEmail'];
$sDn = $user['sDN'];
$usrRole = empty($user['usrRole']) ? 'PROCESSMAKER_OPERATOR' : $user['usrRole'];
$usrRole = empty($user['usrRole']) ? 'LURANA_OPERATOR' : $user['usrRole'];
$data = [];
$data['USR_USERNAME'] = $sUsername;

View File

@@ -0,0 +1,162 @@
<?php
use ProcessMaker\Model\RbacAuthenticationSource;
require_once 'classes/AuthSources.php';
try {
if (isset($_REQUEST['action']) === false) {
throw new Exception('No action was sent');
}
if (isset($_SESSION['USER_LOGGED']) === false) {
throw new Exception('There is no logged in user');
}
$action = $_REQUEST['action'];
$userUid = $_SESSION['USER_LOGGED'];
$responseProxy = ['success' => true];
switch ($action) {
case 'authSourcesList':
$start = $_REQUEST['start'] ?? 0;
$limit = $_REQUEST['limit'] ?? $limit_size;
$filter = $_REQUEST['textFilter'] ?? '';
$orderBy = $_REQUEST['orderBy'] ?? '';
$ascending = $_REQUEST['ascending'] ?? '';
$authSources = new AuthSources();
$responseProxy = $authSources->getListAuthSources($userUid, $start, $limit, $orderBy, $ascending, $filter);
break;
case 'authSourcesDelete':
if (!isset($_REQUEST['auth_uid'])) {
throw new Exception('No auth source UID was sent');
}
$authSourceUid = $_REQUEST['auth_uid'];
$authSources = new AuthSources();
$responseProxy = $authSources->removeAuthSource($authSourceUid);
break;
case 'authSourcesVerifyName':
if (empty($_REQUEST['AUTH_SOURCE_NAME'])) {
throw new Exception('No auth source UID was sent');
}
$authSourceName = $_REQUEST['AUTH_SOURCE_NAME'];
$authSources = new AuthSources();
$responseProxy = $authSources->verifyAuthSourceName($authSourceName);
break;
case 'authSourcesTestConnection':
if ($_REQUEST['AUTH_ANONYMOUS'] == '1') {
$_REQUEST['AUTH_SOURCE_SEARCH_USER'] = '';
$_REQUEST['AUTH_SOURCE_PASSWORD'] = '';
}
$authSourceData = $_REQUEST;
$authSourceData['AUTH_SOURCE_VERSION'] = 3;
$authSources = new AuthSources();
$responseProxy = $authSources->testConnection($authSourceData);
break;
case 'authSourcesSave':
$temporalData = $_REQUEST;
if (isset($temporalData['AUTH_SOURCE_SHOWGRID-checkbox'])) {
if ($temporalData['AUTH_SOURCE_SHOWGRID-checkbox'] == 'on') {
$temporalData['AUTH_SOURCE_SHOWGRID'] = 'on';
$attributes = G::json_decode($temporalData['AUTH_SOURCE_GRID_TEXT']);
$con = 1;
foreach ($attributes as $value) {
$temporalData['AUTH_SOURCE_GRID_ATTRIBUTE'][$con] = (array)$value;
$con++;
}
}
unset($temporalData['AUTH_SOURCE_SHOWGRID-checkbox']);
}
if ($temporalData['AUTH_ANONYMOUS'] == '1') {
$temporalData['AUTH_SOURCE_SEARCH_USER'] = '';
$temporalData['AUTH_SOURCE_PASSWORD'] = '';
}
unset($temporalData['AUTH_SOURCE_GRID_TEXT']);
unset($temporalData['DELETE1']);
unset($temporalData['DELETE2']);
unset($temporalData['AUTH_SOURCE_ATTRIBUTE_IDS']);
unset($temporalData['AUTH_SOURCE_SHOWGRID_FLAG']);
unset($temporalData['AUTH_SOURCE_GRID_TEXT']);
$commonFields = array('AUTH_SOURCE_UID', 'AUTH_SOURCE_NAME', 'AUTH_SOURCE_PROVIDER', 'AUTH_SOURCE_SERVER_NAME', 'AUTH_SOURCE_PORT', 'AUTH_SOURCE_ENABLED_TLS', 'AUTH_ANONYMOUS', 'AUTH_SOURCE_SEARCH_USER', 'AUTH_SOURCE_PASSWORD', 'AUTH_SOURCE_VERSION', 'AUTH_SOURCE_BASE_DN', 'AUTH_SOURCE_OBJECT_CLASSES', 'AUTH_SOURCE_ATTRIBUTES');
$authSourceData = $authSourceExtraData = array();
foreach ($temporalData as $sField => $sValue) {
if (in_array($sField, $commonFields)) {
$authSourceData[$sField] = $sValue;
} else {
$authSourceExtraData[$sField] = $sValue;
}
}
if (!isset($authSourceExtraData['AUTH_SOURCE_SHOWGRID']) || $authSourceExtraData['AUTH_SOURCE_SHOWGRID'] == 'off') {
unset($authSourceExtraData['AUTH_SOURCE_GRID_ATTRIBUTE']);
unset($authSourceExtraData['AUTH_SOURCE_SHOWGRID']);
}
$authSourceData['AUTH_SOURCE_DATA'] = $authSourceExtraData;
$authSources = new AuthSources();
$responseProxy = $authSources->saveAuthSource($authSourceData);
break;
case 'authSourcesImportSearchUsers':
if (!isset($_REQUEST['sUID'])) {
throw new Exception('No auth source UID was sent');
}
$authSourceUid = $_POST['sUID'];
$filters = [
'start'=> $_POST['start'] ?? 0,
'limit'=> $_POST['limit'] ?? ($_POST["pageSize"] ?? 10),
'text'=> $_POST['sKeyword'] ?? ''
];
$authSources = new AuthSources();
$responseProxy = $authSources->searchUsers($authSourceUid, $filters);
break;
case 'authSourcesImportUsers':
if (!isset($_REQUEST['UsersImport'])) {
throw new Exception('There are no users to import');
}
if (!isset($_REQUEST['AUTH_SOURCE_UID'])) {
throw new Exception('The auth source UID was not sent');
}
$authSourceUid = $_REQUEST['AUTH_SOURCE_UID'];
$usersImport = $_REQUEST['UsersImport'];
$usersImport = json_decode($usersImport, true);
$authSources = new AuthSources();
$responseProxy = $authSources->importUsers($authSourceUid, $usersImport);
break;
case 'authSourcesImportLoadDepartment':
$responseProxy['success'] = true;
break;
case 'authSourcesImportSaveDepartment':
$responseProxy['success'] = true;
break;
case 'authSourcesImportLoadGroup':
$responseProxy['success'] = true;
break;
case 'authSourcesImportSaveGroup':
$responseProxy['success'] = true;
break;
default:
throw new Exception('The action "' . $action . '" is not allowed');
break;
}
header('Content-Type: application/json');
echo json_encode($responseProxy, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} catch (Exception $exception) {
$responseProxy['success'] = false;
$responseProxy['message'] = $exception->getMessage();
header('Content-Type: application/json');
echo json_encode($responseProxy, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}

View File

@@ -306,6 +306,7 @@ switch ($function) {
// asign the FirstName and LastName variables
// add replace to change D*Souza to D'Souza by krlos
$aData['USR_FIRSTNAME'] = str_replace("*", "'", $aUser['sFirstname']);
$aData['USR_FIRSTNAME'] = ($aData['USR_FIRSTNAME'] == '') ? $aData['USR_USERNAME'] : $aData['USR_FIRSTNAME'];
$aData['USR_LASTNAME'] = str_replace("*", "'", $aUser['sLastname']);
$aData['USR_EMAIL'] = $aUser['sEmail'];
$aData['USR_DUE_DATE'] = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y') + 2));
@@ -325,16 +326,18 @@ switch ($function) {
}
$aData['USR_AUTH_USER_DN'] = $aUser['sDN'];
$usrRole = 'PROCESSMAKER_OPERATOR';
$usrRole = 'LURANA_OPERATOR';
if (!empty($aFields['AUTH_SOURCE_DATA']['USR_ROLE'])) {
$usrRole = $aFields['AUTH_SOURCE_DATA']['USR_ROLE'];
//$usrRole = $aFields['AUTH_SOURCE_DATA']['USR_ROLE'];
}
try {
//dd($aData, $usrRole, $aFields['AUTH_SOURCE_NAME']);
$sUserUID = $RBAC->createUser($aData, $usrRole, $aFields['AUTH_SOURCE_NAME']);
$usersCreated .= $aData['USR_USERNAME'] . ' ';
$countUsers++;
} catch (Exception $oError) {
dd($oError);
$G_PUBLISH = new Publisher();
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'login/showMessage', '', array('MESSAGE' => $oError->getMessage()));
G::RenderPage("publish", "blank");

View File

@@ -102,7 +102,8 @@
saveNewConnection(form) {
let formData = this.$refs.newConnection.formToFormData(form);
axios.post(this.$root.baseUrl() + "authSources/ldapAdvancedProxy.php?functionAccion=ldapSave", formData)
//axios.post(this.$root.baseUrl() + "authSources/ldapAdvancedProxy.php?functionAccion=ldapSave", formData)
axios.post(this.$root.baseUrl() + "authSources/authSourcesProxy?action=authSourcesSave", formData)
.then(response => {
response;
this.$refs.authenticationSources.refresh();

View File

@@ -98,7 +98,8 @@
},
data() {
return {
baseUrl: this.$root.baseUrl() + "authSources/authSources_Ajax?action=authSourcesList",
//baseUrl: this.$root.baseUrl() + "authSources/authSources_Ajax?action=authSourcesList",
baseUrl: this.$root.baseUrl() + "authSources/authSourcesProxy?action=authSourcesList",
columns: [
"AUTH_SOURCE_NAME",
"AUTH_SOURCE_PROVIDER",
@@ -193,9 +194,11 @@
return;
}
let formData = new FormData();
formData.append("action", "deleteAuthSource");
//formData.append("action", "deleteAuthSource");
formData.append("action", "authSourcesDelete");
formData.append("auth_uid", row.AUTH_SOURCE_UID);
axios.post(this.$root.baseUrl() + "authSources/authSources_Ajax", formData)
//axios.post(this.$root.baseUrl() + "authSources/authSources_Ajax", formData)
axios.post(this.$root.baseUrl() + "authSources/authSourcesProxy", formData)
.then(response => {
response;
this.refresh();

View File

@@ -4,8 +4,8 @@
<b-container fluid>
<b-row>
<b-col>
<b-form-group :label="$root.translation('ID_AVAILABLE_AUTHENTICATION_SOURCES')" description="">
<b-form-select v-model="form.availableAuthenticationSource"
<b-form-group v-show=false :label="$root.translation('ID_AVAILABLE_AUTHENTICATION_SOURCES')" description="">
<b-form-select v-show=false v-model="form.availableAuthenticationSource"
:options="availableAuthenticationSources"/>
</b-form-group>
<b-form-group :label="$root.translation('ID_NAME')">
@@ -380,12 +380,14 @@
test(form) {
let formDataForName = new FormData();
formDataForName.append("AUTH_SOURCE_NAME", form.name);
axios.post(this.$root.baseUrl() + "authSources/ldapAdvancedProxy.php?functionAccion=ldapVerifyName", formDataForName)
//axios.post(this.$root.baseUrl() + "authSources/ldapAdvancedProxy.php?functionAccion=ldapVerifyName", formDataForName)
axios.post(this.$root.baseUrl() + "authSources/authSourcesProxy.php?action=authSourcesVerifyName", formDataForName)
.then(response => {
//the name is valid
if (response.data.row === false || (this.form.uid !== "" && typeof this.form.uid === "string")) {
let formData = this.formToFormData(form);
axios.post(this.$root.baseUrl() + "authSources/ldapAdvancedProxy.php?functionAccion=ldapTestConnection", formData)
//axios.post(this.$root.baseUrl() + "authSources/ldapAdvancedProxy.php?functionAccion=ldapTestConnection", formData)
axios.post(this.$root.baseUrl() + "authSources/authSourcesProxy?action=authSourcesTestConnection", formData)
.then(response => {
//test is successful
if (response.data.status === "OK") {

View File

@@ -141,7 +141,8 @@
//validation name
let formData = new FormData();
formData.append("AUTH_SOURCE_NAME", this.fileContent.AUTH_SOURCE_NAME);
axios.post(this.$root.baseUrl() + "authSources/ldapAdvancedProxy.php?functionAccion=ldapVerifyName", formData)
//axios.post(this.$root.baseUrl() + "authSources/ldapAdvancedProxy.php?functionAccion=ldapVerifyName", formData)
axios.post(this.$root.baseUrl() + "authSources/authSourcesProxy.php?action=authSourcesVerifyName", formData)
.then(response => {
this.newName = response.data.row === false;
this.validationResult = response.data;

View File

@@ -89,7 +89,7 @@ Ext.onReady(function() {
var storeGridSearch = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
method: 'POST',
url: 'ldapAdvancedProxy.php',
url: 'authSourcesProxy.php',
timeout: 240000
}),
autoDestroy: true,
@@ -112,7 +112,7 @@ Ext.onReady(function() {
beforeload: function (store, opt)
{
this.baseParams = {
functionAccion: "searchUsers",
action: "authSourcesImportSearchUsers",
sUID: Fields.AUTH_SOURCE_UID,
sKeyword: searchUsersText.getValue(),
pageSize: pageSize
@@ -174,10 +174,10 @@ Ext.onReady(function() {
Ext.Ajax.request({
params: {
'UsersImport': Ext.encode(usersSelect),
'functionAccion': 'importUsers',
'action': 'authSourcesImportUsers',
'AUTH_SOURCE_UID': Fields.AUTH_SOURCE_UID
},
url : 'ldapAdvancedProxy.php',
url : 'authSourcesProxy.php',
success: function (returnData) {
var resp = Ext.decode(returnData.responseText);
Ext.MessageBox.hide();

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1 +1 @@
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="/lib/authenticationSources/favicon.ico"><title>authenticationSources</title><script src="/js/ext/translation.en.js"></script><script>var pageSize=10;</script><link href="/lib/authenticationSources/css/app.a1f82e8b.css" rel="preload" as="style"><link href="/lib/authenticationSources/css/chunk-vendors.2d065fb2.css" rel="preload" as="style"><link href="/lib/authenticationSources/js/app.d1165b72.js" rel="preload" as="script"><link href="/lib/authenticationSources/js/chunk-vendors.94a2becd.js" rel="preload" as="script"><link href="/lib/authenticationSources/css/chunk-vendors.2d065fb2.css" rel="stylesheet"><link href="/lib/authenticationSources/css/app.a1f82e8b.css" rel="stylesheet"></head><body><noscript><strong>We're sorry but authenticationSources doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id="app"></div><script src="/lib/authenticationSources/js/chunk-vendors.94a2becd.js"></script><script src="/lib/authenticationSources/js/app.d1165b72.js"></script></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="/lib/authenticationSources/favicon.ico"><title>authenticationSources</title><script src="/js/ext/translation.en.js"></script><script>var pageSize=10;</script><link href="/lib/authenticationSources/css/app.a1f82e8b.css" rel="preload" as="style"><link href="/lib/authenticationSources/css/chunk-vendors.26dc108e.css" rel="preload" as="style"><link href="/lib/authenticationSources/js/app.4050fbb5.js" rel="preload" as="script"><link href="/lib/authenticationSources/js/chunk-vendors.9b74053c.js" rel="preload" as="script"><link href="/lib/authenticationSources/css/chunk-vendors.26dc108e.css" rel="stylesheet"><link href="/lib/authenticationSources/css/app.a1f82e8b.css" rel="stylesheet"></head><body><noscript><strong>We're sorry but authenticationSources doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id="app"></div><script src="/lib/authenticationSources/js/chunk-vendors.9b74053c.js"></script><script src="/lib/authenticationSources/js/app.4050fbb5.js"></script></body></html>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long