Search in sources :

Example 1 with AccountLockServiceException

use of org.wso2.carbon.identity.handler.event.account.lock.exception.AccountLockServiceException 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;
}
Also used : AccountLockServiceException(org.wso2.carbon.identity.handler.event.account.lock.exception.AccountLockServiceException) CaptchaHttpServletRequestWrapper(org.wso2.carbon.identity.captcha.util.CaptchaHttpServletRequestWrapper) User(org.wso2.carbon.identity.application.common.model.User) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject) HttpServletResponse(javax.servlet.http.HttpServletResponse) CaptchaServerException(org.wso2.carbon.identity.captcha.exception.CaptchaServerException) IOException(java.io.IOException) CaptchaClientException(org.wso2.carbon.identity.captcha.exception.CaptchaClientException) CaptchaException(org.wso2.carbon.identity.captcha.exception.CaptchaException) IOException(java.io.IOException) CaptchaServerException(org.wso2.carbon.identity.captcha.exception.CaptchaServerException) IdentityRecoveryException(org.wso2.carbon.identity.recovery.IdentityRecoveryException) IdentityGovernanceException(org.wso2.carbon.identity.governance.IdentityGovernanceException) AccountLockServiceException(org.wso2.carbon.identity.handler.event.account.lock.exception.AccountLockServiceException) IdentityGovernanceException(org.wso2.carbon.identity.governance.IdentityGovernanceException) CaptchaPreValidationResponse(org.wso2.carbon.identity.captcha.connector.CaptchaPreValidationResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserRecoveryData(org.wso2.carbon.identity.recovery.model.UserRecoveryData) UserRecoveryDataStore(org.wso2.carbon.identity.recovery.store.UserRecoveryDataStore) IdentityRecoveryException(org.wso2.carbon.identity.recovery.IdentityRecoveryException) Property(org.wso2.carbon.identity.application.common.model.Property) JsonParser(com.google.gson.JsonParser)

Example 2 with AccountLockServiceException

use of org.wso2.carbon.identity.handler.event.account.lock.exception.AccountLockServiceException in project carbon-identity-framework by wso2.

the class JITProvisioningPostAuthenticationHandlerTest method testHandleWithAuthenticatedUserWithFederatedIdp.

@Test(description = "This test case tests the Post JIT provisioning handling flow with an authenticated user")
public void testHandleWithAuthenticatedUserWithFederatedIdp() throws FrameworkException, FederatedAssociationManagerException, AccountLockServiceException, UserStoreException {
    AuthenticationContext context = processAndGetAuthenticationContext(sp, true, true);
    FederatedAssociationManager federatedAssociationManager = mock(FederatedAssociationManagerImpl.class);
    when(FrameworkUtils.getFederatedAssociationManager()).thenReturn(federatedAssociationManager);
    doReturn("test").when(federatedAssociationManager).getUserForFederatedAssociation(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    when(FrameworkUtils.getStepBasedSequenceHandler()).thenReturn(Mockito.mock(StepBasedSequenceHandler.class));
    mockStatic(FrameworkServiceDataHolder.class);
    PowerMockito.when(FrameworkServiceDataHolder.getInstance()).thenReturn(frameworkServiceDataHolder);
    mockStatic(AccountLockService.class);
    when(frameworkServiceDataHolder.getAccountLockService()).thenReturn(accountLockService);
    when(accountLockService.isAccountLocked(anyString(), anyString())).thenReturn(false);
    RealmService mockRealmService = mock(RealmService.class);
    PowerMockito.when(FrameworkServiceDataHolder.getInstance().getRealmService()).thenReturn(mockRealmService);
    UserRealm mockUserRealm = mock(UserRealm.class);
    UserStoreManager mockUserStoreManager = mock(UserStoreManager.class);
    Map<String, String> mockClaimValues = mock(HashMap.class);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(1);
    when(mockRealmService.getTenantUserRealm(anyInt())).thenReturn(mockUserRealm);
    when(mockUserRealm.getUserStoreManager()).thenReturn(mockUserStoreManager);
    when(mockUserStoreManager.getUserClaimValues(anyString(), eq(new String[] { AccountConstants.ACCOUNT_DISABLED_CLAIM }), eq(UserCoreConstants.DEFAULT_PROFILE))).thenReturn(mockClaimValues);
    when(mockClaimValues.get(AccountConstants.ACCOUNT_DISABLED_CLAIM)).thenReturn("false");
    PostAuthnHandlerFlowStatus postAuthnHandlerFlowStatus = postJITProvisioningHandler.handle(request, response, context);
    Assert.assertEquals(postAuthnHandlerFlowStatus, PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED, "Post JIT provisioning handler executed while having a authenticated user without federated " + "authenticator");
}
Also used : FederatedAssociationManager(org.wso2.carbon.identity.user.profile.mgt.association.federation.FederatedAssociationManager) AuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext) UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) Mockito.anyString(org.mockito.Mockito.anyString) StepBasedSequenceHandler(org.wso2.carbon.identity.application.authentication.framework.handler.sequence.StepBasedSequenceHandler) PostAuthnHandlerFlowStatus(org.wso2.carbon.identity.application.authentication.framework.handler.request.PostAuthnHandlerFlowStatus) Test(org.testng.annotations.Test) AbstractFrameworkTest(org.wso2.carbon.identity.application.authentication.framework.AbstractFrameworkTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

JsonObject (com.google.gson.JsonObject)1 JsonParser (com.google.gson.JsonParser)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 Mockito.anyString (org.mockito.Mockito.anyString)1 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)1 Test (org.testng.annotations.Test)1 AbstractFrameworkTest (org.wso2.carbon.identity.application.authentication.framework.AbstractFrameworkTest)1 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)1 PostAuthnHandlerFlowStatus (org.wso2.carbon.identity.application.authentication.framework.handler.request.PostAuthnHandlerFlowStatus)1 StepBasedSequenceHandler (org.wso2.carbon.identity.application.authentication.framework.handler.sequence.StepBasedSequenceHandler)1 Property (org.wso2.carbon.identity.application.common.model.Property)1 User (org.wso2.carbon.identity.application.common.model.User)1 CaptchaPreValidationResponse (org.wso2.carbon.identity.captcha.connector.CaptchaPreValidationResponse)1 CaptchaClientException (org.wso2.carbon.identity.captcha.exception.CaptchaClientException)1 CaptchaException (org.wso2.carbon.identity.captcha.exception.CaptchaException)1 CaptchaServerException (org.wso2.carbon.identity.captcha.exception.CaptchaServerException)1 CaptchaHttpServletRequestWrapper (org.wso2.carbon.identity.captcha.util.CaptchaHttpServletRequestWrapper)1