Skip to content
GitLab
    • Explore Projects Groups Topics Snippets
Projects Groups Topics Snippets
  • /
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
    • Contribute to GitLab
  • Sign in
  • fusiondirectory-orchestrator fusiondirectory-orchestrator
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributor statistics
    • Graph
    • Compare revisions
  • Issues 25
    • Issues 25
    • List
    • Boards
    • Service Desk
    • Milestones
  • Merge requests 6
    • Merge requests 6
  • CI/CD
    • CI/CD
    • Pipelines
    • Jobs
    • Schedules
  • Analytics
    • Analytics
    • Value stream
    • CI/CD
    • Repository
  • Wiki
    • Wiki
  • Activity
  • Graph
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
Collapse sidebar
  • fusiondirectoryfusiondirectory
  • fusiondirectory-orchestratorfusiondirectory-orchestrator
  • Merge requests
  • !76

Draft: Resolve "Redesign notifications class"

  • Review changes

  • Download
  • Patches
  • Plain diff
Open Alexa Oana eliza requested to merge 80-redesign-notifications-class into dev 1 month ago
  • Overview 0
  • Commits 36
  • Pipelines 9
  • Changes 6

Related to #80

Compare
  • version 7
    34fe87ec
    1 month ago

  • version 6
    a14653b2
    1 month ago

  • version 5
    529216f0
    1 month ago

  • version 4
    fa1bf39f
    1 month ago

  • version 3
    205066a6
    1 month ago

  • version 2
    26a576d7
    1 month ago

  • version 1
    2295cf1c
    1 month ago

  • dev (base)

and
  • latest version
    1a411f0a
    36 commits, 1 month ago

  • version 7
    34fe87ec
    27 commits, 1 month ago

  • version 6
    a14653b2
    19 commits, 1 month ago

  • version 5
    529216f0
    18 commits, 1 month ago

  • version 4
    fa1bf39f
    17 commits, 1 month ago

  • version 3
    205066a6
    9 commits, 1 month ago

  • version 2
    26a576d7
    2 commits, 1 month ago

  • version 1
    2295cf1c
    1 commit, 1 month ago

6 files
+ 356
− 330

    Preferences

    File browser
    Compare changes
library/MailUtils.php 0 → 100644
+ 34
− 0
  • View file @ fa1bf39f

  • Edit in single-file editor

  • Open in Web IDE

<?php
class MailUtils
{
private function __construct ()
{
}
public static function sendMail ($setFrom, $setBCC, $recipients, $body, $signature, $subject, $receipt, $attachments)
{
$mail_controller = new \FusionDirectory\Mail\MailLib($setFrom,
$setBCC,
$recipients,
$body,
$signature,
$subject,
$receipt,
$attachments);
return $mail_controller->sendMail();
}
/**
* @return array
* Note : A simple retrieval methods of the mail backend configuration set in FusionDirectory
*/
public static function getMailObjectConfiguration (TaskGateway $gateway): array
{
return $gateway->getLdapTasks(
"(objectClass=fdTasksConf)",
["fdTasksConfLastExecTime", "fdTasksConfIntervalEmails", "fdTasksConfMaxEmails"]
);
}
}
\ No newline at end of file
library/TokenUtils.php 0 → 100644
+ 198
− 0
  • View file @ fa1bf39f

  • Edit in single-file editor

  • Open in Web IDE

<?php
class TokenUtils
{
private function __construct ()
{
}
/**
* @param string $userDN
* @param int $timeStamp
* @return string
* @throws Exception
*/
public static function generateToken (string $userDN, int $timeStamp, TaskGateway $gateway): string
{
$token = NULL;
// Salt has been generated with APG.
$salt = '8onOlEsItKond';
$payload = json_encode($userDN . $salt);
// This allows the token to be different every time.
$time = time();
// Create hmac with sha256 alg and the key provided for JWT token signature in ENV.
$token_hmac = hash_hmac("sha256", $time . $payload, $_ENV["SECRET_KEY"], TRUE);
// We need to have a token allowed to be used within an URL.
$token = Utils::base64urlEncode($token_hmac);
// Save token within LDAP
self::saveTokenInLdap($userDN, $token, $timeStamp, $gateway);
return $token;
}
/**
* @param string $userDN
* @param string $token
* NOTE : UID is the full DN of the user. (uid=...).
* @param int $days
* @return bool
* @throws Exception
*/
public static function saveTokenInLdap (string $userDN, string $token, int $days, TaskGateway $gateway): bool
{
$result = FALSE;
$currentTimestamp = time();
// Calculate the future timestamp by adding days to the current timestamp (We actually adds number of seconds).
$futureTimestamp = $currentTimestamp + ($days * 24 * 60 * 60);
preg_match('/uid=([^,]+),ou=/', $userDN, $matches);
$uid = $matches[1];
$dn = 'cn=' . $uid . ',' . 'ou=tokens' . ',' . $_ENV["LDAP_BASE"];
$ldap_entry["objectClass"] = ['top', 'fdTokenEntry'];
$ldap_entry["fdTokenUserDN"] = $userDN;
$ldap_entry["fdTokenType"] = 'reminder';
$ldap_entry["fdToken"] = $token;
$ldap_entry["fdTokenTimestamp"] = $futureTimestamp;
$ldap_entry["cn"] = $uid;
// set the dn for the token, only take what's between "uid=" and ",ou="
// Verify if token ou branch exists
if (!self::tokenBranchExist('ou=tokens' . ',' . $_ENV["LDAP_BASE"], $gateway)) {
// Create the branch
self::createBranchToken($gateway);
}
// The user token DN creation
$userTokenDN = 'cn=' . $uid . ',ou=tokens' . ',' . $_ENV["LDAP_BASE"];
// Verify if a token already exists for specified user and remove it to create new one correctly.
if (self::tokenBranchExist($userTokenDN, $gateway)) {
// Remove the user token
self::removeUserToken($userTokenDN, $gateway);
}
// Add token to LDAP for specific UID
try {
$result = ldap_add($gateway->ds, $dn, $ldap_entry); // bool returned
} catch (Exception $e) {
echo json_encode(["Ldap Error - Token could not be saved!" => "$e"]); // string returned
exit;
}
return $result;
}
/**
* @param int $subTaskCall
* @param int $firstCall
* @param int $secondCall
* @return int
* Note : Simply return the difference between first and second call. (First call can be null).
*/
public static function getTokenExpiration (int $subTaskCall, int $firstCall, int $secondCall): int
{
// if firstCall is empty, secondCall is the timestamp expiry for the token.
$result = $secondCall;
if (!empty($firstCall)) {
// Verification if the subTask is the second reminder or the first reminder.
if ($subTaskCall === $firstCall) {
$result = $firstCall - $secondCall;
}
}
return $result;
}
/**
* @param $userTokenDN
* @return void
* Note : Simply remove the token for specific user DN
*/
public static function removeUserToken ($userTokenDN, TaskGateway $gateway): void
{
// Add token to LDAP for specific UID
try {
$result = ldap_delete($gateway->ds, $userTokenDN); // bool returned
} catch (Exception $e) {
echo json_encode(["Ldap Error - User token could not be removed!" => "$e"]); // string returned
exit;
}
}
/**
* Create ou=pluginManager LDAP branch
* @throws Exception
*/
public static function createBranchToken (TaskGateway $gateway): void
{
try {
ldap_add(
$gateway->ds, 'ou=tokens' . ',' . $_ENV["LDAP_BASE"],
[
'ou' => 'tokens',
'objectClass' => 'organizationalUnit',
]
);
} catch (Exception $e) {
echo json_encode(["Ldap Error - Impossible to create the token branch" => "$e"]); // string returned
exit;
}
}
/**
* @param string $token
* @param array $mailTemplateForm
* @param string $taskDN
* @return array
*/
public static function generateTokenUrl (string $token, array $mailTemplateForm, string $taskDN): array
{
//Only take the cn of the main task name :
preg_match('/cn=([^,]+),ou=/', $taskDN, $matches);
$taskName = $matches[1];
// Remove the API URI
$cleanedUrl = preg_replace('#/rest\.php/v1$#', '', $_ENV['FUSION_DIRECTORY_API_URL']);
$url = $cleanedUrl . '/accountProlongation.php?token=' . $token . '&task=' . $taskName;
$mailTemplateForm['body'] .= $url;
return $mailTemplateForm;
}
/**
* @param string $dn
* @return bool
* Note : Simply inspect if the branch for token is existing.
*/
public static function tokenBranchExist (string $dn, TaskGateway $gateway): bool
{
$result = FALSE;
try {
$search = ldap_search($gateway->ds, $dn, "(objectClass=*)");
// Check if the search was successful
if ($search) {
// Get the number of entries found
$entries = ldap_get_entries($gateway->ds, $search);
// If entries are found, set result to true
if ($entries["count"] > 0) {
$result = TRUE;
}
}
} catch (Exception $e) {
$result = FALSE;
}
return $result;
}
}
\ No newline at end of file
library/Utils.php 0 → 100644
+ 85
− 0
  • View file @ fa1bf39f

  • Edit in single-file editor

  • Open in Web IDE

<?php
class Utils
{
private function __construct ()
{
}
/**
* @param array $array
* @return array
* Note : Recursively filters out empty values and arrays at any depth.
*/
public static function recursiveArrayFilter (array $array): array
{
// First filter the array for non-empty elements
$filtered = array_filter($array, function ($item) {
if (is_array($item)) {
// Recursively filter the sub-array
$item = self::recursiveArrayFilter($item);
// Only retain non-empty arrays
return !empty($item);
} else {
// Retain non-empty scalar values
return !empty($item);
}
});
return $filtered;
}
/**
* Find matching keys between 2 lists.
*
* @param array|null $elements
* @param array $keys
* @return array
*/
public static function findMatchingKeys (?array $elements, array $keys): array
{
$matching = [];
if (!empty($elements)) {
foreach ($elements as $element) {
foreach ($keys as $key) {
if (!empty($element) && array_key_exists($key, $element)) {
$matching[] = $key;
}
}
}
}
return $matching;
}
/**
* @param $array
* @return array
* Note : simply return all values of a multi-dimensional array.
*/
public static function getArrayValuesRecursive ($array)
{
$values = [];
foreach ($array as $value) {
if (is_array($value)) {
// If value is an array, merge its values recursively
$values = array_merge($values, self::getArrayValuesRecursive($value));
} else {
// If value is not an array, add it to the result
$values[] = $value;
}
}
return $values;
}
/**
* @param string $text
* @return string
* Note : This come from jwtToken, as it is completely private - it is cloned here for now.
*/
public static function base64urlEncode (string $text): string
{
return str_replace(["+", "/", "="], ["A", "B", ""], base64_encode($text));
}
}
\ No newline at end of file
plugins/tasks/Audit.php
+ 1
− 24
  • View file @ fa1bf39f

  • Edit in single-file editor

  • Open in Web IDE


Conflict: This file was modified in both the source and target branches. Ask someone with write access to resolve it.
@@ -47,7 +47,7 @@ class Audit implements EndpointInterface
$result = $this->processAuditDeletion($this->gateway->getObjectTypeTask('Audit'));
// Recursive function to filter out empty arrays at any depth
$nonEmptyResults = $this->recursiveArrayFilter($result);
$nonEmptyResults = Utils::recursiveArrayFilter($result);
if (!empty($nonEmptyResults)) {
return $nonEmptyResults;
@@ -119,27 +119,4 @@ class Audit implements EndpointInterface
return $audit;
}
/**
* @param array $array
* @return array
* Note : Recursively filters out empty values and arrays at any depth.
*/
private function recursiveArrayFilter (array $array): array
{
// First filter the array for non-empty elements
$filtered = array_filter($array, function ($item) {
if (is_array($item)) {
// Recursively filter the sub-array
$item = $this->recursiveArrayFilter($item);
// Only retain non-empty arrays
return !empty($item);
} else {
// Retain non-empty scalar values
return !empty($item);
}
});
return $filtered;
}
}
\ No newline at end of file
plugins/tasks/Notifications.php
+ 32
− 79
  • View file @ fa1bf39f

  • Edit in single-file editor

  • Open in Web IDE


Conflict: This file was modified in both the source and target branches. Ask someone with write access to resolve it.
@@ -4,6 +4,7 @@ class Notifications implements EndpointInterface
{
private TaskGateway $gateway;
private string $errorMessage = 'No matching audited attributes with monitored attributes, safely removed!';
public function __construct (TaskGateway $gateway)
{
@@ -61,7 +62,6 @@ class Notifications implements EndpointInterface
foreach ($notificationsSubTasks as $task) {
// If the tasks must be treated - status and scheduled - process the sub-tasks
if ($this->gateway->statusAndScheduleCheck($task)) {
// Retrieve data from the main task
$notificationsMainTask = $this->getNotificationsMainTask($task['fdtasksgranularmaster'][0]);
$notificationsMainTaskName = $task['fdtasksgranularmaster'][0];
@@ -69,26 +69,7 @@ class Notifications implements EndpointInterface
// Generate the mail form with all mail controller requirements
$mailTemplateForm = $this->generateMainTaskMailTemplate($notificationsMainTask);
// Simply retrieve the list of audited attributes
$auditAttributes = $this->decodeAuditAttributes($task);
// Recovering monitored attributes list from the defined notification task.
$monitoredAttrs = $notificationsMainTask[0]['fdtasksnotificationsattributes'];
// Reformat supann
$monitoredSupannResource = $this->getSupannResourceState($notificationsMainTask[0]);
// Simply remove keys with 'count' reported by ldap.
$this->gateway->unsetCountKeys($monitoredAttrs);
$this->gateway->unsetCountKeys($monitoredSupannResource);
// Find matching attributes between audited and monitored attributes
$matchingAttrs = $this->findMatchingAttributes($auditAttributes, $monitoredAttrs);
// Verify Supann resource state if applicable
if ($this->shouldVerifySupannResource($monitoredSupannResource, $auditAttributes)) {
// Adds it to the mating attrs for further notification process.
$matchingAttrs[] = 'supannRessourceEtat';
}
$matchingAttrs = $this->getMatchingAttrs($notificationsMainTask, $task);
if (!empty($matchingAttrs)) {
// Fill an array with UID of audited user and related matching attributes
@@ -103,7 +84,7 @@ class Notifications implements EndpointInterface
} else { // Simply remove the subTask has no notifications are required
$result[$task['dn']]['Removed'] = $this->gateway->removeSubTask($task['dn']);
$result[$task['dn']]['Status'] = 'No matching audited attributes with monitored attributes, safely removed!';
$result[$task['dn']]['Status'] = $this->errorMessage;
}
}
}
@@ -115,6 +96,32 @@ class Notifications implements EndpointInterface
return $result;
}
private function getMatchingAttrs (array $notificationsMainTask, array $task): array
{
// Simply retrieve the list of audited attributes
$auditAttributes = $this->decodeAuditAttributes($task);
// Recovering monitored attributes list from the defined notification task.
$monitoredAttrs = $notificationsMainTask[0]['fdtasksnotificationsattributes'];
// Reformat supann
$monitoredSupannResource = $this->getSupannResourceState($notificationsMainTask[0]);
// Simply remove keys with 'count' reported by ldap.
$this->gateway->unsetCountKeys($monitoredAttrs);
$this->gateway->unsetCountKeys($monitoredSupannResource);
// Find matching attributes between audited and monitored attributes
$matchingAttrs = $this->findMatchingAttributes($auditAttributes, $monitoredAttrs);
// Verify Supann resource state if applicable
if ($this->shouldVerifySupannResource($monitoredSupannResource, $auditAttributes)) {
// Adds it to the mating attrs for further notification process.
$matchingAttrs[] = 'supannRessourceEtat';
}
return $matchingAttrs;
}
/**
* Determine if Supann resource verification is needed.
*
@@ -165,30 +172,6 @@ class Notifications implements EndpointInterface
return $auditAttributes;
}
/**
* Find matching attributes between audit and monitored attributes.
*
* @param array|null $auditAttributes
* @param array $monitoredAttrs
* @return array
*/
private function findMatchingAttributes (?array $auditAttributes, array $monitoredAttrs): array
{
$matchingAttrs = [];
if (!empty($auditAttributes)) {
foreach ($auditAttributes as $attributeName) {
foreach ($monitoredAttrs as $monitoredAttr) {
if (!empty($attributeName) && array_key_exists($monitoredAttr, $attributeName)) {
$matchingAttrs[] = $monitoredAttr;
}
}
}
}
return $matchingAttrs;
}
/**
* @param array $supannResource
* @param array $auditedAttrs
@@ -197,45 +180,15 @@ class Notifications implements EndpointInterface
*/
private function verifySupannState (array $supannResource, array $auditedAttrs): bool
{
$result = FALSE;
//Construct Supann Resource State as string
$monitoredSupannState = '{' . $supannResource['resource'][0] . '}' . $supannResource['state'][0];
if (!empty($supannResource['subState'][0])) {
$monitoredSupannState = '{' . $supannResource['resource'][0] . '}' . $supannResource['state'][0] . ':' . $supannResource['subState'][0];
} else {
$monitoredSupannState = '{' . $supannResource['resource'][0] . '}' . $supannResource['state'][0];
$monitoredSupannState = $monitoredSupannState . ':' . $supannResource['subState'][0];
}
// Get all the values only of a multidimensional array.
$auditedValues = $this->getArrayValuesRecursive($auditedAttrs);
if (in_array($monitoredSupannState, $auditedValues)) {
$result = TRUE;
} else {
$result = FALSE;
}
return $result;
}
/**
* @param $array
* @return array
* Note : simply return all values of a multi-dimensional array.
*/
public function getArrayValuesRecursive ($array)
{
$values = [];
foreach ($array as $value) {
if (is_array($value)) {
// If value is an array, merge its values recursively
$values = array_merge($values, $this->getArrayValuesRecursive($value));
} else {
// If value is not an array, add it to the result
$values[] = $value;
}
}
return $values;
return in_array($monitoredSupannState, $auditedValues);
}
/**
Assignee
Alexa Oana eliza's avatar
Alexa Oana eliza
Assign to
0 Reviewers
None
Request review from
Labels
1
PJ1802-0188
1
PJ1802-0188
    Assign labels
  • Manage project labels

Milestone
No milestone
None
None
Time tracking
No estimate or time spent
Lock merge request
Unlocked
1
1 Participant
Alexa Oana eliza
Reference: fusiondirectory/fusiondirectory-orchestrator!76
Source branch: 80-redesign-notifications-class

Menu

Explore Projects Groups Topics Snippets