TASK-237 Fix the login with AD users

This commit is contained in:
Brayan Pereyra
2025-09-22 22:29:47 +00:00
parent a777147d6f
commit 554b4ad14b
9 changed files with 926 additions and 65 deletions

View File

@@ -2,6 +2,7 @@
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use ProcessMaker\Exception\RBACException; use ProcessMaker\Exception\RBACException;
use ProcessMaker\Model\RbacAuthenticationSource;
class RBAC class RBAC
{ {
@@ -272,11 +273,6 @@ class RBAC
} }
} }
} }
if (!in_array('ldapAdvanced', $this->aRbacPlugins)) {
if (class_exists('ldapAdvanced')) {
$this->aRbacPlugins[] = 'ldapAdvanced';
}
}
} }
/** /**
@@ -895,43 +891,33 @@ class RBAC
*/ */
public function checkAutomaticRegister($strUser, $strPass) public function checkAutomaticRegister($strUser, $strPass)
{ {
$result = -1; //default return value, $result = -1;
$filters = array(
foreach ($this->aRbacPlugins as $className) { 'fields' => ['*'],
$plugin = new $className(); 'start' => 0,
if (method_exists($plugin, 'automaticRegister')) { 'limit'=> 1000
$criteria = new Criteria('rbac'); );
$criteria->add(AuthenticationSourcePeer::AUTH_SOURCE_PROVIDER, $className); $rbacAuthenticationSource = new RbacAuthenticationSource();
$criteria->addAscendingOrderByColumn(AuthenticationSourcePeer::AUTH_SOURCE_NAME); $authSourceReturn = $rbacAuthenticationSource->show($filters);
$dataset = AuthenticationSourcePeer::doSelectRS($criteria, Propel::getDbConnection('rbac_ro')); if (!empty($authSourceReturn['data'])) {
$dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); foreach ($authSourceReturn['data'] as $authSource) {
$dataset->next(); $authSource['AUTH_SOURCE_DATA'] = json_decode($authSource['AUTH_SOURCE_DATA'], true);
$row = $dataset->getRow(); if ((int)$authSource['AUTH_SOURCE_DATA']['AUTH_SOURCE_AUTO_REGISTER'] == 1) {
while (is_array($row)) { $ldapSource = new LdapSource();
$row = array_merge($row, unserialize($row['AUTH_SOURCE_DATA'])); $ldapSource->authSourceUid = $authSource['AUTH_SOURCE_UID'];
//Check if this authsource is enabled for AutoRegister, if not skip this try {
if ($row['AUTH_SOURCE_AUTO_REGISTER'] == 1) { $res = $ldapSource->automaticRegister($authSource, $strUser, $strPass);
$plugin->sAuthSource = $row['AUTH_SOURCE_UID']; if ($res == 1) {
$plugin->sSystem = $this->sSystem; return $res;
//search the usersRolesObj
//create the users in ProcessMaker
try {
$res = $plugin->automaticRegister($row, $strUser, $strPass);
if ($res == 1) {
return $res;
}
} catch (Exception $e) {
$message = $e->getMessage();
$context = [
'action' => 'ldapSynchronize',
'authSource' => $row
];
Log::channel(':ldapSynchronize')->error($message, Bootstrap::context($context));
} }
} catch (Exception $e) {
$message = $e->getMessage();
$context = [
'action' => 'ldapSynchronize',
'authSource' => $authSource
];
Log::channel(':ldapSynchronize')->error($message, Bootstrap::context($context));
} }
$dataset->next();
$row = $dataset->getRow();
} }
} }
} }
@@ -965,26 +951,16 @@ class RBAC
} }
} }
foreach ($this->aRbacPlugins as $className) { $ldapSource = new LdapSource();
if (strtolower($className) === strtolower($authType)) { $ldapSource->authSourceUid = $userFields['UID_AUTH_SOURCE'];
$plugin = new $className(); $bValidUser = $ldapSource->VerifyLogin($userFields['USR_AUTH_USER_DN'], $strPass);
$reflectionClass = new ReflectionClass($plugin);
if ($reflectionClass->hasConstant('AUTH_TYPE')) {
return $plugin->VerifyLogin($userFields['USR_USERNAME'], $strPass);
}
$plugin->sAuthSource = $userFields['UID_AUTH_SOURCE'];
$plugin->sSystem = $this->sSystem;
$bValidUser = $plugin->VerifyLogin($userFields['USR_AUTH_USER_DN'], $strPass); if ($bValidUser === true) {
if ($bValidUser === true) { return ($userFields['USR_UID']);
return ($userFields['USR_UID']); } else {
} else { return -2; //wrong password
return -2; //wrong password
}
}
} }
//return -5; //invalid authentication source
return -5; //invalid authentication source
} }
/** /**

View File

@@ -218,9 +218,9 @@ class AuthSources
*/ */
public function testConnection($authSourceData) { public function testConnection($authSourceData) {
try { try {
$authSourceData = $this->verifyEditAuthSourceData($authSourceData);
$ldapSource = new LdapSource(); $ldapSource = new LdapSource();
$authSourceConnectionData = $ldapSource->ldapConnection($authSourceData); $authSourceConnectionData = $ldapSource->ldapConnection($authSourceData);
$connectionEstablished = isset($authSourceConnectionData['connection']) && $authSourceConnectionData['connection'];
$response = ['success' => true, 'status' => 'OK']; $response = ['success' => true, 'status' => 'OK'];
if ($authSourceConnectionData['startTLS'] === false) { if ($authSourceConnectionData['startTLS'] === false) {
@@ -253,6 +253,7 @@ class AuthSources
try { try {
$ldapSource = new LdapSource(); $ldapSource = new LdapSource();
$authSourceData['AUTH_SOURCE_VERSION'] = 3; $authSourceData['AUTH_SOURCE_VERSION'] = 3;
$authSourceData = $this->verifyEditAuthSourceData($authSourceData);
$ldapConnection = $ldapSource->ldapConnection($authSourceData); $ldapConnection = $ldapSource->ldapConnection($authSourceData);
if (!isset($ldapConnection['connection']) || !$ldapConnection['connection']) { if (!isset($ldapConnection['connection']) || !$ldapConnection['connection']) {
@@ -409,7 +410,6 @@ class AuthSources
} }
$sUserUID = $RBAC->createUser($aData, $usrRole, $authSourceReturn['AUTH_SOURCE_NAME']); $sUserUID = $RBAC->createUser($aData, $usrRole, $authSourceReturn['AUTH_SOURCE_NAME']);
// Set USR_STATUS for User model (string format) // Set USR_STATUS for User model (string format)
$aData['USR_STATUS'] = (isset($aUser['USR_STATUS'])) ? $aUser['USR_STATUS'] : 'ACTIVE'; $aData['USR_STATUS'] = (isset($aUser['USR_STATUS'])) ? $aUser['USR_STATUS'] : 'ACTIVE';
$aData['USR_UID'] = $sUserUID; $aData['USR_UID'] = $sUserUID;
@@ -776,6 +776,29 @@ class AuthSources
return ['success' => false, 'message' => $exception->getMessage()]; return ['success' => false, 'message' => $exception->getMessage()];
} }
} }
private function verifyEditAuthSourceData($authSourceData) {
try {
if (!empty($authSourceData['AUTH_SOURCE_UID'])) {
if (empty($authSourceData['AUTH_SOURCE_PASSWORD'])) {
$filters = [
'fields' => ['AUTH_SOURCE_PASSWORD'],
'conditions' => ['AUTH_SOURCE_UID'=> $authSourceData['AUTH_SOURCE_UID']]
];
$rbacAuthenticationSource = new RbacAuthenticationSource();
$authSourceReturn = $rbacAuthenticationSource->show($filters);
if (!empty($authSourceReturn['data']) && !empty($authSourceReturn['data'][0]['AUTH_SOURCE_PASSWORD'])) {
$authSourceData['AUTH_SOURCE_PASSWORD'] = G::decrypt($authSourceReturn['data'][0]['AUTH_SOURCE_PASSWORD'], URL_KEY);
}
}
}
return $authSourceData;
} catch (Exception $exception) {
return [];
}
}
/** /**
* Filters and organizes departments based on parent-child relationships * Filters and organizes departments based on parent-child relationships
* *
@@ -969,7 +992,7 @@ class AuthSources
$groupwf = new Groupwf(); $groupwf = new Groupwf();
$filters = [ $filters = [
'start' => 0, 'limit' => 100000, 'start' => 0, 'limit' => 100000,
'conditions' => ['GRP_LDAP_DN' => ['!=', '']] 'conditions' => ['GRP_LDAP_DN', '!=', '']
]; ];
$allGroups = $groupwf->show($filters); $allGroups = $groupwf->show($filters);
return $allGroups['data'] ?? []; return $allGroups['data'] ?? [];

View File

@@ -1,6 +1,7 @@
<?php <?php
use ProcessMaker\Model\RbacAuthenticationSource; use ProcessMaker\Model\RbacAuthenticationSource;
use ProcessMaker\Model\RbacUsers;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
@@ -13,6 +14,7 @@ class LdapSource
public $authSourceUid; public $authSourceUid;
public $ldapcnn = null; public $ldapcnn = null;
public $terminatedOu; public $terminatedOu;
private $arrayDepartmentUserSynchronizedChecked = [];
private $arrayObjectClassFilter = [ private $arrayObjectClassFilter = [
"user" => "|(objectclass=inetorgperson)(objectclass=organizationalperson)(objectclass=person)(objectclass=user)", "user" => "|(objectclass=inetorgperson)(objectclass=organizationalperson)(objectclass=person)(objectclass=user)",
@@ -648,4 +650,812 @@ class LdapSource
return $result; return $result;
} }
//-------------------------
public function automaticRegister($authSource, $strUser, $strPass)
{
$rbac = RBAC::getSingleton();
$user = $this->searchUserByUid($strUser);
$result = 0;
if (!empty($user)) {
if ($this->VerifyLogin($user['sUsername'], $strPass) === true) {
$result = 1;
}
if ($result == 0 && $this->VerifyLogin($user['sDN'], $strPass) === true) {
$result = 1;
}
} else {
return 0;
}
if ($result == 0) {
$filters = ['conditions' => ['AUTH_SOURCE_UID'=> $this->authSourceUid]];
$rbacAuthenticationSource = new RbacAuthenticationSource();
$authSourceReturn = $rbacAuthenticationSource->show($filters);
$authenticationSourceData = $authSourceReturn['data'][0];
$authenticationSourceData['AUTH_SOURCE_DATA'] = json_decode($authenticationSourceData['AUTH_SOURCE_DATA'], true);
$attributes = [];
if (isset($authSource['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE'])) {
$attributes = $authSource['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE'];
}
$usrRole = 'LURANA_OPERATOR';
if (!empty($authSource['AUTH_SOURCE_DATA']['USR_ROLE'])) {
$usrRole = $authSource['AUTH_SOURCE_DATA']['USR_ROLE'];
}
$data = [];
$data['USR_USERNAME'] = $user['sUsername'];
$data["USR_PASSWORD"] = "00000000000000000000000000000000";
$data['USR_FIRSTNAME'] = $user['sFirstname'];
$data['USR_LASTNAME'] = $user['sLastname'];
$data['USR_EMAIL'] = $user['sEmail'];
$data['USR_DUE_DATE'] = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y') + 2));
$data['USR_CREATE_DATE'] = date('Y-m-d H:i:s');
$data['USR_UPDATE_DATE'] = date('Y-m-d H:i:s');
$data['USR_BIRTHDAY'] = date('Y-m-d');
$data['USR_STATUS'] = (isset($user['USR_STATUS'])) ? (($user['USR_STATUS'] == 'ACTIVE') ? 1 : 0) : 1;
$data['USR_AUTH_TYPE'] = strtolower($authSource['AUTH_SOURCE_PROVIDER']);
$data['UID_AUTH_SOURCE'] = $authSource['AUTH_SOURCE_UID'];
$data['USR_AUTH_USER_DN'] = $user['sDN'];
$data['USR_ROLE'] = $usrRole;
if (!empty($attributes)) {
foreach ($attributes as $value) {
if (isset($user[$value['attributeUser']])) {
$data[$value['attributeUser']] = str_replace("*", "'", $user[$value['attributeUser']]);
if ($value['attributeUser'] == 'USR_STATUS') {
$evalValue = $data[$value['attributeUser']];
$statusValue = (isset($user['USR_STATUS'])) ? $user['USR_STATUS'] : 'ACTIVE';
$data[$value['attributeUser']] = $statusValue;
}
}
}
}
//req - accountexpires
if (isset($user["USR_DUE_DATE"]) && $user["USR_DUE_DATE"] != '') {
$data["USR_DUE_DATE"] = $this->convertDateADtoPM($user["USR_DUE_DATE"]);
}
//end
$userUid = $rbac->createUser($data, $usrRole);
$data['USR_UID'] = $userUid;
$users = new Users();
$data['USR_STATUS'] = (isset($user['USR_STATUS'])) ? $user['USR_STATUS'] : 'ACTIVE';
$users->create($data);
$this->log(null, "Automatic Register for user $strUser ");
$result = 1;
}
return $result;
}
public function searchUserByUid($keyword, $identifier = "")
{
try {
$arrayUserData = [];
$filters = ['conditions' => ['AUTH_SOURCE_UID'=> $this->authSourceUid]];
$rbacAuthenticationSource = new RbacAuthenticationSource();
$authSourceReturn = $rbacAuthenticationSource->show($filters);
$authenticationSourceData = $authSourceReturn['data'][0];
$authenticationSourceData['AUTH_SOURCE_DATA'] = json_decode($authenticationSourceData['AUTH_SOURCE_DATA'], true);
$authenticationSourceData['AUTH_SOURCE_PASSWORD'] = G::decrypt($authenticationSourceData['AUTH_SOURCE_PASSWORD'], URL_KEY);
if (is_null($this->ldapcnn)) {
$ldapcnn = $this->ldapConnection($authenticationSourceData);
$this->ldapcnn = $ldapcnn['connection'];
}
$ldapcnn = $this->ldapcnn;
//Get User
$attributeUserSet = [];
$attributeSetAdd = [];
if (
isset($authenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"]) && !empty($authenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"])
) {
foreach ($authenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"] as $value) {
$attributeSetAdd[] = $value["attributeLdap"];
$attributeUserSet[$value["attributeUser"]] = $value["attributeLdap"];
}
}
$uidUserIdentifier = (isset($authenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"])) ? $authenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"] : "uid";
$filter2 = "";
if ($identifier != "" && $identifier != $uidUserIdentifier) {
$filter2 = "($identifier=$keyword)";
}
$filter = "(&(" . $this->arrayObjectClassFilter["user"] . ")(|($uidUserIdentifier=$keyword)$filter2))";
$searchResult = @ldap_search($ldapcnn, $authenticationSourceData["AUTH_SOURCE_BASE_DN"], $filter, array_merge($this->arrayAttributesForUser, $attributeSetAdd));
$context = [
"baseDN" => $authenticationSourceData["AUTH_SOURCE_BASE_DN"],
"filter" => $filter,
"attribute" => array_merge($this->arrayAttributesForUser, $attributeSetAdd)
];
$this->stdLog($ldapcnn, "ldap_search", $context);
if ($error = ldap_errno($ldapcnn)) {
$messageError = ldap_err2str($error);
Cache::put('ldapMessageError', $messageError, 120); //laravel 8.x the time parameter is in seconds.
//
} else {
if ($searchResult) {
$numEntries = ldap_count_entries($ldapcnn, $searchResult);
$this->stdLog($ldapcnn, "ldap_count_entries");
if ($numEntries > 0) {
$entry = ldap_first_entry($ldapcnn, $searchResult);
$this->stdLog($ldapcnn, "ldap_first_entry");
$arrayUserLdap = $this->ldapGetAttributes($ldapcnn, $entry);
$username = (isset($arrayUserLdap[$uidUserIdentifier])) ? $arrayUserLdap[$uidUserIdentifier] : "";
if ((is_array($username) && !empty($username)) || trim($username) != "") {
$userCountControl = "";
//Active Directory, OpenLDAP
if (isset($arrayUserLdap["useraccountcontrol"])) {
switch ($arrayUserLdap["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($arrayUserLdap["status"])) {
$userCountControl = strtoupper($arrayUserLdap["status"]);
}
$aUserAttributes = [];
foreach ($attributeUserSet as $key => $value) {
if ($key == "USR_STATUS") {
$aUserAttributes[$key] = ($userCountControl != "") ? $userCountControl : "ACTIVE";
} else {
if (isset($arrayUserLdap[$value])) {
$aUserAttributes[$key] = $arrayUserLdap[$value];
}
}
}
$arrayUserData = array_merge($this->getUserDataFromAttribute($username, $arrayUserLdap), $aUserAttributes);
}
}
}
}
return $arrayUserData;
} catch (Exception $e) {
throw $e;
}
}
public function VerifyLogin($strUser, $strPass)
{
if (is_array($strUser)) {
$strUser = $strUser[0];
} else {
$strUser = trim($strUser);
}
if ($strUser == "") {
return -1;
}
if (strlen($strPass) == 0) {
return -2;
}
$userDn = $strUser;
$ldapcnn = null;
$validUserPass = 1;
try {
$filters = ['conditions' => ['AUTH_SOURCE_UID'=> $this->authSourceUid]];
$rbacAuthenticationSource = new RbacAuthenticationSource();
$authSourceReturn = $rbacAuthenticationSource->show($filters);
$authenticationSourceData = $authSourceReturn['data'][0];
$authenticationSourceData['AUTH_SOURCE_DATA'] = json_decode($authenticationSourceData['AUTH_SOURCE_DATA'], true);
if (
isset($authenticationSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_SHOWGRID']) &&
$authenticationSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_SHOWGRID'] == 'on'
) {
$setAttributes = 1;
}
$filters = [
'fields' => ['USR_USERNAME', 'USR_UID'],
'conditions' => [
'UID_AUTH_SOURCE' => $authenticationSourceData["AUTH_SOURCE_UID"],
'USR_AUTH_USER_DN' => $strUser,
['USR_USERNAME', '!=', '']
]
];
$rbacUsers = new RbacUsers();
$usersByAuthSource = $rbacUsers->show($filters);
if (!empty($usersByAuthSource['data'] && !empty($usersByAuthSource['data'][0]))) {
$usrName = $usersByAuthSource['data'][0]['USR_USERNAME'];
$usrUid = $usersByAuthSource['data'][0]['USR_UID'];
} else {
return -1;
}
$verifiedUser = $this->searchUserByUid($usrName, $authenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"]);
if (empty($verifiedUser) || trim($verifiedUser["sDN"]) == null) {
return -1;
}
/*
if ($verifiedUser["sDN"] != $strUser || $setAttributes == 1) {
$userDn = $verifiedUser['sDN'];
// Update data
$user = new User();
$arrayUserData = $user->getUserRecordByPk($usrUid, [], false);
$result = $this->ldapUserUpdateByDnAndData(
$this->ldapcnn,
$authenticationSourceData,
$userDn,
[$arrayUserData['USR_USERNAME'] => $arrayUserData]
);
//Update DN
$con = Propel::getConnection(RbacUsersPeer::DATABASE_NAME);
// select set
$c1 = new Criteria("rbac");
$c1->add(RbacUsersPeer::UID_AUTH_SOURCE, $authenticationSourceData["AUTH_SOURCE_UID"]);
$c1->add(RbacUsersPeer::USR_AUTH_USER_DN, $strUser);
// update set
$c2 = new Criteria("rbac");
$c2->add(RbacUsersPeer::USR_AUTH_USER_DN, $userDn);
BasePeer::doUpdate($c1, $c2, $con);
}
*/
//Check ldap connection for user
$authenticationSourceData["AUTH_ANONYMOUS"] = "0";
$authenticationSourceData["AUTH_SOURCE_SEARCH_USER"] = $userDn;
$authenticationSourceData["AUTH_SOURCE_PASSWORD"] = $strPass;
$ldapcnn = $this->ldapConnection($authenticationSourceData);
$ldapcnn = $ldapcnn['connection'];
$flagUpdate = false;
switch (hexdec(ldap_errno($ldapcnn))) {
case 0:
//0x00
$flagUpdate = true;
$statusRbac = 1;
$statusUser = 'ACTIVE';
break;
case 52:
case 88:
case 94:
//0x34, 0x58, 0x5e
//LDAP_UNAVAILABLE
//LDAP_USER_CANCELLED
//LDAP_NO_RESULTS_RETURNED
$flagUpdate = true;
$statusRbac = 0;
$statusUser = 'INACTIVE';
break;
default:
break;
}
if ($flagUpdate) {
$setValues = [
'USR_AUTH_USER_DN' => $userDn,
'USR_STATUS' => $statusRbac,
'USR_FIRSTNAME' => ''
];
$conditions = [
'UID_AUTH_SOURCE' =>$authenticationSourceData["AUTH_SOURCE_UID"],
'USR_AUTH_USER_DN' => $strUser,
'USR_STATUS' => 1
];
$rbacUsers = new RbacUsers();
$rbacUsers->updateData($setValues, $conditions);
$columnsWf = [];
$columnsWf['USR_UID'] = $usrUid;
$columnsWf['USR_STATUS'] = $statusUser;
$oUser = new Users();
$oUser->update($columnsWf);
}
$attributes = $authenticationSourceData["AUTH_SOURCE_DATA"];
if (!isset($attributes['AUTH_SOURCE_RETIRED_OU'])) {
$attributes['AUTH_SOURCE_RETIRED_OU'] = '';
}
/*
$attributes["AUTH_SOURCE_RETIRED_OU"] ahora es igual a ''
dd('A punto', $verifiedUser, $usrName, $attributes["AUTH_SOURCE_RETIRED_OU"]);
// Check if the user is in the terminated organizational unit
if (!empty($verifiedUser) && $this->userIsTerminated($usrName, $attributes["AUTH_SOURCE_RETIRED_OU"])) {
$this->deactivateUser($usrName);
$this->log($ldapcnn, "user $strUser is member of Remove OU, deactivating this user.");
return -3;
}
*/
$validUserPass = ldap_errno($ldapcnn) == 0;
} catch (Exception $e) {
$context = [
"action" => "ldapSynchronize",
"authSource" => $authenticationSourceData
];
$message = $e->getMessage();
Log::channel(':ldapSynchronize')->error($message, Bootstrap::context($context));
$validUserPass = -5;
}
if ($validUserPass == 1) {
$this->log($ldapcnn, "sucessful login user " . $userDn);
} else {
$this->log($ldapcnn, "failure authentication for user $strUser");
}
return $validUserPass;
}
public function deactivateUser($userUid)
{
if (!class_exists('RbacUsers')) {
require_once(PATH_RBAC . 'model/RbacUsers.php');
}
$con = Propel::getConnection(RbacUsersPeer::DATABASE_NAME);
// select set
$c1 = new Criteria('rbac');
$c1->add(RbacUsersPeer::USR_USERNAME, $userUid);
// update set
$c2 = new Criteria('rbac');
$c2->add(RbacUsersPeer::USR_STATUS, '0');
BasePeer::doUpdate($c1, $c2, $con);
if (!class_exists('Users')) {
require_once('classes/model/Users.php');
}
$con = Propel::getConnection(UsersPeer::DATABASE_NAME);
// select set
$c1 = new Criteria('workflow');
$c1->add(UsersPeer::USR_USERNAME, $userUid);
// update set
$c2 = new Criteria('workflow');
$c2->add(UsersPeer::USR_STATUS, 'INACTIVE');
$c2->add(UsersPeer::DEP_UID, '');
BasePeer::doUpdate($c1, $c2, $con);
}
public function userIsTerminated($userUid, $sOuTerminated)
{
$terminated = false;
$aLdapUsers = $this->getUsersFromDepartmentByName($sOuTerminated);
foreach ($aLdapUsers as $aLdapUser) {
if ($aLdapUser['sUsername'] == $userUid) {
$terminated = true;
break;
}
}
return $terminated;
}
public function getUsersFromDepartmentByName($departmentName)
{
$dFilter = "(&(" . $this->arrayObjectClassFilter["department"] . ")(ou=" . $departmentName . "))";
$aUsers = [];
$filters = ['conditions' => ['AUTH_SOURCE_UID'=> $this->authSourceUid]];
$rbacAuthenticationSource = new RbacAuthenticationSource();
$authSourceReturn = $rbacAuthenticationSource->show($filters);
$authenticationSourceData = $authSourceReturn['data'][0];
$authenticationSourceData['AUTH_SOURCE_DATA'] = json_decode($authenticationSourceData['AUTH_SOURCE_DATA'], true);
$authenticationSourceData['AUTH_SOURCE_PASSWORD'] = G::decrypt($authenticationSourceData['AUTH_SOURCE_PASSWORD'], URL_KEY);
if (is_null($this->ldapcnn)) {
$ldapcnn = $this->ldapConnection($authenticationSourceData);
$this->ldapcnn = $ldapcnn['connection'];
}
$ldapcnn = $this->ldapcnn;
$oSearch = @ldap_search($ldapcnn, $authenticationSourceData["AUTH_SOURCE_BASE_DN"], $dFilter, $this->arrayAttributesForUser);
$context = [
"baseDN" => $authenticationSourceData["AUTH_SOURCE_BASE_DN"],
"filter" => $dFilter,
"attributes" => $this->arrayAttributesForUser
];
$this->stdLog($ldapcnn, "ldap_search", $context);
if ($oError = ldap_errno($ldapcnn)) {
return $aUsers;
} else {
if ($oSearch) {
//get the departments from the ldap entries
if (ldap_count_entries($ldapcnn, $oSearch) > 0) {
$this->stdLog($ldapcnn, "ldap_count_entries");
$oEntry = ldap_first_entry($ldapcnn, $oSearch);
$this->stdLog($ldapcnn, "ldap_first_entry");
do {
$aAttr = $this->ldapGetAttributes($ldapcnn, $oEntry);
$result = $this->ldapGetUsersFromDepartment("GET", $aAttr["dn"]);
foreach ($result as $item) {
$aUsers[] = $item;
}
} while ($oEntry = ldap_next_entry($ldapcnn, $oEntry));
}
}
return $aUsers;
}
}
public function ldapGetUsersFromDepartment($option, $dn, array $arrayData = [])
{
try {
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > START");
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > \$dn ----> $dn");
$arrayUser = [];
$totalUser = 0;
$countUser = 0;
//Set variables
$dn = trim($dn);
$rbac = RBAC::getSingleton();
if (is_null($rbac->authSourcesObj)) {
$rbac->authSourcesObj = new AuthenticationSource();
}
$arrayAuthenticationSourceData = $rbac->authSourcesObj->load($this->sAuthSource);
$this->ldapcnn = $this->ldapConnection($arrayAuthenticationSourceData);
$ldapcnn = $this->ldapcnn;
//Get Users
$limit = $this->getPageSizeLimitByData($arrayAuthenticationSourceData);
$flagError = false;
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"] . ")";
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > \$filter ----> $filter");
$cookie = '';
do {
$searchResult = @ldap_list(
$ldapcnn,
$dn,
$filter,
$this->arrayAttributesForUser,
0,
-1,
-1,
LDAP_DEREF_NEVER,
[['oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => ['size' => $limit, 'cookie' => $cookie]]]
);
ldap_parse_result($ldapcnn, $searchResult, $errcode, $matcheddn, $errmsg, $referrals, $controls);
$this->stdLog($ldapcnn, "ldap_list", ["filter" => $filter, "attributes" => $this->arrayAttributesForUser]);
if ($error = ldap_errno($ldapcnn)) {
$flagError = true;
} else {
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > ldap_list > OK");
switch ($option) {
case "GET":
list($totalUser, $countUser, $arrayUser) = $this->ldapGetUsersFromDepartmentSearchResult($ldapcnn, $searchResult, $option, $dn, $uidUserIdentifier, $totalUser, $countUser, $arrayUser);
break;
case "SYNCHRONIZE":
list($totalUser, $countUser, $arrayData) = $this->ldapGetUsersFromDepartmentSearchResult($ldapcnn, $searchResult, $option, $dn, $uidUserIdentifier, $totalUser, $countUser, $arrayData);
break;
}
}
if (!$flagError) {
if (isset($controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'])) {
// You need to pass the cookie from the last call to the next one
$cookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'];
} else {
$cookie = '';
}
}
// Empty cookie means last page
} while (!empty($cookie) && !$flagError);
// Get Users //2
if ($flagError) {
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > Search by characters > START");
foreach ($this->characters() as $value) {
$char = $value;
$ldapcnn = $this->ldapConnection($arrayAuthenticationSourceData);
$filter = ($filterUsers != "") ? $filterUsers : "(" . $this->arrayObjectClassFilter["user"] . ")";
$filter = "(&$filter($uidUserIdentifier=$char*))";
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > \$filter ----> $filter");
$searchResult = @ldap_list($ldapcnn, $dn, $filter, $this->arrayAttributesForUser);
$this->stdLog($ldapcnn, "ldap_list", ["attributes" => $this->arrayAttributesForUser]);
if ($error = ldap_errno($ldapcnn)) {
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > ldap_list > ERROR > \$error ---->\n" . print_r($error, true));
} else {
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > ldap_list > OK");
switch ($option) {
case "GET":
list($totalUser, $countUser, $arrayUser) = $this->ldapGetUsersFromDepartmentSearchResult($ldapcnn, $searchResult, $option, $dn, $uidUserIdentifier, $totalUser, $countUser, $arrayUser);
break;
case "SYNCHRONIZE":
list($totalUser, $countUser, $arrayData) = $this->ldapGetUsersFromDepartmentSearchResult($ldapcnn, $searchResult, $option, $dn, $uidUserIdentifier, $totalUser, $countUser, $arrayData);
break;
}
}
}
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > Search by characters > END");
}
$this->log($ldapcnn, "Found $totalUser users in department $dn");
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > END");
// Return
switch ($option) {
case "GET":
return $arrayUser;
break;
case "SYNCHRONIZE":
return $arrayData;
break;
}
} catch (Exception $e) {
throw $e;
}
}
public function characters()
{
try {
$arrayCharacter = [];
for ($i = 33; $i <= 127; $i++) {
$char = trim(strtolower(chr($i)));
if ($char != "") {
$arrayCharacter[$i] = $char;
}
}
unset($arrayCharacter[33]); // !
unset($arrayCharacter[38]); // &
unset($arrayCharacter[40]); // (
unset($arrayCharacter[41]); // )
unset($arrayCharacter[42]); // *
unset($arrayCharacter[60]); // <
unset($arrayCharacter[61]); // =
unset($arrayCharacter[62]); // >
unset($arrayCharacter[124]); // |
unset($arrayCharacter[126]); // ~
unset($arrayCharacter[127]); // DEL
// Return
return array_unique($arrayCharacter);
} catch (Exception $e) {
throw $e;
}
}
public function ldapGetUsersFromDepartmentSearchResult($ldapcnn, $searchResult, $option, $dn, $uidUserIdentifier, $totalUser, $countUser, array $arrayData)
{
try {
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartmentSearchResult() > START");
if ($searchResult) {
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartmentSearchResult() > ldap_list > OK");
$numEntries = ldap_count_entries($ldapcnn, $searchResult);
$this->stdLog($ldapcnn, "ldap_count_entries");
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartmentSearchResult() > ldap_list > OK > \$numEntries ----> $numEntries");
$totalUser += $numEntries;
if ($numEntries > 0) {
$this->log($ldapcnn, "Search $dn accounts with identifier = $uidUserIdentifier");
$entry = ldap_first_entry($ldapcnn, $searchResult);
$this->stdLog($ldapcnn, "ldap_first_entry");
do {
$arrayUserLdap = $this->ldapGetAttributes($ldapcnn, $entry);
$username = (isset($arrayUserLdap[$uidUserIdentifier])) ? $arrayUserLdap[$uidUserIdentifier] : "";
$countUser++;
if ((is_array($username) && !empty($username)) || trim($username) != "") {
$arrayUserData = $this->getUserDataFromAttribute($username, $arrayUserLdap);
if (!isset($this->arrayDepartmentUserSynchronizedChecked[$arrayUserData["sUsername"]])) {
$this->arrayDepartmentUserSynchronizedChecked[$arrayUserData["sUsername"]] = 1;
switch ($option) {
case "GET":
$arrayData[] = $arrayUserData;
break;
case "SYNCHRONIZE":
$arrayData = $this->departmentSynchronizeUser("", $arrayUserData, $arrayData);
break;
}
} else {
$this->log($ldapcnn, "User have repeated: Username \"" . $arrayUserData["sUsername"] . "\", DN \"" . $arrayUserData["sDN"] . "\"");
}
}
if ($option == "SYNCHRONIZE") {
// Progress bar
//$this->frontEndShow("BAR", "Departments: " . $arrayData["i"] . "/" . $arrayData["n"] . " " . $this->progressBar($totalUser, $countUser));
}
} while ($entry = ldap_next_entry($ldapcnn, $entry));
}
}
$this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartmentSearchResult() > END");
// Return
return array($totalUser, $countUser, $arrayData);
} catch (Exception $e) {
throw $e;
}
}
public function departmentSynchronizeUser($departmentUid, array $arrayUserLdap, array $arrayData)
{
try {
$this->debugLog("class.ldapAdvanced.php > function departmentSynchronizeUser() > START");
$this->debugLog("class.ldapAdvanced.php > function departmentSynchronizeUser() > \$arrayUserLdap[sUsername] ----> " . $arrayUserLdap["sUsername"]);
$userUid = "";
$found = false;
$arrayUserData = $this->departmentGetUserDataIfUsernameExists($arrayUserLdap["sUsername"]);
if (!empty($arrayUserData)) {
//User already exists in this department and there is nothing to do
//User already exists
$userUid = $arrayUserData["USR_UID"];
$found = true;
$arrayData["already"]++;
$arrayData["alreadyUsers"] .= $arrayUserData["USR_USERNAME"] . " ";
}
if (!$found) {
//If user DO NOT exists in this department.. do:
//If exists with another AuthSource -> impossible
//If exists in another department, but in PM and for this authsource, we need to move it
//$arrayNewUserData = $this->searchUserByUid($arrayUserLdap["sUsername"]);
$arrayNewUserData = $arrayUserLdap;
$arrayAux = $this->custom_ldap_explode_dn($arrayNewUserData["sDN"]);
array_shift($arrayAux);
$departmentUid = $this->getDepUidIfExistsDN(implode(",", $arrayAux)); //Check if exists the Department DN in DB
$this->debugLog("class.ldapAdvanced.php > function departmentSynchronizeUser() > \$departmentUid ----> $departmentUid");
if ($departmentUid != "") {
$arrayUserData = $this->authenticationSourceGetUserDataIfUsernameExists($arrayNewUserData["sUsername"]);
if (!empty($arrayUserData)) {
//User exists in this Authentication Source
//Move User
$userUid = $arrayUserData["USR_UID"];
$this->activateUser($arrayUserData["USR_UID"], $arrayNewUserData["sDN"], $departmentUid);
$arrayData["moved"]++;
$arrayData["movedUsers"] .= $arrayUserData["USR_USERNAME"] . " ";
$this->setArrayAuthenticationSourceUser($userUid, $arrayNewUserData); //INITIALIZE DATA //Update User
} else {
$arrayUserData = $this->getUserFromPM($arrayNewUserData["sUsername"]);
if (!empty($arrayUserData)) {
//User exists in another Authentication Source and another Department
//Impossible
$userUid = $arrayUserData["USR_UID"];
$arrayData["impossible"]++;
$arrayData["impossibleUsers"] .= $arrayUserData["USR_USERNAME"] . " ";
} else {
//User not exists
//Create User
$userUid = $this->createUserAndActivate($arrayNewUserData, $departmentUid);
$arrayData["created"]++;
$arrayData["createdUsers"] .= $arrayNewUserData["sUsername"] . " ";
$this->setArrayAuthenticationSourceUser($userUid, $arrayNewUserData); //INITIALIZE DATA //Add User
}
}
}
}
if ($userUid != "") {
$arrayData["arrayUserUid"][] = $userUid;
if (isset($arrayUserLdap["sManagerDN"]) && $arrayUserLdap["sManagerDN"] != "") {
if (!isset($arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]])) {
$arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]] = [];
}
$arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]][$userUid] = $userUid;
}
}
$this->debugLog("class.ldapAdvanced.php > function departmentSynchronizeUser() > \$userUid ----> $userUid");
$this->debugLog("class.ldapAdvanced.php > function departmentSynchronizeUser() > END");
return $arrayData;
} catch (Exception $e) {
throw $e;
}
}
public function debugLog($text)
{
try {
if ($this->debug) {
$this->log(null, "DEBUG: $text");
}
} catch (Exception $e) {
throw $e;
}
}
private function convertDateADtoPM($dateAD)
{
$unixTimestamp = ($dateAD / 10000000) - 11644560000;
$datePM = date('Y-m-d', mktime(0, 0, 0, date('m'), '01', date('Y') + 2));
if ($unixTimestamp > 0) {
$dateAux = date("Y-m-d", $unixTimestamp);
$yearAux = date("Y", $unixTimestamp);
if (strlen(trim($yearAux)) <= 4) {
$datePM = $dateAux;
}
}
return $datePM;
}
} }

View File

@@ -280,6 +280,10 @@
required required
}; };
} }
if (this.flagEdit === true) {
fields.form.password = {
};
}
return fields; return fields;
}, },
data() { data() {
@@ -376,6 +380,7 @@
}, },
load(obj) { load(obj) {
this.form = obj; this.form = obj;
this.flagEdit = true
}, },
test(form) { test(form) {
let formDataForName = new FormData(); let formDataForName = new FormData();

View File

@@ -15,6 +15,42 @@ class RbacUsers extends Model
protected $table = 'RBAC_USERS'; protected $table = 'RBAC_USERS';
public $timestamps = false; public $timestamps = false;
public function show($filters = array())
{
try {
$query = static::query();
if (is_array($filters['fields'])) {
$query->select($filters['fields']);
}
if (is_array($filters['conditions'])) {
$query->where($filters['conditions']);
}
$total = $query->count();
if (is_array($filters['start']) || is_array($filters['limit'])) {
$start = $filters['start'] ?? 0;
$limit = $filters['limit'] ?? 25;
$query->offset($start)->limit($limit);
}
if (is_array($filters['orderBy'])) {
$query->orderBy($filters['orderBy'][0], $filters['orderBy'][1] ?? 'asc');
}
$data =$query->get()->toArray();
$result = [
'total' => $total,
'data' => $data
];
return $result;
} catch (Exception $exception) {
return $exception->getMessage();
}
}
/** /**
* Create a new user * Create a new user
* *
@@ -49,6 +85,17 @@ class RbacUsers extends Model
return $data; return $data;
} }
public static function updateData($userData, $conditions = [])
{
try {
$responseSave = self::where($conditions)
->update($userData);
return $responseSave;
} catch (Exception $exception) {
return $exception->getMessage();
}
}
/** /**
* Verify if username exists * Verify if username exists
* *

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.26dc108e.css" rel="preload" as="style"><link href="/lib/authenticationSources/js/app.09d204f4.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.09d204f4.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.88f17c35.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.88f17c35.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