Skip to content

Commit

Permalink
Refactor to use Optional
Browse files Browse the repository at this point in the history
  • Loading branch information
PasinduYeshan committed Nov 29, 2024
1 parent a61a5d7 commit 76bdf04
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -179,11 +180,8 @@ public static boolean isPasswordExpired(String tenantDomain, String tenantAwareU
skipIfNoApplicableRules);
}

// If the default behavior is to skip the password expiry, rules with skip logic are not necessary.
List<PasswordExpiryRule> filteredRules = passwordExpiryRules.stream()
.filter(rule -> !skipIfNoApplicableRules ||
!PasswordExpiryRuleOperatorEnum.NE.equals(rule.getOperator()))
.collect(Collectors.toList());
List<PasswordExpiryRule> filteredRules =
filterApplicableExpiryRules(passwordExpiryRules, skipIfNoApplicableRules);

Map<PasswordExpiryRuleAttributeEnum, Set<String>> fetchedUserAttributes =
new EnumMap<>(PasswordExpiryRuleAttributeEnum.class);
Expand Down Expand Up @@ -305,16 +303,16 @@ private static boolean isPasswordExpiredUnderDefaultPolicy(String tenantDomain,
* @param tenantAwareUsername The tenant aware username.
* @param groupIds The group IDs of the user.
* @param roleIds The role IDs of the user.
* @return The password expiry time in milliseconds.
* @return Optional containing the password expiry time in milliseconds, or empty if not applicable.
* @throws PostAuthenticationFailedException If an error occurred while getting the password expiry time.
*/
public static Long getUserPasswordExpiryTime(String tenantDomain, String tenantAwareUsername,
List<String> groupIds, List<String> roleIds)
public static Optional<Long> getUserPasswordExpiryTime(String tenantDomain, String tenantAwareUsername,
List<String> groupIds, List<String> roleIds)
throws PostAuthenticationFailedException {

try {
// If the password expiry is not enabled, password expiry time is not applicable.
if (!isPasswordExpiryEnabled(tenantDomain)) return null;
if (!isPasswordExpiryEnabled(tenantDomain)) return Optional.empty();

UserRealm userRealm = getUserRealm(tenantDomain);
UserStoreManager userStoreManager = getUserStoreManager(userRealm);
Expand All @@ -324,7 +322,7 @@ public static Long getUserPasswordExpiryTime(String tenantDomain, String tenantA

// If last password update time is not available, it will be considered as expired.
if (StringUtils.isBlank(lastPasswordUpdatedTime)) {
return System.currentTimeMillis();
return Optional.of(System.currentTimeMillis());
}

long lastPasswordUpdatedTimeInMillis = getLastPasswordUpdatedTimeInMillis(lastPasswordUpdatedTime);
Expand All @@ -335,15 +333,13 @@ public static Long getUserPasswordExpiryTime(String tenantDomain, String tenantA

// If no rules are defined, use the default expiry time if "skipIfNoApplicableRules" is disabled.
if (CollectionUtils.isEmpty(passwordExpiryRules)) {
if (skipIfNoApplicableRules) return null;
return lastPasswordUpdatedTimeInMillis + getDaysTimeInMillis(defaultPasswordExpiryInDays);
if (skipIfNoApplicableRules) return Optional.empty();
return Optional.of(
lastPasswordUpdatedTimeInMillis + getDaysTimeInMillis(defaultPasswordExpiryInDays));
}

// If the default behavior is to skip the password expiry, rules with skip logic are not necessary.
List<PasswordExpiryRule> filteredRules = passwordExpiryRules.stream()
.filter(rule -> !skipIfNoApplicableRules ||
!PasswordExpiryRuleOperatorEnum.NE.equals(rule.getOperator()))
.collect(Collectors.toList());
List<PasswordExpiryRule> filteredRules =
filterApplicableExpiryRules(passwordExpiryRules, skipIfNoApplicableRules);

Map<PasswordExpiryRuleAttributeEnum, Set<String>> userAttributes =
new EnumMap<>(PasswordExpiryRuleAttributeEnum.class);
Expand All @@ -358,23 +354,33 @@ public static Long getUserPasswordExpiryTime(String tenantDomain, String tenantA
if (isRuleApplicable(rule, userAttributes, tenantDomain, userId, userStoreManager)) {
// Skip the rule if the operator is not equals.
if (PasswordExpiryRuleOperatorEnum.NE.equals(rule.getOperator())) {
return null;
return Optional.empty();
}
int expiryDays =
rule.getExpiryDays() > 0 ? rule.getExpiryDays() : getPasswordExpiryInDays(tenantDomain);
return lastPasswordUpdatedTimeInMillis + getDaysTimeInMillis(expiryDays);
return Optional.of(lastPasswordUpdatedTimeInMillis + getDaysTimeInMillis(expiryDays));
}
}

if (skipIfNoApplicableRules) return null;
return lastPasswordUpdatedTimeInMillis + getDaysTimeInMillis(defaultPasswordExpiryInDays);
if (skipIfNoApplicableRules) return Optional.empty();
return Optional.of(
lastPasswordUpdatedTimeInMillis + getDaysTimeInMillis(defaultPasswordExpiryInDays));
} catch (UserStoreException e) {
throw new PostAuthenticationFailedException(PasswordPolicyConstants.ErrorMessages.
ERROR_WHILE_GETTING_USER_STORE_DOMAIN.getCode(),
PasswordPolicyConstants.ErrorMessages.ERROR_WHILE_GETTING_USER_STORE_DOMAIN.getMessage());
}
}

private static List<PasswordExpiryRule> filterApplicableExpiryRules(List<PasswordExpiryRule> passwordExpiryRules,
boolean skipIfNoApplicableRules) {

// If the default behavior is to skip the password expiry, rules with skip logic are not required.
return passwordExpiryRules.stream().filter(
rule -> !skipIfNoApplicableRules || !PasswordExpiryRuleOperatorEnum.NE.equals(rule.getOperator()))
.collect(Collectors.toList());
}

/**
* This method returns the time in milliseconds for the given number of days.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Optional;
import java.util.stream.Collectors;

import static org.mockito.ArgumentMatchers.any;
Expand Down Expand Up @@ -394,20 +395,20 @@ public void testGetUserPasswordExpiryTime(Integer daysAgo, String[] roles, Strin
List<String> groupIds = Arrays.stream(groups).map(GROUP_MAP::get).collect(Collectors.toList());

long testStartTime = System.currentTimeMillis();
Long expiryTime =
Optional<Long> expiryTime =
PasswordPolicyUtils.getUserPasswordExpiryTime(tenantDomain, tenantAwareUsername, groupIds, roleIds);
long testEndTime = System.currentTimeMillis();

if (expiryDays == null) {
Assert.assertNull(expiryTime, description);
Assert.assertFalse(expiryTime.isPresent(), description);
} else if (expiryDays == 0) {
Assert.assertNotNull(expiryTime);
Assert.assertTrue(expiryTime >= testStartTime && expiryTime <= testEndTime);
Assert.assertTrue(expiryTime.get() >= testStartTime && expiryTime.get() <= testEndTime);
} else {
Assert.assertNotNull(expiryTime);
Assert.assertNotNull(updateTime);
long expectedExpiryTime = updateTime + getDaysTimeInMillis(expiryDays);
Assert.assertTrue(Math.abs(expiryTime - expectedExpiryTime) <= TIME_TOLERANCE_MS);
Assert.assertTrue(Math.abs(expiryTime.get() - expectedExpiryTime) <= TIME_TOLERANCE_MS);
}
}

Expand All @@ -417,10 +418,10 @@ public void testGetUserPasswordExpiryTime()

// Case 1: Password expiry disabled.
mockPasswordExpiryEnabled(identityGovernanceService, PasswordPolicyConstants.FALSE);
Long expiryTime =
Optional<Long> expiryTime =
PasswordPolicyUtils.getUserPasswordExpiryTime(
tenantDomain, tenantAwareUsername, null, null);
Assert.assertNull(expiryTime);
Assert.assertFalse(expiryTime.isPresent());

// Case 2: Password expiry enabled, but no rules.
mockPasswordExpiryEnabled(identityGovernanceService, PasswordPolicyConstants.TRUE);
Expand Down Expand Up @@ -452,7 +453,7 @@ public void testGetUserPasswordExpiryTime()
tenantDomain, tenantAwareUsername, null, null);

long expectedExpiryTime = updateTime + getDaysTimeInMillis(DEFAULT_EXPIRY_DAYS);
Assert.assertTrue(Math.abs(expiryTime - expectedExpiryTime) <= TIME_TOLERANCE_MS);
Assert.assertTrue(Math.abs(expiryTime.get() - expectedExpiryTime) <= TIME_TOLERANCE_MS);

// Case 3: Password expiry enabled, no applicable rules, skipIfNoApplicableRules enabled.
when(identityGovernanceService.getConfiguration(
Expand All @@ -461,7 +462,7 @@ public void testGetUserPasswordExpiryTime()

expiryTime = PasswordPolicyUtils.getUserPasswordExpiryTime(
tenantDomain, tenantAwareUsername, null, null);
Assert.assertNull(expiryTime);
Assert.assertFalse(expiryTime.isPresent());

// Case 4: UserStoreException.
when(abstractUserStoreManager.getUserIDFromUserName(tenantAwareUsername)).thenThrow(
Expand Down

0 comments on commit 76bdf04

Please sign in to comment.