use of org.wso2.carbon.identity.recovery.IdentityRecoveryException in project identity-governance by wso2-extensions.
the class PasswordRecoveryReCaptchaConnector method preValidate.
@Override
public CaptchaPreValidationResponse preValidate(ServletRequest servletRequest, ServletResponse servletResponse) throws CaptchaException {
CaptchaPreValidationResponse preValidationResponse = new CaptchaPreValidationResponse();
boolean forgotPasswordRecaptchaEnabled = checkReCaptchaEnabledForForgotPassoword(servletRequest, FORGOT_PASSWORD_RECAPTCHA_ENABLE);
String pathUrl = ((HttpServletRequest) servletRequest).getRequestURI();
if (forgotPasswordRecaptchaEnabled && (CaptchaUtil.isPathAvailable(pathUrl, ACCOUNT_SECURITY_QUESTION_URL) || CaptchaUtil.isPathAvailable(pathUrl, ACCOUNT_SECURITY_QUESTIONS_URL) || CaptchaUtil.isPathAvailable(pathUrl, RECOVER_PASSWORD_URL))) {
preValidationResponse.setCaptchaValidationRequired(true);
}
// Handle recover with Email option.
if (pathUrl.equals(RECOVER_PASSWORD_URL)) {
return preValidationResponse;
}
// Handle recover with security questions option.
HttpServletRequest httpServletRequestWrapper;
try {
httpServletRequestWrapper = new CaptchaHttpServletRequestWrapper((HttpServletRequest) servletRequest);
preValidationResponse.setWrappedHttpServletRequest(httpServletRequestWrapper);
} catch (IOException e) {
log.error("Error occurred while wrapping ServletRequest.", e);
return preValidationResponse;
}
String path = httpServletRequestWrapper.getRequestURI();
User user = new User();
boolean initializationFlow = false;
if (CaptchaUtil.isPathAvailable(path, ACCOUNT_SECURITY_QUESTION_URL) || CaptchaUtil.isPathAvailable(path, ACCOUNT_SECURITY_QUESTIONS_URL)) {
user.setUserName(servletRequest.getParameter("username"));
if (StringUtils.isNotBlank(servletRequest.getParameter("realm"))) {
user.setUserStoreDomain(servletRequest.getParameter("realm"));
} else {
user.setUserStoreDomain(IdentityUtil.getPrimaryDomainName());
}
user.setTenantDomain(servletRequest.getParameter("tenant-domain"));
initializationFlow = true;
} else {
JsonObject requestObject;
try {
try (InputStream in = httpServletRequestWrapper.getInputStream()) {
requestObject = new JsonParser().parse(IOUtils.toString(in)).getAsJsonObject();
}
} catch (IOException e) {
return preValidationResponse;
}
UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance();
try {
UserRecoveryData userRecoveryData = userRecoveryDataStore.load(requestObject.get("key").getAsString());
if (userRecoveryData != null) {
user = userRecoveryData.getUser();
}
} catch (IdentityRecoveryException e) {
return preValidationResponse;
}
}
if (StringUtils.isBlank(user.getUserName())) {
// Invalid Request
return preValidationResponse;
}
if (StringUtils.isBlank(user.getTenantDomain())) {
user.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
}
Property[] connectorConfigs;
try {
connectorConfigs = identityGovernanceService.getConfiguration(new String[] { RECOVERY_QUESTION_PASSWORD_RECAPTCHA_ENABLE, RECOVERY_QUESTION_PASSWORD_RECAPTCHA_MAX_FAILED_ATTEMPTS }, user.getTenantDomain());
} catch (IdentityGovernanceException e) {
throw new CaptchaServerException("Unable to retrieve connector configs.", e);
}
String connectorEnabled = null;
String maxAttemptsStr = null;
for (Property connectorConfig : connectorConfigs) {
if ((RECOVERY_QUESTION_PASSWORD_RECAPTCHA_ENABLE).equals(connectorConfig.getName())) {
connectorEnabled = connectorConfig.getValue();
} else if ((RECOVERY_QUESTION_PASSWORD_RECAPTCHA_MAX_FAILED_ATTEMPTS).equals(connectorConfig.getName())) {
maxAttemptsStr = connectorConfig.getValue();
}
}
if (!Boolean.parseBoolean(connectorEnabled)) {
return preValidationResponse;
}
if (StringUtils.isBlank(maxAttemptsStr) || !NumberUtils.isNumber(maxAttemptsStr)) {
log.warn("Invalid configuration found in the PasswordRecoveryReCaptchaConnector for the tenant - " + user.getTenantDomain());
return preValidationResponse;
}
int maxFailedAttempts = Integer.parseInt(maxAttemptsStr);
int tenantId;
try {
tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
} catch (Exception e) {
// Invalid tenant
return preValidationResponse;
}
try {
if (CaptchaDataHolder.getInstance().getAccountLockService().isAccountLocked(user.getUserName(), user.getTenantDomain(), user.getUserStoreDomain())) {
return preValidationResponse;
}
} catch (AccountLockServiceException e) {
if (log.isDebugEnabled()) {
log.debug("Error while validating if account is locked for user: " + user.getUserName() + " of user " + "store domain: " + user.getUserStoreDomain() + " and tenant domain: " + user.getTenantDomain());
}
return preValidationResponse;
}
Map<String, String> claimValues = CaptchaUtil.getClaimValues(user, tenantId, new String[] { FAIL_ATTEMPTS_CLAIM });
if (claimValues == null || claimValues.isEmpty()) {
// Invalid user
return preValidationResponse;
}
int currentFailedAttempts = 0;
if (NumberUtils.isNumber(claimValues.get(FAIL_ATTEMPTS_CLAIM))) {
currentFailedAttempts = Integer.parseInt(claimValues.get(FAIL_ATTEMPTS_CLAIM));
}
HttpServletResponse httpServletResponse = ((HttpServletResponse) servletResponse);
if (currentFailedAttempts > maxFailedAttempts) {
if (initializationFlow) {
httpServletResponse.setHeader("reCaptcha", "true");
httpServletResponse.setHeader("reCaptchaKey", CaptchaDataHolder.getInstance().getReCaptchaSiteKey());
httpServletResponse.setHeader("reCaptchaAPI", CaptchaDataHolder.getInstance().getReCaptchaAPIUrl());
} else {
preValidationResponse.setCaptchaValidationRequired(true);
preValidationResponse.setMaxFailedLimitReached(true);
addPostValidationData(servletRequest);
}
} else if (currentFailedAttempts == maxFailedAttempts && !initializationFlow) {
addPostValidationData(servletRequest);
}
return preValidationResponse;
}
use of org.wso2.carbon.identity.recovery.IdentityRecoveryException in project identity-governance by wso2-extensions.
the class SecurityQuestionApiServiceImpl method securityQuestionGet.
@Override
public Response securityQuestionGet(String username, String realm, String tenantDomain) {
if (IdentityUtil.threadLocalProperties.get().get(Constants.TENANT_NAME_FROM_CONTEXT) != null) {
tenantDomain = (String) IdentityUtil.threadLocalProperties.get().get(Constants.TENANT_NAME_FROM_CONTEXT);
}
User user = new User();
user.setUserName(username);
if (StringUtils.isNotBlank(realm)) {
user.setUserStoreDomain(realm);
} else {
user.setUserStoreDomain(UserStoreConfigConstants.PRIMARY);
}
if (StringUtils.isBlank(tenantDomain)) {
user.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
} else {
user.setTenantDomain(tenantDomain);
}
int tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
if (StringUtils.isBlank(realm)) {
String[] userList = RecoveryUtil.getUserList(tenantId, username);
if (ArrayUtils.isEmpty(userList)) {
String msg = "Unable to find an user with username: " + username + " in the system.";
LOG.error(msg);
} else if (userList.length == 1) {
user.setUserStoreDomain(IdentityUtil.extractDomainFromName(userList[0]));
} else {
String msg = "There are multiple users with username: " + username + " in the system, " + "please send the correct user-store domain along with the username.";
LOG.error(msg);
RecoveryUtil.handleBadRequest(msg, Constants.ERROR_CODE_MULTIPLE_USERS_MATCHING);
}
}
InitiateQuestionResponseDTO initiateQuestionResponseDTO = null;
SecurityQuestionPasswordRecoveryManager securityQuestionBasedPwdRecoveryManager = RecoveryUtil.getSecurityQuestionBasedPwdRecoveryManager();
try {
ChallengeQuestionResponse challengeQuestionResponse = securityQuestionBasedPwdRecoveryManager.initiateUserChallengeQuestion(user);
initiateQuestionResponseDTO = RecoveryUtil.getInitiateQuestionResponseDTO(challengeQuestionResponse);
} catch (IdentityRecoveryClientException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Client Error while initiating password recovery flow using security questions ", e);
}
if (IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_CHALLENGE_QUESTION_NOT_FOUND.getCode().equals(e.getErrorCode())) {
return Response.noContent().build();
}
RecoveryUtil.handleBadRequest(e.getMessage(), e.getErrorCode());
} catch (IdentityRecoveryException e) {
RecoveryUtil.handleInternalServerError(Constants.SERVER_ERROR, e.getErrorCode(), LOG, e);
} catch (Throwable throwable) {
RecoveryUtil.handleInternalServerError(Constants.SERVER_ERROR, IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED.getCode(), LOG, throwable);
}
return Response.accepted(initiateQuestionResponseDTO).build();
}
use of org.wso2.carbon.identity.recovery.IdentityRecoveryException in project identity-governance by wso2-extensions.
the class SetPasswordApiServiceImpl method setPasswordPost.
@Override
public Response setPasswordPost(ResetPasswordRequestDTO resetPasswordRequest) {
NotificationPasswordRecoveryManager notificationPasswordRecoveryManager = RecoveryUtil.getNotificationBasedPwdRecoveryManager();
User user = null;
try {
user = notificationPasswordRecoveryManager.updateUserPassword(resetPasswordRequest.getKey(), resetPasswordRequest.getPassword(), RecoveryUtil.getProperties(resetPasswordRequest.getProperties()));
} catch (IdentityRecoveryClientException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Client Error while resetting password ", e);
}
if (IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_HISTORY_VIOLATE.getCode().equals(e.getErrorCode())) {
RetryErrorDTO errorDTO = new RetryErrorDTO();
errorDTO.setCode(e.getErrorCode());
errorDTO.setMessage(e.getMessage());
errorDTO.setDescription(e.getMessage());
errorDTO.setKey(resetPasswordRequest.getKey());
return Response.status(Response.Status.PRECONDITION_FAILED).entity(errorDTO).build();
}
RecoveryUtil.handleBadRequest(e.getMessage(), e.getErrorCode());
} catch (IdentityRecoveryException e) {
RecoveryUtil.handleInternalServerError(Constants.SERVER_ERROR, e.getErrorCode(), LOG, e);
} catch (Throwable throwable) {
RecoveryUtil.handleInternalServerError(Constants.SERVER_ERROR, IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED.getCode(), LOG, throwable);
}
return Response.ok(RecoveryUtil.getUserDTO(user)).build();
}
use of org.wso2.carbon.identity.recovery.IdentityRecoveryException in project identity-governance by wso2-extensions.
the class ValidateAnswerApiServiceImpl method validateAnswerPost.
@Override
public Response validateAnswerPost(AnswerVerificationRequestDTO answerVerificationRequest) {
SecurityQuestionPasswordRecoveryManager securityQuestionBasedPwdRecoveryManager = RecoveryUtil.getSecurityQuestionBasedPwdRecoveryManager();
ChallengeQuestionResponse challengeQuestion = null;
try {
challengeQuestion = securityQuestionBasedPwdRecoveryManager.validateUserChallengeQuestions(RecoveryUtil.getUserChallengeAnswers(answerVerificationRequest.getAnswers()), answerVerificationRequest.getKey(), RecoveryUtil.getProperties(answerVerificationRequest.getProperties()));
} catch (IdentityRecoveryClientException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Client Error while verifying challenge answers in recovery flow", e);
}
if (IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_INVALID_ANSWER_FOR_SECURITY_QUESTION.getCode().equals(e.getErrorCode())) {
RetryErrorDTO errorDTO = new RetryErrorDTO();
errorDTO.setCode(e.getErrorCode());
errorDTO.setMessage(e.getMessage());
errorDTO.setDescription(e.getMessage());
errorDTO.setKey(answerVerificationRequest.getKey());
return Response.status(Response.Status.PRECONDITION_FAILED).entity(errorDTO).build();
}
RecoveryUtil.handleBadRequest(e.getMessage(), e.getErrorCode());
} catch (IdentityRecoveryException e) {
RecoveryUtil.handleInternalServerError(Constants.SERVER_ERROR, e.getErrorCode(), LOG, e);
} catch (Throwable throwable) {
RecoveryUtil.handleInternalServerError(Constants.SERVER_ERROR, IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED.getCode(), LOG, throwable);
}
return Response.ok(RecoveryUtil.getInitiateQuestionResponseDTO(challengeQuestion)).build();
}
use of org.wso2.carbon.identity.recovery.IdentityRecoveryException in project identity-governance by wso2-extensions.
the class RecoverPasswordApiServiceImplTest method testRecoverPasswordPost.
@Test
public void testRecoverPasswordPost() throws IdentityRecoveryException {
mockedIdentityTenantUtil.when(() -> IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
mockedRecoveryUtil.when(RecoveryUtil::getNotificationBasedPwdRecoveryManager).thenReturn(notificationPasswordRecoveryManager);
ResolvedUserResult resolvedUserResult = new ResolvedUserResult(ResolvedUserResult.UserResolvedStatus.FAIL);
Mockito.when(notificationPasswordRecoveryManager.sendRecoveryNotification(isNull(), anyString(), anyBoolean(), isNull())).thenReturn(notificationResponseBean);
mockedFrameworkUtils.when(() -> FrameworkUtils.processMultiAttributeLoginIdentification(anyString(), anyString())).thenReturn(resolvedUserResult);
assertEquals(recoverPasswordApiService.recoverPasswordPost(buildRecoveryInitiatingRequestDTO(), "", true).getStatus(), 202);
}
Aggregations