Search in sources :

Example 11 with UserRecoveryDataDO

use of org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO in project carbon-identity-framework by wso2.

the class RecoveryProcessor method verifyConfirmationKey.

/**
 * Confirm that confirmation key has been sent to the same user.
 *
 * @param sequence        TODO
 * @param username        TODO
 * @param confirmationKey confirmation key from the user
 * @return verification result as a bean
 */
public VerificationBean verifyConfirmationKey(String confirmationKey) {
    UserRecoveryDataDO dataDO = null;
    try {
        dataDO = dataStore.load(confirmationKey);
        dataStore.invalidate(dataDO);
    } catch (IdentityException e) {
        log.error("Invalid User for confirmation code", e);
        return new VerificationBean(VerificationBean.ERROR_CODE_INVALID_USER);
    }
    if (dataDO == null) {
        return new VerificationBean(VerificationBean.ERROR_CODE_INVALID_CODE);
    }
    if (!dataDO.isValid()) {
        return new VerificationBean(VerificationBean.ERROR_CODE_EXPIRED_CODE);
    } else {
        // Verification successful.
        return new VerificationBean(true);
    }
}
Also used : VerificationBean(org.wso2.carbon.identity.mgt.beans.VerificationBean) UserRecoveryDataDO(org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO) IdentityException(org.wso2.carbon.identity.base.IdentityException)

Example 12 with UserRecoveryDataDO

use of org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO in project carbon-identity-framework by wso2.

the class RecoveryProcessor method updateConfirmationCode.

public VerificationBean updateConfirmationCode(int sequence, String username, int tenantId) throws IdentityException {
    String confirmationKey = generateUserCode(sequence, username);
    String secretKey = UUIDGenerator.generateUUID();
    UserRecoveryDataDO recoveryDataDO = new UserRecoveryDataDO(username, tenantId, confirmationKey, secretKey);
    if (sequence != 3 && sequence != 30) {
        dataStore.invalidate(username, tenantId);
    }
    dataStore.store(recoveryDataDO);
    String externalCode = null;
    try {
        externalCode = getUserExternalCodeStr(confirmationKey);
    } catch (Exception e) {
        throw IdentityException.error("Error occurred while getting external code for user : " + username, e);
    }
    return new VerificationBean(username, externalCode);
}
Also used : VerificationBean(org.wso2.carbon.identity.mgt.beans.VerificationBean) UserRecoveryDataDO(org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO) UserStoreException(org.wso2.carbon.user.api.UserStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IdentityException(org.wso2.carbon.identity.base.IdentityException)

Example 13 with UserRecoveryDataDO

use of org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO in project carbon-identity-framework by wso2.

the class RecoveryProcessor method recoverWithNotification.

/**
 * Processing recovery
 *
 * @param recoveryDTO class that contains user and tenant Information
 * @return true if the reset request is processed successfully.
 * @throws IdentityException if fails
 */
public NotificationDataDTO recoverWithNotification(UserRecoveryDTO recoveryDTO) throws IdentityException {
    String notificationAddress;
    String secretKey = null;
    String confirmationKey = null;
    NotificationSendingModule module = null;
    boolean persistData = true;
    String userId = recoveryDTO.getUserId();
    String domainName = recoveryDTO.getTenantDomain();
    int tenantId = recoveryDTO.getTenantId();
    String userStore = IdentityUtil.extractDomainFromName(userId);
    String userName = UserCoreUtil.removeDomainFromName(userId);
    TenantManager tenantManager = IdentityMgtServiceComponent.getRealmService().getTenantManager();
    try {
        Tenant tenant = tenantManager.getTenant(tenantId);
        if (tenant != null) {
            domainName = tenant.getDomain();
        }
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("No Tenant domain for tenant id " + tenantId, e);
        }
    }
    NotificationDataDTO notificationData = new NotificationDataDTO();
    if (MessageContext.getCurrentMessageContext() != null && MessageContext.getCurrentMessageContext().getProperty(MessageContext.TRANSPORT_HEADERS) != null) {
        Map<String, String> transportHeaderMap = (Map) MessageContext.getCurrentMessageContext().getProperty(MessageContext.TRANSPORT_HEADERS);
        if (MapUtils.isNotEmpty(transportHeaderMap)) {
            TransportHeader[] transportHeadersArray = new TransportHeader[transportHeaderMap.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : transportHeaderMap.entrySet()) {
                TransportHeader transportHeader = new TransportHeader();
                transportHeader.setHeaderName(entry.getKey());
                transportHeader.setHeaderValue(entry.getValue());
                transportHeadersArray[i] = transportHeader;
                ++i;
            }
            notificationData.setTransportHeaders(transportHeadersArray);
        }
    }
    String internalCode = null;
    String type = recoveryDTO.getNotificationType();
    if (type != null) {
        module = modules.get(type);
    }
    if (module == null) {
        module = defaultModule;
    }
    NotificationData emailNotificationData = new NotificationData();
    String emailTemplate = null;
    notificationAddress = Utils.getEmailAddressForUser(userId, tenantId);
    String firstName = Utils.getClaimFromUserStoreManager(userId, tenantId, "http://wso2.org/claims/givenname");
    emailNotificationData.setTagData(FIRST_NAME, firstName);
    emailNotificationData.setTagData(USER_STORE_DOMAIN, userStore);
    emailNotificationData.setTagData(USER_NAME, userName);
    emailNotificationData.setTagData(TENANT_DOMAIN, domainName);
    if ((notificationAddress == null) || (notificationAddress.trim().length() < 0)) {
        throw IdentityException.error("Notification sending failure. Notification address is not defined for user : " + userId);
    }
    emailNotificationData.setSendTo(notificationAddress);
    if (log.isDebugEnabled()) {
        log.debug("Building notification with data - First name: " + firstName + " User name: " + userId + " Send To: " + notificationAddress);
    }
    Config config = null;
    ConfigBuilder configBuilder = ConfigBuilder.getInstance();
    try {
        config = configBuilder.loadConfiguration(ConfigType.EMAIL, StorageType.REGISTRY, tenantId);
    } catch (Exception e1) {
        throw IdentityException.error("Error while loading email templates for user : " + userId, e1);
    }
    if (recoveryDTO.getNotification() != null) {
        emailTemplate = config.getProperty(recoveryDTO.getNotification().trim());
        String notification = recoveryDTO.getNotification().trim();
        notificationData.setNotification(notification);
        if (IdentityMgtConstants.Notification.PASSWORD_RESET_RECOVERY.equals(notification) || IdentityMgtConstants.Notification.RESEND_NOTIFICATION.equals(notification)) {
            internalCode = generateUserCode(2, userId);
            try {
                confirmationKey = getUserExternalCodeStr(internalCode);
            } catch (Exception e) {
                throw IdentityException.error("Error while getting user's external code string.", e);
            }
            secretKey = UUIDGenerator.generateUUID();
            emailNotificationData.setTagData(CONFIRMATION_CODE, confirmationKey);
            emailTemplate = config.getProperty(notification);
        } else if (IdentityMgtConstants.Notification.ACCOUNT_CONFORM.equals(notification)) {
            confirmationKey = UUIDGenerator.generateUUID();
            secretKey = UUIDGenerator.generateUUID();
            emailNotificationData.setTagData(CONFIRMATION_CODE, confirmationKey);
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_CONFORM);
        } else if (IdentityMgtConstants.Notification.TEMPORARY_PASSWORD.equals(notification)) {
            // TODO
            String temporaryPassword = recoveryDTO.getTemporaryPassword();
            if (temporaryPassword == null || temporaryPassword.trim().length() < 1) {
                char[] chars = IdentityMgtConfig.getInstance().getPasswordGenerator().generatePassword();
                temporaryPassword = new String(chars);
            }
            Utils.updatePassword(userId, tenantId, temporaryPassword);
            emailNotificationData.setTagData(TEMPORARY_PASSWORD, temporaryPassword);
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.TEMPORARY_PASSWORD);
            persistData = false;
        } else if (IdentityMgtConstants.Notification.ACCOUNT_UNLOCK.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_UNLOCK);
            persistData = false;
        } else if (IdentityMgtConstants.Notification.ACCOUNT_ENABLE.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_ENABLE);
            persistData = false;
        } else if (IdentityMgtConstants.Notification.ACCOUNT_DISABLE.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_DISABLE);
            persistData = false;
        } else if (IdentityMgtConstants.Notification.ACCOUNT_ID_RECOVERY.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_ID_RECOVERY);
            persistData = false;
        } else if (IdentityMgtConstants.Notification.ASK_PASSWORD.equals(notification)) {
            if (firstName == null || firstName.isEmpty()) {
                emailNotificationData.setTagData(FIRST_NAME, userId);
            }
            internalCode = generateUserCode(2, userId);
            try {
                confirmationKey = getUserExternalCodeStr(internalCode);
            } catch (Exception e) {
                throw IdentityException.error("Error while with recovering with password.", e);
            }
            secretKey = UUIDGenerator.generateUUID();
            emailNotificationData.setTagData(CONFIRMATION_CODE, confirmationKey);
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ASK_PASSWORD);
        }
        if (log.isDebugEnabled()) {
            log.debug("Notification type: " + notification);
        }
    }
    Notification emailNotification = null;
    try {
        emailNotification = NotificationBuilder.createNotification("EMAIL", emailTemplate, emailNotificationData);
    } catch (Exception e) {
        throw IdentityException.error("Error when creating notification for user : " + userId, e);
    }
    notificationData.setNotificationAddress(notificationAddress);
    notificationData.setUserId(userId);
    notificationData.setDomainName(domainName);
    notificationData.setNotificationType(recoveryDTO.getNotificationType());
    if (persistData) {
        UserRecoveryDataDO recoveryDataDO = new UserRecoveryDataDO(userId, tenantId, internalCode, secretKey);
        dataStore.invalidate(userId, tenantId);
        dataStore.store(recoveryDataDO);
    }
    if (IdentityMgtConfig.getInstance().isNotificationInternallyManaged()) {
        module.setNotificationData(notificationData);
        module.setNotification(emailNotification);
        notificationSender.sendNotification(module);
        notificationData.setNotificationSent(true);
    } else {
        notificationData.setNotificationSent(false);
        notificationData.setNotificationCode(confirmationKey);
    }
    return notificationData;
}
Also used : Config(org.wso2.carbon.identity.mgt.config.Config) NotificationDataDTO(org.wso2.carbon.identity.mgt.dto.NotificationDataDTO) UserStoreException(org.wso2.carbon.user.api.UserStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IdentityException(org.wso2.carbon.identity.base.IdentityException) Notification(org.wso2.carbon.identity.mgt.mail.Notification) TransportHeader(org.wso2.carbon.identity.mgt.mail.TransportHeader) Tenant(org.wso2.carbon.user.api.Tenant) UserRecoveryDataDO(org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ConfigBuilder(org.wso2.carbon.identity.mgt.config.ConfigBuilder) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) HashMap(java.util.HashMap) Map(java.util.Map) NotificationData(org.wso2.carbon.identity.mgt.mail.NotificationData)

Example 14 with UserRecoveryDataDO

use of org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO in project carbon-identity-framework by wso2.

the class RecoveryProcessor method verifyUserForRecovery.

/**
 * Verifies user id with underline user store
 *
 * @param sequence TODO
 * @param userDTO  bean class that contains user and tenant Information
 * @return true/false whether user is verified or not. If user is a tenant
 * user then always return false
 */
public VerificationBean verifyUserForRecovery(int sequence, UserDTO userDTO) {
    String userId = userDTO.getUserId();
    int tenantId = userDTO.getTenantId();
    boolean success = false;
    VerificationBean bean = null;
    try {
        UserStoreManager userStoreManager = IdentityMgtServiceComponent.getRealmService().getTenantUserRealm(tenantId).getUserStoreManager();
        if (userStoreManager.isExistingUser(userId)) {
            if (IdentityMgtConfig.getInstance().isAuthPolicyAccountLockCheck()) {
                String accountLock = Utils.getClaimFromUserStoreManager(userId, tenantId, UserIdentityDataStore.ACCOUNT_LOCK);
                if (!Boolean.parseBoolean(accountLock)) {
                    success = true;
                } else {
                // account is Locked. Not allowing to recover.
                }
            } else if (IdentityMgtConfig.getInstance().isAuthPolicyAccountDisableCheck()) {
                String accountDisable = Utils.getClaimFromUserStoreManager(userId, tenantId, UserIdentityDataStore.ACCOUNT_DISABLED);
                if (!Boolean.parseBoolean(accountDisable)) {
                    success = true;
                } else {
                    // account is Disabled. Not allowing to recover.
                    if (log.isDebugEnabled()) {
                        log.debug("Account is disabled. Can not allow to recover.");
                    }
                    bean = new VerificationBean(VerificationBean.ERROR_CODE_DISABLED_ACCOUNT);
                }
            } else {
                success = true;
            }
        } else {
            log.error("User with user name : " + userId + " does not exists in tenant domain : " + userDTO.getTenantDomain());
            bean = new VerificationBean(VerificationBean.ERROR_CODE_INVALID_USER + " " + "User does not exists");
        }
        if (success) {
            String internalCode = generateUserCode(sequence, userId);
            String key = UUID.randomUUID().toString();
            UserRecoveryDataDO dataDO = new UserRecoveryDataDO(userId, tenantId, internalCode, key);
            if (sequence != 3) {
                dataStore.invalidate(userId, tenantId);
            }
            dataStore.store(dataDO);
            log.info("User verification successful for user : " + userId + " from tenant domain :" + userDTO.getTenantDomain());
            bean = new VerificationBean(userId, getUserExternalCodeStr(internalCode));
        }
    } catch (Exception e) {
        String errorMessage = "Error verifying user : " + userId;
        log.error(errorMessage, e);
        bean = new VerificationBean(VerificationBean.ERROR_CODE_UNEXPECTED + " " + errorMessage);
    }
    if (bean == null) {
        bean = new VerificationBean(VerificationBean.ERROR_CODE_UNEXPECTED);
    }
    return bean;
}
Also used : VerificationBean(org.wso2.carbon.identity.mgt.beans.VerificationBean) UserRecoveryDataDO(org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IdentityException(org.wso2.carbon.identity.base.IdentityException)

Example 15 with UserRecoveryDataDO

use of org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO in project carbon-identity-framework by wso2.

the class UserIdentityManagementService method recoverUserIdentityWithSecurityQuestions.

/**
 * Checks the security questions and their answerers against the user's
 * stored questions and answerers. If not all security questions of the user
 * are answered, an exception will be thrown. After all security questions
 * are answered properly, then the system will generate a random password,
 * and reset the user password with it and then will be returned the
 * resulting DTO containing the temporary password.
 * TODO : Re-think
 *
 * @param userName
 * @param secQuesAnsweres
 * @return
 * @throws IdentityMgtServiceException
 */
public void recoverUserIdentityWithSecurityQuestions(String userName, UserIdentityClaimDTO[] secQuesAnsweres) throws IdentityMgtServiceException {
    try {
        int tenantId = Utils.getTenantId(MultitenantUtils.getTenantDomain(userName));
        UserStoreManager userStoreManager = IdentityMgtServiceComponent.getRealmService().getTenantUserRealm(tenantId).getUserStoreManager();
        UserIdentityClaimDTO[] storedSecQuesAnswers = UserIdentityManagementUtil.getUserSecurityQuestions(userName, userStoreManager);
        // have not answered all questions of the user
        if (secQuesAnsweres.length < storedSecQuesAnswers.length) {
            throw new IdentityMgtServiceException("All questions must be answered");
        }
        // NOW check the answer for every question
        // 
        int numberOfAnsweredQuestions = 0;
        // for every stored security question
        for (UserIdentityClaimDTO storedSecQues : storedSecQuesAnswers) {
            // for every answered security question
            for (UserIdentityClaimDTO answredSecQues : secQuesAnsweres) {
                // when the questions are equal, check for the answer
                if (answredSecQues.getClaimUri().trim().equals(storedSecQues.getClaimUri().trim())) {
                    // if answerers are not equal, throw an exception
                    if (!answredSecQues.getClaimValue().trim().equals(storedSecQues.getClaimValue().trim())) {
                        throw new IdentityMgtServiceException("Invalid answeres. Identity recovery failed");
                    }
                    numberOfAnsweredQuestions++;
                }
            }
        }
        // not all USER's security questions has been answered
        if (numberOfAnsweredQuestions < storedSecQuesAnswers.length) {
            throw new IdentityMgtServiceException("All questions must be answered");
        }
        // now okay to recover
        // reset the password with a random value
        char[] tempPassword = UserIdentityManagementUtil.generateTemporaryPassword();
        userStoreManager.updateCredentialByAdmin(userName, tempPassword);
        // store the temp password as a Metadata
        UserRecoveryDataDO metadataDO = new UserRecoveryDataDO();
        metadataDO.setUserName(userName).setTenantId(tenantId).setCode(new String(tempPassword));
        UserIdentityManagementUtil.storeUserIdentityMetadata(metadataDO);
        // sending an email to the user
        UserIdentityMgtBean bean = new UserIdentityMgtBean();
        String email = userStoreManager.getUserClaimValue(userName, IdentityMgtConfig.getInstance().getAccountRecoveryClaim(), null);
        log.debug("Sending email to " + email);
        bean.setUserId(userName).setUserTemporaryPassword(new String(tempPassword)).setEmail(email);
        UserIdentityManagementUtil.notifyViaEmail(bean);
    } catch (UserStoreException e) {
        log.error("Error while recovering user identity", e);
        throw new IdentityMgtServiceException("Error while recovering user identity");
    } catch (IdentityException e) {
        log.error("Error while recovering user identity", e);
        throw new IdentityMgtServiceException("Error while recovering user identity");
    }
}
Also used : IdentityMgtServiceException(org.wso2.carbon.identity.mgt.IdentityMgtServiceException) UserRecoveryDataDO(org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO) UserIdentityMgtBean(org.wso2.carbon.identity.mgt.beans.UserIdentityMgtBean) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) UserIdentityClaimDTO(org.wso2.carbon.identity.mgt.dto.UserIdentityClaimDTO) IdentityException(org.wso2.carbon.identity.base.IdentityException)

Aggregations

UserRecoveryDataDO (org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO)16 IdentityException (org.wso2.carbon.identity.base.IdentityException)7 VerificationBean (org.wso2.carbon.identity.mgt.beans.VerificationBean)4 JDBCUserRecoveryDataStore (org.wso2.carbon.identity.mgt.store.JDBCUserRecoveryDataStore)4 UserStoreException (org.wso2.carbon.user.api.UserStoreException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 Connection (java.sql.Connection)3 PreparedStatement (java.sql.PreparedStatement)3 SQLException (java.sql.SQLException)3 Registry (org.wso2.carbon.registry.core.Registry)3 Resource (org.wso2.carbon.registry.core.Resource)3 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)3 ResultSet (java.sql.ResultSet)2 ArrayList (java.util.ArrayList)2 NotificationDataDTO (org.wso2.carbon.identity.mgt.dto.NotificationDataDTO)2 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)2 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Properties (java.util.Properties)1 IdentityMgtServiceException (org.wso2.carbon.identity.mgt.IdentityMgtServiceException)1