org.wso2.carbon.user.core.UserCoreConstants Java Examples

The following examples show how to use org.wso2.carbon.user.core.UserCoreConstants. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserStoreActionListener.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public boolean doPreAddRole(String roleName, String[] userList, Permission[] permissions, UserStoreManager
        userStoreManager) throws UserStoreException {

    try {
        if (!isEnable() || isCalledViaIdentityMgtListners()) {
            return true;
        }
        AddRoleWFRequestHandler addRoleWFRequestHandler = new AddRoleWFRequestHandler();
        String domain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig
                                                                                              .PROPERTY_DOMAIN_NAME);

        int tenantId = userStoreManager.getTenantId() ;
        String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(currentUser);

        return addRoleWFRequestHandler.startAddRoleFlow(domain, roleName, userList, permissions);
    } catch (WorkflowException e) {
        // Sending e.getMessage() since it is required to give error message to end user.
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #2
Source File: StratosUserManagerUtils.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Add a user to the user-store of the particular tenant
 *
 * @param userStoreManager UserStoreManager
 * @param userInfoBean     UserInfoBean
 * @throws UserManagerException
 */
public static void addUser(UserStoreManager userStoreManager, UserInfoBean userInfoBean)
        throws UserManagerException {

    if (log.isDebugEnabled()) {
        log.debug("Creating new User: " + userInfoBean.getUserName());
    }

    String[] roles = new String[1];
    roles[0] = userInfoBean.getRole();
    Map<String, String> claims = new HashMap<String, String>();

    //set firstname, lastname and email as user claims
    claims.put(UserCoreConstants.ClaimTypeURIs.EMAIL_ADDRESS, userInfoBean.getEmail());
    claims.put(UserCoreConstants.ClaimTypeURIs.GIVEN_NAME, userInfoBean.getFirstName());
    claims.put(UserCoreConstants.ClaimTypeURIs.SURNAME, userInfoBean.getLastName());

    try {
        userStoreManager.addUser(userInfoBean.getUserName(), userInfoBean.getCredential(), roles, claims, userInfoBean.getProfileName());
    } catch (UserStoreException e) {
        String msg = "Error in adding user " + userInfoBean.getUserName() + " to User Store";
        log.error(msg, e);
        throw new UserManagerException(e.getMessage());
    }

}
 
Example #3
Source File: AbstractApplicationAuthenticatorTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@DataProvider(name = "usernameProvider")
public Object[][] getUsernames() {

    String userStoreDomainAppendedName = USER_STORE_NAME + UserCoreConstants.DOMAIN_SEPARATOR + USER_NAME;

    return new Object[][]{
            {
                    // username already has a domain appended
                    userStoreDomainAppendedName, "WSO2.COM", userStoreDomainAppendedName
            },
            {
                    // setting domain from threadlocal
                    USER_NAME, USER_STORE_NAME, userStoreDomainAppendedName
            },
            {
                    // username doesn't have domain, thread local domain is empty too
                    USER_NAME, null, USER_NAME
            },
            {
                    // username doesn't have domain, thread local domain is empty too
                    USER_NAME, "", USER_NAME
            },

    };
}
 
Example #4
Source File: LDAPServerStoreManagerTest.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void setUp() {

        this.realmConfiguration = new RealmConfiguration();

        Map<String,String> map = new HashMap<String, String>();
        map.put(UserCoreConstants.RealmConfig.PROPERTY_JAVA_REG_EX, "[\\S]{5,30}");
        map.put(LDAPConstants.USER_SEARCH_BASE, "ou=Users,dc=example,dc=com");
        map.put("PASSWORD_HASH_METHOD", "PlainText");
        map.put("DEFAULT_REALM_NAME", "EXAMPLE..COM");
        map.put(LDAPConstants.CONNECTION_URL, "ldap://localhost:10389");
        map.put(LDAPConstants.CONNECTION_NAME, "uid=admin,ou=system");
        map.put(LDAPConstants.CONNECTION_PASSWORD, "secret");
        map.put(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST, "50");
        map.put(LDAPConstants.USER_NAME_LIST_FILTER, "(objectClass=person)");


        this.realmConfiguration.setUserStoreProperties(map);
        
    }
 
Example #5
Source File: WorkflowImplTenantMgtListener.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public void onTenantCreate(TenantInfoBean tenantInfoBean) throws StratosException {
    String fullName = tenantInfoBean.getAdmin() + UserCoreConstants.TENANT_DOMAIN_COMBINER + tenantInfoBean.getTenantDomain() ;
    BPSProfile bpsProfileDTO = new BPSProfile();
    String url = IdentityUtil.getServerURL(WorkflowImplServiceDataHolder.getInstance()
            .getConfigurationContextService().getServerConfigContext().getServicePath(), true, true);
    try {
        bpsProfileDTO.setManagerHostURL(url);
        bpsProfileDTO.setWorkerHostURL(url);
        bpsProfileDTO.setUsername(fullName);
        bpsProfileDTO.setPassword(new char[0]);
        bpsProfileDTO.setProfileName(WFImplConstant.DEFAULT_BPS_PROFILE_NAME);

        WorkflowImplServiceDataHolder.getInstance().getWorkflowImplService()
                .addBPSProfile(bpsProfileDTO, tenantInfoBean
                        .getTenantId());

    }catch (WorkflowImplException e) {
        //This is not thrown exception because this is not blocked to the other functionality. User can create
        // default profile by manually.
        String errorMsg = "Error occured while adding default bps profile, " + e.getMessage();
        log.error(errorMsg);
    }

}
 
Example #6
Source File: DefaultProvisioningHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Check for internal roles and convert internal role domain names to camel case to match with predefined
 * internal role domains.
 *
 * @param roles roles to verify and update
 * @return updated role list
 */
private List<String> convertInternalRoleDomainsToCamelCase(List<String> roles) {

    List<String> updatedRoles = new ArrayList<>();

    if (roles != null) {
        // If internal roles exist, convert internal role domain names to case sensitive predefined domain names.
        for (String role : roles) {
            if (StringUtils.containsIgnoreCase(role, UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants
                    .DOMAIN_SEPARATOR)) {
                updatedRoles.add(UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR +
                        UserCoreUtil.removeDomainFromName(role));
            } else if (StringUtils.containsIgnoreCase(role, APPLICATION_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR)) {
                updatedRoles.add(APPLICATION_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR + UserCoreUtil
                        .removeDomainFromName(role));
            } else if (StringUtils.containsIgnoreCase(role, WORKFLOW_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR)) {
                updatedRoles.add(WORKFLOW_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR + UserCoreUtil
                        .removeDomainFromName(role));
            } else {
                updatedRoles.add(role);
            }
        }
    }

    return updatedRoles;
}
 
Example #7
Source File: UserRealmProxy.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void mapEntityName(String entityName, FlaggedName fName,
                           UserStoreManager userStoreManager) {
    if (entityName.contains(UserCoreConstants.SHARED_ROLE_TENANT_SEPERATOR)) {
        String[] nameAndDn = entityName.split(UserCoreConstants.SHARED_ROLE_TENANT_SEPERATOR);
        fName.setItemName(nameAndDn[0]);
        fName.setDn(nameAndDn[1]);

        // TODO remove abstract user store
        fName.setShared(((AbstractUserStoreManager) userStoreManager).isOthersSharedRole(entityName));
        if (fName.isShared()) {
            fName.setItemDisplayName(UserCoreConstants.SHARED_ROLE_TENANT_SEPERATOR +
                    fName.getItemName());
        }

    } else {
        fName.setItemName(entityName);
    }

}
 
Example #8
Source File: DefaultRequestCoordinator.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * This method retrieves requested claim value from the user store
 *
 * @param username
 * @param userStoreManager
 * @param claimURI
 * @return claim value as a String
 * @throws FrameworkException
 */
private String getClaimValue(String username, UserStoreManager userStoreManager, String claimURI) throws
        FrameworkException {

    try {
        Map<String, String> values = userStoreManager.getUserClaimValues(username, new String[]{claimURI},
                UserCoreConstants.DEFAULT_PROFILE);
        if (log.isDebugEnabled()) {
            log.debug(String.format("%s claim value of user %s is set to: " + values.get(claimURI),
                    claimURI, username));
        }
        return values.get(claimURI);

    } catch (UserStoreException e) {
        throw new FrameworkException("Error occurred while retrieving claim: " + claimURI, e);
    }
}
 
Example #9
Source File: SecondaryUserStoreConfigurationUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static Map<String, String> getSecondaryUserStorePropertiesFromTenantUserRealm(String userStoreDomain)
        throws IdentityUserStoreMgtException {

    Map<String, String> secondaryUserStoreProperties = null;
    try {
        RealmConfiguration realmConfiguration = UserStoreConfigComponent.getRealmService().getTenantUserRealm(
                getTenantIdInTheCurrentContext()).getRealmConfiguration();
        while (realmConfiguration != null) {
            String domainName = realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig
                    .PROPERTY_DOMAIN_NAME);
            if (StringUtils.equalsIgnoreCase(domainName, userStoreDomain)) {
                secondaryUserStoreProperties = realmConfiguration.getUserStoreProperties();
                break;
            } else {
                realmConfiguration = realmConfiguration.getSecondaryRealmConfig();
            }
        }
    } catch (UserStoreException e) {
        String errorMessage = "Error while retrieving user store configurations for user store domain: "
                + userStoreDomain;
        throw new IdentityUserStoreMgtException(errorMessage, e);
    }
    return secondaryUserStoreProperties;
}
 
Example #10
Source File: UserSignUpWorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Method to delete a user
 * @param serverURL
 * @param adminUsername
 * @param adminPassword
 * @param userName
 * @throws Exception
 */
protected static void deleteUser(String serverURL, String adminUsername,
                                 String adminPassword, String userName) throws Exception {
	if (log.isDebugEnabled()) {
		log.debug("Remove the rejected user :" + userName);
	}		
	String url = serverURL + "UserAdmin";
	
	int index = userName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
	//remove the PRIMARY part from the user name
	if (index > 0) {
		if(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equalsIgnoreCase(userName.substring(0, index))){
			userName = userName.substring(index + 1);
		}			
	} 

	UserAdminStub userAdminStub = new UserAdminStub(url);
	CarbonUtils.setBasicAccessSecurityHeaders(adminUsername, adminPassword, userAdminStub._getServiceClient());
	userAdminStub.deleteUser(userName);

}
 
Example #11
Source File: UserStoreActionListener.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public boolean doPreDeleteUserClaimValues(String userName, String[] claims, String profileName, UserStoreManager
        userStoreManager) throws UserStoreException {

    if (!isEnable() || isCalledViaIdentityMgtListners()) {
        return true;
    }
    try {
        DeleteMultipleClaimsWFRequestHandler deleteMultipleClaimsWFRequestHandler = new DeleteMultipleClaimsWFRequestHandler();
        String domain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig
                                                                                              .PROPERTY_DOMAIN_NAME);
        int tenantId = userStoreManager.getTenantId() ;
        String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(currentUser);

        return deleteMultipleClaimsWFRequestHandler.startDeleteMultipleClaimsWorkflow(domain, userName, claims,
                profileName);
    } catch (WorkflowException e) {
        // Sending e.getMessage() since it is required to give error message to end user.
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #12
Source File: UserStoreActionListener.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public boolean doPreUpdateRoleName(String roleName, String newRoleName, UserStoreManager userStoreManager) throws
        UserStoreException {
    if (!isEnable() || isCalledViaIdentityMgtListners()) {
        return true;
    }
    try {
        UpdateRoleNameWFRequestHandler updateRoleNameWFRequestHandler = new UpdateRoleNameWFRequestHandler();
        String domain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig
                                                                                              .PROPERTY_DOMAIN_NAME);

        int tenantId = userStoreManager.getTenantId() ;
        String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(currentUser);

        return updateRoleNameWFRequestHandler.startUpdateRoleNameFlow(domain, roleName, newRoleName);
    } catch (WorkflowException e) {
        // Sending e.getMessage() since it is required to give error message to end user.
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #13
Source File: UserStoreActionListener.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public boolean doPreDeleteRole(String roleName, UserStoreManager userStoreManager) throws UserStoreException {

    if (!isEnable() || isCalledViaIdentityMgtListners()) {
        return true;
    }
    try {
        DeleteRoleWFRequestHandler deleteRoleWFRequestHandler = new DeleteRoleWFRequestHandler();
        String domain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig
                                                                                              .PROPERTY_DOMAIN_NAME);

        int tenantId = userStoreManager.getTenantId() ;
        String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(currentUser);

        return deleteRoleWFRequestHandler.startDeleteRoleFlow(domain, roleName);
    } catch (WorkflowException e) {
        // Sending e.getMessage() since it is required to give error message to end user.
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #14
Source File: ApplicationManagementAdminService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Method to retrieve all the application roles of a user.
 *
 * @param username User name.
 * @return Application role list.
 * @throws IdentityApplicationManagementException Error in retrieving roles of a user.
 */
private List<String> getApplicationRolesOfUser(String username) throws IdentityApplicationManagementException {

    try {
        String[] userRoles = CarbonContext.getThreadLocalCarbonContext().getUserRealm().
                getUserStoreManager().getRoleListOfUser(username);
        List<String> applicationRoles = new ArrayList<>();
        if (userRoles != null) {
            String applicationRoleDomain =
                    ApplicationConstants.APPLICATION_DOMAIN + UserCoreConstants.DOMAIN_SEPARATOR;
            for (String role : userRoles) {
                if (role.startsWith(applicationRoleDomain)) {
                    applicationRoles.add(role);
                }
            }
        }
        return applicationRoles;
    } catch (UserStoreException e) {
        throw new IdentityApplicationManagementException("Error while retrieving application roles for user: " +
                username, e);
    }
}
 
Example #15
Source File: User.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a User object constructed from fully qualified username
 *
 * @param username Fully qualified username
 * @return User object
 * @throws IllegalArgumentException
 */
public static User getUserFromUserName(String username) {

    User user = new User();
    if (StringUtils.isNotBlank(username)) {
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
        String tenantAwareUsernameWithNoUserDomain = UserCoreUtil.removeDomainFromName(tenantAwareUsername);
        String userStoreDomain = IdentityUtil.extractDomainFromName(username).toUpperCase(Locale.ENGLISH);
        user.setUserName(tenantAwareUsernameWithNoUserDomain);
        if (StringUtils.isNotEmpty(tenantDomain)) {
            user.setTenantDomain(tenantDomain);
        } else {
            user.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        }
        if (StringUtils.isNotEmpty(userStoreDomain)) {
            user.setUserStoreDomain(userStoreDomain);
        } else {
            user.setTenantDomain(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME);
        }
    }
    return user;
}
 
Example #16
Source File: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Appends domain name to the user/role name
 *
 * @param name       user/role name
 * @param domainName domain name
 * @return application name with domain name
 */
public static String addDomainToName(String name, String domainName) {

    if (domainName != null && name != null && !name.contains(UserCoreConstants.DOMAIN_SEPARATOR)) {
        if (!UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equalsIgnoreCase(domainName)) {
            if (UserCoreConstants.INTERNAL_DOMAIN.equalsIgnoreCase(domainName) ||
                    WORKFLOW_DOMAIN.equalsIgnoreCase(domainName) || APPLICATION_DOMAIN.equalsIgnoreCase(domainName)) {
                name = domainName.substring(0, 1).toUpperCase() + domainName.substring(1).toLowerCase() +
                        UserCoreConstants.DOMAIN_SEPARATOR + name;
            } else {
                name = domainName.toUpperCase() + UserCoreConstants.DOMAIN_SEPARATOR + name;
            }
        }
    }
    return name;
}
 
Example #17
Source File: UserRealmProxy.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void mapEntityName(String entityName, FlaggedName fName,
                           UserStoreManager userStoreManager) {
    if (entityName.contains(UserCoreConstants.SHARED_ROLE_TENANT_SEPERATOR)) {
        String[] nameAndDn = entityName.split(UserCoreConstants.SHARED_ROLE_TENANT_SEPERATOR);
        fName.setItemName(nameAndDn[0]);
        fName.setDn(nameAndDn[1]);

        // TODO remove abstract user store
        fName.setShared(((AbstractUserStoreManager) userStoreManager).isOthersSharedRole(entityName));
        if (fName.isShared()) {
            fName.setItemDisplayName(UserCoreConstants.SHARED_ROLE_TENANT_SEPERATOR +
                    fName.getItemName());
        }

    } else {
        fName.setItemName(entityName);
    }

}
 
Example #18
Source File: IdentityMgtEventListener.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
     * This method checks if the updating claim is an user identity data or
     * security question. Identity data and security questions are updated by
     * the identity store, therefore they will not be added to the user store.
     * Other claims are skipped to the set or update.
     */
    @Override
    public boolean doPreSetUserClaimValue(String userName, String claimURI, String claimValue,
                                          String profileName, UserStoreManager userStoreManager)
            throws UserStoreException {
        if (!isEnable()) {
            return true;
        }

        IdentityMgtConfig config = IdentityMgtConfig.getInstance();

        // security questions and identity claims are updated at the identity store
        if (claimURI.contains(UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI) ||
                claimURI.contains(UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI)) {
//			  the whole listner to return and fail adding the cliam in doSetUserClaim
            return true;
        } else {
            // a simple user claim. add it to the user store
            return true;
        }
    }
 
Example #19
Source File: UserIdentityManagementUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Remove primary security questions
 *
 * @param tenantId
 * @throws IdentityException
 */
public static void removePrimaryQuestions(String[] primarySecurityQuestion, int tenantId) throws IdentityException {

    UserRecoveryDataDO[] metadata = new UserRecoveryDataDO[primarySecurityQuestion.length];
    int i = 0;
    for (String secQuestion : primarySecurityQuestion) {
        if (!secQuestion.contains(UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI)) {
            throw IdentityException.error("One or more security questions does not contain the namespace " +
                    UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI);
        }
        metadata[i++] =
                new UserRecoveryDataDO("TENANT", tenantId,
                        UserRecoveryDataDO.METADATA_PRIMARAY_SECURITY_QUESTION,
                        secQuestion);
    }

}
 
Example #20
Source File: FIDOAuthenticator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private AuthenticatedUser getUsername(AuthenticationContext context) throws AuthenticationFailedException {
    //username from authentication context.
    AuthenticatedUser authenticatedUser = null;
    for (int i = 1; i <= context.getSequenceConfig().getStepMap().size(); i++) {
        StepConfig stepConfig = context.getSequenceConfig().getStepMap().get(i);
        if (stepConfig.getAuthenticatedUser() != null && stepConfig.getAuthenticatedAutenticator()
                .getApplicationAuthenticator() instanceof LocalApplicationAuthenticator) {
            authenticatedUser = stepConfig.getAuthenticatedUser();
            if (authenticatedUser.getUserStoreDomain() == null) {
                authenticatedUser.setUserStoreDomain(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME);
            }


            if (log.isDebugEnabled()) {
                log.debug("username :" + authenticatedUser.toString());
            }
            break;
        }
    }
    if(authenticatedUser == null){
        throw new AuthenticationFailedException("Could not locate an authenticated username from previous steps " +
                "of the sequence. Hence cannot continue with FIDO authentication.");
    }
    return authenticatedUser;
}
 
Example #21
Source File: UserStoreActionListener.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public boolean doPreDeleteUser(String userName, UserStoreManager userStoreManager) throws UserStoreException {

    if (!isEnable() || isCalledViaIdentityMgtListners()) {
        return true;
    }
    try {
        DeleteUserWFRequestHandler deleteUserWFRequestHandler = new DeleteUserWFRequestHandler();
        String domain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig
                                                                                              .PROPERTY_DOMAIN_NAME);
        int tenantId = userStoreManager.getTenantId() ;
        String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(currentUser);

        return deleteUserWFRequestHandler.startDeleteUserFlow(domain, userName);
    } catch (WorkflowException e) {
        // Sending e.getMessage() since it is required to give error message to end user.
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #22
Source File: UserProfileAdmin.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public boolean isAddProfileEnabledForDomain(String domain) throws UserProfileException {

        org.wso2.carbon.user.core.UserStoreManager userStoreManager = null;
        org.wso2.carbon.user.core.UserRealm realm = getUserRealm();
        boolean isAddProfileEnabled = false;

        try {
            if (StringUtils.isBlank(domain) || StringUtils.equals(domain, UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME)) {
                userStoreManager = realm.getUserStoreManager();
            } else {
                userStoreManager = realm.getUserStoreManager().getSecondaryUserStoreManager(domain);
            }

        } catch (UserStoreException e) {
            String errorMessage = "Error in obtaining SecondaryUserStoreManager.";
            log.error(errorMessage, e);
            throw new UserProfileException(errorMessage, e);
        }

        if (userStoreManager != null) {
            isAddProfileEnabled = userStoreManager.isMultipleProfilesAllowed();
        }

        return isAddProfileEnabled;
    }
 
Example #23
Source File: UserIdentityManagementUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all user claims
 *
 * @param userName
 * @return
 * @throws IdentityMgtServiceException
 */
public static UserIdentityClaimDTO[] getAllUserIdentityClaims(String userName)
        throws IdentityMgtServiceException {
    int tenantId = 0;
    try {
        tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        UserStoreManager userStoreManager =
                IdentityMgtServiceComponent.getRealmService()
                        .getTenantUserRealm(tenantId)
                        .getUserStoreManager();
        // read all claims and convert them to UserIdentityClaimDTO
        Claim[] claims = userStoreManager.getUserClaimValues(userName, null);
        List<UserIdentityClaimDTO> allDefaultClaims = new ArrayList<UserIdentityClaimDTO>();
        for (Claim claim : claims) {
            if (claim.getClaimUri().contains(UserCoreConstants.DEFAULT_CARBON_DIALECT)) {
                UserIdentityClaimDTO claimDTO = new UserIdentityClaimDTO();
                claimDTO.setClaimUri(claim.getClaimUri());
                claimDTO.setClaimValue(claim.getValue());
                allDefaultClaims.add(claimDTO);
            }
        }
        UserIdentityClaimDTO[] claimDTOs = new UserIdentityClaimDTO[allDefaultClaims.size()];
        return allDefaultClaims.toArray(claimDTOs);
    } catch (UserStoreException e) {
        throw new IdentityMgtServiceException("Error while getting user identity claims", e);
    }
}
 
Example #24
Source File: UserInformationRecoveryService.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * This returns the user supported claims.
 *
 * @param dialect
 * @return
 * @throws IdentityException
 */
public UserIdentityClaimDTO[] getUserIdentitySupportedClaims(String dialect)
        throws IdentityException {
    IdentityClaimManager claimManager = null;
    Claim[] claims = null;
    UserRealm realm = null;

    claimManager = IdentityClaimManager.getInstance();
    realm = IdentityTenantUtil.getRealm(null, null);
    claims = claimManager.getAllSupportedClaims(dialect, realm);

    if (claims == null || claims.length == 0) {
        log.warn("Could not find any matching claims for requested dialect : " + dialect);
        return new UserIdentityClaimDTO[0];
    }

    List<UserIdentityClaimDTO> claimList = new ArrayList<UserIdentityClaimDTO>();

    for (int i = 0; i < claims.length; i++) {
        if (claims[i].getDisplayTag() != null
                && !IdentityConstants.PPID_DISPLAY_VALUE.equals(claims[i].getDisplayTag())) {
            if (UserCoreConstants.ClaimTypeURIs.ACCOUNT_STATUS.equals(claims[i].getClaimUri())) {
                continue;
            }
            if (claims[i].isSupportedByDefault() && (!claims[i].isReadOnly())) {

                UserIdentityClaimDTO claimDto = new UserIdentityClaimDTO();
                claimDto.setClaimUri(claims[i].getClaimUri());
                claimDto.setClaimValue(claims[i].getValue());
                claimDto.setRequired(claims[i].isRequired());
                claimDto.setDisplayName(claims[i].getDisplayTag());
                claimList.add(claimDto);
            }
        }
    }

    return claimList.toArray(new UserIdentityClaimDTO[claimList.size()]);
}
 
Example #25
Source File: UserIdentityManagementUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Enable the user account
 *
 * @param userName
 * @param userStoreManager
 * @throws IdentityException
 */
public static void enableUserAccount(String userName, UserStoreManager userStoreManager)
        throws IdentityException {

    if (!isIdentityMgtListenerEnable()) {
        throw IdentityException.error("Cannot enable account, IdentityMgtEventListener is not enabled.");
    }

    String domainName = ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).getRealmConfiguration().
            getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
    userName = UserCoreUtil.addDomainToName(userName, domainName);

    try {
        if (!userStoreManager.isExistingUser(userName)) {
            log.error("User " + userName + " does not exist in tenant " + userStoreManager.getTenantId());
            throw IdentityException.error("No user account found for user " + userName + "to enable");
        }
    } catch (UserStoreException e) {
        log.error("Error while reading user identity data", e);
        throw IdentityException.error("Error while enabling user account " + userName);

    }

    UserIdentityDataStore store = IdentityMgtConfig.getInstance().getIdentityDataStore();
    UserIdentityClaimsDO userIdentityDO = store.load(UserCoreUtil.removeDomainFromName(userName), userStoreManager);
    if (userIdentityDO != null) {
        userIdentityDO.setAccountDisabled(false);
        store.store(userIdentityDO, userStoreManager);
    } else {
        throw IdentityException.error("No user account found for user " + userName);
    }

}
 
Example #26
Source File: DefaultAttributeFinder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public Set<String> getSupportedAttributes() {
    try {
        ClaimManager claimManager = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getClaimManager();
        ClaimMapping[] claims = claimManager
                .getAllClaimMappings(UserCoreConstants.DEFAULT_CARBON_DIALECT);
        for (ClaimMapping claim : claims) {
            supportedAttrs.add(claim.getClaim().getClaimUri());
        }
    } catch (Exception e) {
        //ignore
    }
    return supportedAttrs;
}
 
Example #27
Source File: Utils.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public static String getUserStoreDomainName(String userName) {
    int index;
    String userDomain;
    if ((index = userName.indexOf(CarbonConstants.DOMAIN_SEPARATOR)) >= 0) {
        // remove domain name if exist
        userDomain = userName.substring(0, index);
    } else {
        userDomain = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME;
    }
    return userDomain;
}
 
Example #28
Source File: UserStoreConfigAdminService.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void validateDomain(String domain, Boolean isDisable) throws IdentityUserStoreMgtException {

        String currentAuthorizedUserName = CarbonContext.getThreadLocalCarbonContext().getUsername();
        int index = currentAuthorizedUserName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
        String currentUserDomain = null;
        if (index > 0) {
            currentUserDomain = currentAuthorizedUserName.substring(0, index);
        }

        if (currentUserDomain != null && currentUserDomain.equalsIgnoreCase(domain) && isDisable) {
            LOG.error("Error while disabling user store from a user who is in the same user store.");
            throw new IdentityUserStoreMgtException("Error while updating user store state.");
        }
    }
 
Example #29
Source File: UserStoreActionListener.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean doPreSetUserClaimValue(String userName, String claimURI, String claimValue, String profileName,
                                      UserStoreManager userStoreManager) throws UserStoreException {
    if (!isEnable() || isCalledViaIdentityMgtListners()) {
        return true;
    }

    Map<String, String> claims = new HashMap<>();
    claims.put(claimURI, claimValue);

    try {
        SetMultipleClaimsWFRequestHandler setMultipleClaimsWFRequestHandler = new SetMultipleClaimsWFRequestHandler();
        String domain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig
                                                                                              .PROPERTY_DOMAIN_NAME);

        int tenantId = userStoreManager.getTenantId() ;
        String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(currentUser);

        return setMultipleClaimsWFRequestHandler.startSetMultipleClaimsWorkflow(domain, userName, claims,
                                                                                profileName);

    } catch (WorkflowException e) {
        // Sending e.getMessage() since it is required to give error message to end user.
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #30
Source File: Utils.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * get email address from user store
 *
 * @param userName user name
 * @param tenantId tenant id
 * @return email address
 */
public static String getEmailAddressForUser(String userName, int tenantId) {

    String email = null;

    try {
        if (log.isDebugEnabled()) {
            log.debug("Retrieving email address from user profile.");
        }

        Tenant tenant = IdentityMgtServiceComponent.getRealmService().
                getTenantManager().getTenant(tenantId);
        if (tenant != null && tenant.getAdminName().equals(userName)) {
            email = tenant.getEmail();
        }

        if (email == null || email.trim().length() < 1) {
            email = getClaimFromUserStoreManager(userName, tenantId,
                    UserCoreConstants.ClaimTypeURIs.EMAIL_ADDRESS);
        }

        if ((email == null || email.trim().length() < 1) && MultitenantUtils.isEmailUserName()) {
            email = UserCoreUtil.removeDomainFromName(userName);
        }
    } catch (Exception e) {
        String msg = "Unable to retrieve an email address associated with the given user : " + userName;
        log.warn(msg, e);   // It is common to have users with no email address defined.
    }

    return email;
}