// Need to know how many times to fail login to lock account
AdminOrgApi adminOrgApi = adminContext.getApi().getOrgApi();
OrgPasswordPolicySettings settingsToRevertTo = null;
// session api isn't typically exposed to the user, as it is implicit
SessionApi sessionApi = context.utils().injector().getInstance(SessionApi.class);
OrgPasswordPolicySettings settings = adminOrgApi.getSettings(org.getId()).getPasswordPolicy();
assertNotNull(settings);
// Adjust account settings so we can lock the account - be careful to not set invalidLoginsBeforeLockout too low!
if (!settings.isAccountLockoutEnabled()) {
settingsToRevertTo = settings;
settings = settings.toBuilder().accountLockoutEnabled(true).invalidLoginsBeforeLockout(5).build();
settings = adminOrgApi.editPasswordPolicy(org.getId(), settings);
}
assertTrue(settings.isAccountLockoutEnabled());
for (int i = 0; i < settings.getInvalidLoginsBeforeLockout() + 1; i++) {
try {
sessionApi.loginUserInOrgWithPassword(URI.create(endpoint + "/sessions"), user.getName(), org.getName(), "wrongpassword!");
fail("Managed to login using the wrong password!");
} catch (AuthorizationException e) {
} catch (Exception e) {
fail("Expected AuthorizationException", e);
}
}
user = userApi.get(user.getHref());
assertTrue(user.isLocked());
try {
sessionApi.loginUserInOrgWithPassword(URI.create(endpoint + "/sessions"), user.getName(), org.getName(), "newPassword");
fail("Managed to login to locked account!");
} catch (AuthorizationException e) {
} catch (Exception e) {
fail("Expected AuthorizationException", e);
}
userApi.unlock(user.getHref());
user = userApi.get(user.getHref());
assertFalse(user.isLocked());
// Double-check the user can now login again
SessionWithToken sessionWithToken = sessionApi.loginUserInOrgWithPassword(URI.create(endpoint + "/sessions"), user.getName(), org.getName(), "newPassword");
assertNotNull(sessionWithToken.getToken());
sessionApi.logoutSessionWithToken(sessionWithToken.getSession().getHref(), sessionWithToken.getToken());
// Return account settings to the previous values, if necessary
if (settingsToRevertTo != null) {
adminOrgApi.editPasswordPolicy(org.getId(), settingsToRevertTo);
}