Search in sources :

Example 1 with DISPLAY

use of org.wso2.carbon.identity.openidconnect.model.Constants.DISPLAY in project carbon-identity-framework by wso2.

the class JsGraphBuilder method filterOptions.

/**
 * Filter out options in the step config to retain only the options provided in authentication options
 *
 * @param authenticationOptions Authentication options to keep
 * @param stepConfig            The step config to be modified
 */
protected void filterOptions(Map<String, Map<String, String>> authenticationOptions, StepConfig stepConfig) {
    Map<String, Set<String>> filteredOptions = new HashMap<>();
    authenticationOptions.forEach((id, option) -> {
        String idp = option.get(FrameworkConstants.JSAttributes.IDP);
        String authenticator = option.get(FrameworkConstants.JSAttributes.AUTHENTICATOR);
        if (StringUtils.isNotBlank(authenticator) && StringUtils.isBlank(idp)) {
            // If Idp is not set, but authenticator is set, idp is assumed as local
            idp = FrameworkConstants.LOCAL_IDP_NAME;
        }
        if (StringUtils.isNotBlank(idp)) {
            filteredOptions.putIfAbsent(idp, new HashSet<>());
            if (StringUtils.isNotBlank(authenticator)) {
                filteredOptions.get(idp).add(authenticator.toLowerCase());
            }
        }
    });
    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Set<String>> entry : filteredOptions.entrySet()) {
            sb.append('\n').append(entry.getKey()).append(" : ");
            sb.append(StringUtils.join(entry.getValue(), ","));
        }
        log.debug("Authenticator options: " + sb.toString());
    }
    Set<AuthenticatorConfig> authenticatorsToRemove = new HashSet<>();
    Map<String, AuthenticatorConfig> idpsToRemove = new HashMap<>();
    stepConfig.getAuthenticatorList().forEach(authenticatorConfig -> authenticatorConfig.getIdps().forEach((idpName, idp) -> {
        Set<String> authenticators = filteredOptions.get(idpName);
        boolean removeOption = false;
        if (authenticators == null) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Authentication options didn't include idp: %s. Hence excluding from " + "options list", idpName));
            }
            removeOption = true;
        } else if (!authenticators.isEmpty()) {
            // Both idp and authenticator present, but authenticator is given by display name due to the fact
            // that it is the one available at UI. Should translate the display name to actual name, and
            // keep/remove option
            removeOption = true;
            if (FrameworkConstants.LOCAL_IDP_NAME.equals(idpName)) {
                List<LocalAuthenticatorConfig> localAuthenticators = ApplicationAuthenticatorService.getInstance().getLocalAuthenticators();
                for (LocalAuthenticatorConfig localAuthenticatorConfig : localAuthenticators) {
                    if (authenticatorConfig.getName().equals(localAuthenticatorConfig.getName()) && authenticators.contains(localAuthenticatorConfig.getDisplayName().toLowerCase())) {
                        removeOption = false;
                        break;
                    }
                }
                if (log.isDebugEnabled()) {
                    if (removeOption) {
                        log.debug(String.format("Authenticator options don't match any entry for local" + "authenticator: %s. Hence removing the option", authenticatorConfig.getName()));
                    } else {
                        log.debug(String.format("Authenticator options contained a match for local " + "authenticator: %s. Hence keeping the option", authenticatorConfig.getName()));
                    }
                }
            } else {
                for (FederatedAuthenticatorConfig federatedAuthConfig : idp.getFederatedAuthenticatorConfigs()) {
                    if (authenticatorConfig.getName().equals(federatedAuthConfig.getName()) && authenticators.contains(federatedAuthConfig.getDisplayName().toLowerCase())) {
                        removeOption = false;
                        break;
                    }
                }
                if (log.isDebugEnabled()) {
                    if (removeOption) {
                        log.debug(String.format("Authenticator options don't match any entry for idp: %s, " + "authenticator: %s. Hence removing the option", idpName, authenticatorConfig.getName()));
                    } else {
                        log.debug(String.format("Authenticator options contained a match for idp: %s, " + "authenticator: %s. Hence keeping the option", idpName, authenticatorConfig.getName()));
                    }
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(String.format("No authenticator filters for idp %s, hence keeping it as an option", idpName));
            }
        }
        if (removeOption) {
            if (authenticatorConfig.getIdps().size() > 1) {
                idpsToRemove.put(idpName, authenticatorConfig);
            } else {
                authenticatorsToRemove.add(authenticatorConfig);
            }
        }
    }));
    if (stepConfig.getAuthenticatorList().size() > authenticatorsToRemove.size()) {
        idpsToRemove.forEach((idp, authenticatorConfig) -> {
            int index = stepConfig.getAuthenticatorList().indexOf(authenticatorConfig);
            stepConfig.getAuthenticatorList().get(index).getIdps().remove(idp);
            stepConfig.getAuthenticatorList().get(index).getIdpNames().remove(idp);
            if (log.isDebugEnabled()) {
                log.debug("Removed " + idp + " option from " + authenticatorConfig.getName() + " as it " + "doesn't match the provided authenticator options");
            }
        });
        // If all idps are removed from the authenticator the authenticator should be removed.
        stepConfig.getAuthenticatorList().forEach(authenticatorConfig -> {
            if (authenticatorConfig.getIdps().isEmpty()) {
                authenticatorsToRemove.add(authenticatorConfig);
            }
        });
        stepConfig.getAuthenticatorList().removeAll(authenticatorsToRemove);
        if (log.isDebugEnabled()) {
            log.debug("Removed " + authenticatorsToRemove.size() + " options which doesn't match the " + "provided authenticator options");
        }
    } else {
        log.warn("The filtered authenticator list is empty, hence proceeding without filtering");
    }
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) Bindings(javax.script.Bindings) AuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext) FrameworkConstants(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants) HashMap(java.util.HashMap) Function(java.util.function.Function) HashSet(java.util.HashSet) AuthenticationDecisionEvaluator(org.wso2.carbon.identity.application.authentication.framework.AuthenticationDecisionEvaluator) JSObject(jdk.nashorn.api.scripting.JSObject) Map(java.util.Map) JsFunctionRegistry(org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry) BiConsumer(java.util.function.BiConsumer) ScriptException(javax.script.ScriptException) FrameworkServiceComponent(org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceComponent) Compilable(javax.script.Compilable) MapUtils(org.apache.commons.collections.MapUtils) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) ApplicationAuthenticatorService(org.wso2.carbon.identity.application.common.ApplicationAuthenticatorService) AsyncProcess(org.wso2.carbon.identity.application.authentication.framework.AsyncProcess) Set(java.util.Set) AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) UUID(java.util.UUID) FunctionLibrary(org.wso2.carbon.identity.functions.library.mgt.model.FunctionLibrary) FederatedAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig) Collectors(java.util.stream.Collectors) ScriptContext(javax.script.ScriptContext) Serializable(java.io.Serializable) FunctionLibraryManagementService(org.wso2.carbon.identity.functions.library.mgt.FunctionLibraryManagementService) List(java.util.List) Invocable(javax.script.Invocable) FrameworkServiceDataHolder(org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceDataHolder) CarbonContext(org.wso2.carbon.context.CarbonContext) CompiledScript(javax.script.CompiledScript) ScriptEngine(javax.script.ScriptEngine) Log(org.apache.commons.logging.Log) FunctionLibraryManagementException(org.wso2.carbon.identity.functions.library.mgt.exception.FunctionLibraryManagementException) ScriptObjectMirror(jdk.nashorn.api.scripting.ScriptObjectMirror) LogFactory(org.apache.commons.logging.LogFactory) JsAuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext) FrameworkUtils(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils) LocalAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig) Collections(java.util.Collections) AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) FederatedAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig) LocalAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) FederatedAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig) LocalAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 2 with DISPLAY

use of org.wso2.carbon.identity.openidconnect.model.Constants.DISPLAY in project carbon-identity-framework by wso2.

the class UserRealmProxy method getUsersOfRole.

public FlaggedName[] getUsersOfRole(String roleName, String filter, int limit) throws UserAdminException {
    try {
        int index = roleName != null ? roleName.indexOf(CarbonConstants.DOMAIN_SEPARATOR) : -1;
        boolean domainProvided = index > 0;
        String domain = domainProvided ? roleName.substring(0, index) : null;
        if (domain != null && filter != null && !filter.toLowerCase().startsWith(domain.toLowerCase()) && !(UserCoreConstants.INTERNAL_DOMAIN.equalsIgnoreCase(domain) || UserMgtConstants.APPLICATION_DOMAIN.equalsIgnoreCase(domain))) {
            filter = domain + CarbonConstants.DOMAIN_SEPARATOR + filter;
        }
        UserStoreManager usMan = realm.getUserStoreManager();
        String[] usersOfRole;
        boolean canLimitAndFilterUsersFromUMLevel = canLimitAndFilterUsersFromUMLevel(roleName, usMan);
        if (domain == null && limit != 0) {
            if (filter != null) {
                filter = CarbonConstants.DOMAIN_SEPARATOR + filter;
            } else {
                filter = "/*";
            }
        }
        /*
            With the fix delivered for https://github.com/wso2/product-is/issues/6511, limiting and filtering from
            the JDBC UserStoreManager is possible thus making the in-memory filtering and limiting logic in here
            irrelevant for JDBC UM. But still, Read Only LDAP UM does not supports DB level limiting and filtering
            (refer to https://github.com/wso2/product-is/issues/6573) thus the logic is kept as it is.
             */
        if (canLimitAndFilterUsersFromUMLevel) {
            int userCountLimit = getUserCountLimit(limit);
            String domainFreeFilter = getDomainFreeFilter(filter);
            AbstractUserStoreManager abstractUsMan = (AbstractUserStoreManager) usMan;
            usersOfRole = abstractUsMan.getUserListOfRole(roleName, domainFreeFilter, userCountLimit);
        } else {
            usersOfRole = usMan.getUserListOfRole(roleName);
        }
        Arrays.sort(usersOfRole);
        Map<String, Integer> userCount = new HashMap<String, Integer>();
        if (limit == 0) {
            filter = filter.replace("*", ".*");
            Pattern pattern = Pattern.compile(filter, Pattern.CASE_INSENSITIVE);
            List<FlaggedName> flaggedNames = new ArrayList<FlaggedName>();
            for (String anUsersOfRole : usersOfRole) {
                // check if display name is present in the user name
                int combinerIndex = anUsersOfRole.indexOf(UserCoreConstants.NAME_COMBINER);
                Matcher matcher;
                if (combinerIndex > 0) {
                    matcher = pattern.matcher(anUsersOfRole.substring(combinerIndex + UserCoreConstants.NAME_COMBINER.length()));
                } else {
                    matcher = pattern.matcher(anUsersOfRole);
                }
                if (!matcher.matches()) {
                    continue;
                }
                FlaggedName fName = new FlaggedName();
                fName.setSelected(true);
                if (combinerIndex > 0) {
                    // if display name is appended
                    fName.setItemName(anUsersOfRole.substring(0, combinerIndex));
                    fName.setItemDisplayName(anUsersOfRole.substring(combinerIndex + UserCoreConstants.NAME_COMBINER.length()));
                } else {
                    // if only user name is present
                    fName.setItemName(anUsersOfRole);
                    fName.setItemDisplayName(anUsersOfRole);
                }
                if (domain != null && !(UserCoreConstants.INTERNAL_DOMAIN.equalsIgnoreCase(domain) || UserMgtConstants.APPLICATION_DOMAIN.equalsIgnoreCase(domain))) {
                    if (usMan.getSecondaryUserStoreManager(domain) != null && (usMan.getSecondaryUserStoreManager(domain).isReadOnly() || FALSE.equals(usMan.getSecondaryUserStoreManager(domain).getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.WRITE_GROUPS_ENABLED)))) {
                        fName.setEditable(false);
                    } else {
                        fName.setEditable(true);
                    }
                } else {
                    if (usMan.isReadOnly() || (usMan.getSecondaryUserStoreManager(domain) != null && FALSE.equals(usMan.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.WRITE_GROUPS_ENABLED)))) {
                        fName.setEditable(false);
                    } else {
                        fName.setEditable(true);
                    }
                }
                if (domain != null) {
                    if (userCount.containsKey(domain)) {
                        userCount.put(domain, userCount.get(domain) + 1);
                    } else {
                        userCount.put(domain, 1);
                    }
                } else {
                    if (userCount.containsKey(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME)) {
                        userCount.put(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME, userCount.get(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME) + 1);
                    } else {
                        userCount.put(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME, 1);
                    }
                }
                flaggedNames.add(fName);
            }
            String exceededDomains = "";
            boolean isPrimaryExceeding = false;
            Map<String, Integer> maxUserListCount = ((AbstractUserStoreManager) realm.getUserStoreManager()).getMaxListCount(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST);
            String[] domains = userCount.keySet().toArray(new String[userCount.keySet().size()]);
            for (int i = 0; i < domains.length; i++) {
                if (UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domains[i])) {
                    if (userCount.get(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME).equals(maxUserListCount.get(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME))) {
                        isPrimaryExceeding = true;
                    }
                    continue;
                }
                if (userCount.get(domains[i]).equals(maxUserListCount.get(domains[i].toUpperCase()))) {
                    exceededDomains += domains[i];
                    if (i != domains.length - 1) {
                        exceededDomains += ":";
                    }
                }
            }
            FlaggedName flaggedName = new FlaggedName();
            if (isPrimaryExceeding) {
                flaggedName.setItemName("true");
            } else {
                flaggedName.setItemName(FALSE);
            }
            flaggedName.setItemDisplayName(exceededDomains);
            flaggedNames.add(flaggedName);
            return flaggedNames.toArray(new FlaggedName[flaggedNames.size()]);
        }
        String[] userNames = usMan.listUsers(filter, limit);
        FlaggedName[] flaggedNames = new FlaggedName[userNames.length + 1];
        for (int i = 0; i < userNames.length; i++) {
            FlaggedName fName = new FlaggedName();
            fName.setItemName(userNames[i]);
            if (Arrays.binarySearch(usersOfRole, userNames[i]) > -1) {
                fName.setSelected(true);
            }
            // check if display name is present in the user name
            int combinerIndex = userNames[i].indexOf(UserCoreConstants.NAME_COMBINER);
            if (combinerIndex > 0) {
                // if display name is appended
                fName.setItemName(userNames[i].substring(0, combinerIndex));
                fName.setItemDisplayName(userNames[i].substring(combinerIndex + UserCoreConstants.NAME_COMBINER.length()));
            } else {
                // if only user name is present
                fName.setItemName(userNames[i]);
            }
            if (domain != null && !(UserCoreConstants.INTERNAL_DOMAIN.equalsIgnoreCase(domain) || UserMgtConstants.APPLICATION_DOMAIN.equalsIgnoreCase(domain))) {
                if (usMan.getSecondaryUserStoreManager(domain) != null && (usMan.getSecondaryUserStoreManager(domain).isReadOnly() || FALSE.equals(usMan.getSecondaryUserStoreManager(domain).getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.WRITE_GROUPS_ENABLED)))) {
                    fName.setEditable(false);
                } else {
                    fName.setEditable(true);
                }
            } else {
                if (usMan.isReadOnly() || (usMan.getSecondaryUserStoreManager(domain) != null && FALSE.equals(usMan.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.WRITE_GROUPS_ENABLED)))) {
                    fName.setEditable(false);
                } else {
                    fName.setEditable(true);
                }
            }
            if (domain != null) {
                if (userCount.containsKey(domain)) {
                    userCount.put(domain, userCount.get(domain) + 1);
                } else {
                    userCount.put(domain, 1);
                }
            } else {
                if (userCount.containsKey(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME)) {
                    userCount.put(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME, userCount.get(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME) + 1);
                } else {
                    userCount.put(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME, 1);
                }
            }
            flaggedNames[i] = fName;
        }
        String exceededDomains = "";
        boolean isPrimaryExceeding = false;
        Map<String, Integer> maxUserListCount = ((AbstractUserStoreManager) realm.getUserStoreManager()).getMaxListCount(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST);
        String[] domains = userCount.keySet().toArray(new String[userCount.keySet().size()]);
        for (int i = 0; i < domains.length; i++) {
            if (UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domains[i])) {
                if (userCount.get(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME).equals(maxUserListCount.get(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME))) {
                    isPrimaryExceeding = true;
                }
                continue;
            }
            if (userCount.get(domains[i]).equals(maxUserListCount.get(domains[i].toUpperCase()))) {
                exceededDomains += domains[i];
                if (i != domains.length - 1) {
                    exceededDomains += ":";
                }
            }
        }
        FlaggedName flaggedName = new FlaggedName();
        if (isPrimaryExceeding) {
            flaggedName.setItemName("true");
        } else {
            flaggedName.setItemName(FALSE);
        }
        flaggedName.setItemDisplayName(exceededDomains);
        flaggedNames[flaggedNames.length - 1] = flaggedName;
        return flaggedNames;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new UserAdminException(e.getMessage(), e);
    }
}
Also used : Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) FlaggedName(org.wso2.carbon.user.mgt.common.FlaggedName) ArrayList(java.util.ArrayList) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) JDBCUserStoreManager(org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager) UserAdminException(org.wso2.carbon.user.mgt.common.UserAdminException) UserAdminException(org.wso2.carbon.user.mgt.common.UserAdminException) RegistryException(org.wso2.carbon.registry.api.RegistryException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager)

Example 3 with DISPLAY

use of org.wso2.carbon.identity.openidconnect.model.Constants.DISPLAY in project carbon-identity-framework by wso2.

the class ConsentPurpose method build.

/**
 * Build ConsentPurpose from ConsentPurpose OM element.
 *
 * @param consentPurposeOM ConsentPurpose OM element.
 * @return ConsentPurpose object.
 */
public static ConsentPurpose build(OMElement consentPurposeOM) throws IdentityApplicationManagementException {
    ConsentPurpose consentPurpose = new ConsentPurpose();
    if (consentPurposeOM == null) {
        return consentPurpose;
    }
    Iterator<?> children = consentPurposeOM.getChildElements();
    while (children.hasNext()) {
        OMElement member = (OMElement) children.next();
        if (PURPOSE_ID_ELEM.equals(member.getLocalName())) {
            try {
                consentPurpose.setPurposeId(Integer.parseInt(member.getText()));
            } catch (NumberFormatException e) {
                log.warn("PurposeID should be an Integer. Found: " + member.getText() + " instead.");
                throw new IdentityApplicationManagementException("Invalid purpose ID: " + member.getText(), e);
            }
        } else {
            if (DISPLAY_ORDER_ELEM.equals(member.getLocalName())) {
                try {
                    consentPurpose.setDisplayOrder(Integer.parseInt(member.getText()));
                } catch (NumberFormatException e) {
                    log.warn("DisplayOrder should be an Integer. Found: " + member.getText() + " instead. Setting " + "default display order: " + DEFAULT_DISPLAY_ORDER);
                    consentPurpose.setDisplayOrder(DEFAULT_DISPLAY_ORDER);
                }
            }
        }
    }
    return consentPurpose;
}
Also used : IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OMElement(org.apache.axiom.om.OMElement)

Example 4 with DISPLAY

use of org.wso2.carbon.identity.openidconnect.model.Constants.DISPLAY in project carbon-identity-framework by wso2.

the class PostAuthnMissingClaimHandlerTest method testCorrectDisplayNamesDeriveForMissingClaims.

@SuppressWarnings("checkstyle:LocalVariableName")
@Test(description = "This test case tests the related display names for mandatory missing claims are derived")
public void testCorrectDisplayNamesDeriveForMissingClaims() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
    List<AttributeMapping> mappedAttributes = new ArrayList<>();
    Map<String, String> localClaimProperties = new HashMap<>();
    localClaimProperties.put("Description", "Local");
    localClaimProperties.put("DisplayName", "Local");
    Map<String, String> localityClaimProperties = new HashMap<>();
    localityClaimProperties.put("Description", "Locality");
    localityClaimProperties.put("DisplayName", "Locality");
    Map<String, String> secretKeyClaimProperties = new HashMap<>();
    secretKeyClaimProperties.put("Description", "Claim to store the secret key");
    secretKeyClaimProperties.put("DisplayName", "Secret Key");
    Map<String, String> countryClaimProperties = new HashMap<>();
    countryClaimProperties.put("Description", "Country");
    countryClaimProperties.put("DisplayName", "Country");
    Map<String, String> verifyEmailClaimProperties = new HashMap<>();
    verifyEmailClaimProperties.put("Description", "Temporary claim to invoke email verified feature");
    verifyEmailClaimProperties.put("DisplayName", "Verify Email");
    List<LocalClaim> localClaims = new ArrayList<>();
    LocalClaim localClaim = new LocalClaim("http://wso2.org/claims/local", mappedAttributes, localClaimProperties);
    LocalClaim localClaim2 = new LocalClaim("http://wso2.org/claims/locality", mappedAttributes, localityClaimProperties);
    LocalClaim localClaim3 = new LocalClaim("http://wso2.org/claims/identity/secretkey", mappedAttributes, secretKeyClaimProperties);
    LocalClaim localClaim4 = new LocalClaim("http://wso2.org/claims/country", mappedAttributes, countryClaimProperties);
    LocalClaim localClaim5 = new LocalClaim("http://wso2.org/claims/identity/verifyEmail", mappedAttributes, verifyEmailClaimProperties);
    localClaims.add(localClaim);
    localClaims.add(localClaim2);
    localClaims.add(localClaim3);
    localClaims.add(localClaim4);
    localClaims.add(localClaim5);
    Map<String, String> missingClaimMap = new HashMap<>();
    missingClaimMap.put("http://wso2.org/claims/local", "http://wso2.org/claims/local");
    missingClaimMap.put("http://wso2.org/claims/country", "http://wso2.org/claims/country");
    missingClaimMap.put("http://wso2.org/claims/locality", "http://wso2.org/claims/locality");
    String relatedDisplayNames = "http://wso2.org/claims/local|Local,http://wso2.org/claims/country|Country," + "http://wso2.org/claims/locality|Locality";
    Class<PostAuthnMissingClaimHandler> claimDisplay = PostAuthnMissingClaimHandler.class;
    Object obj = claimDisplay.newInstance();
    Method displayName = claimDisplay.getDeclaredMethod("getMissingClaimsDisplayNames", Map.class, List.class);
    displayName.setAccessible(true);
    String returnedDisplayNames = (String) displayName.invoke(obj, missingClaimMap, localClaims);
    assertEquals(returnedDisplayNames, relatedDisplayNames);
}
Also used : HashMap(java.util.HashMap) AttributeMapping(org.wso2.carbon.identity.claim.metadata.mgt.model.AttributeMapping) ArrayList(java.util.ArrayList) LocalClaim(org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim) Method(java.lang.reflect.Method) Test(org.testng.annotations.Test)

Example 5 with DISPLAY

use of org.wso2.carbon.identity.openidconnect.model.Constants.DISPLAY in project product-is by wso2.

the class SCIM2GroupTest method testGetGroupsAfterRemovingHybridRoleOfAMember.

@Test(dependsOnMethods = "testGETGroupDetails", description = "Test whether the assigned user list of a hybrid " + "role created by a Service Provider is updated properly when a secondary user store is disabled/deleted " + "where one of the users in the respective secondary user store was assigned to the respective hybrid role.")
public void testGetGroupsAfterRemovingHybridRoleOfAMember() throws Exception {
    ApplicationManagementServiceClient applicationManagementServiceClient = new ApplicationManagementServiceClient(sessionCookie, backendURL, ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null));
    ServiceProvider serviceProviderApp = new ServiceProvider();
    serviceProviderApp.setApplicationName(APPLICATION_NAME);
    serviceProviderApp.setDescription("sample-description");
    serviceProviderApp.setSaasApp(true);
    applicationManagementServiceClient.createApplication(serviceProviderApp);
    serviceProviderApp = applicationManagementServiceClient.getApplication(APPLICATION_NAME);
    Assert.assertEquals(serviceProviderApp.getApplicationName(), APPLICATION_NAME, "Failed to create the Service Provider: " + APPLICATION_NAME);
    UserManagementClient userMgtClient = new UserManagementClient(backendURL, getSessionCookie());
    userMgtClient.addUser(USERNAME_OF_THE_NEW_USER, "newUserPassword", new String[] { APPLICATION_ROLE_NAME }, null);
    endpointURL = GROUPS_ENDPOINT;
    ExtractableResponse scimResponse = getResponseOfGet(endpointURL, SCIM_CONTENT_TYPE).then().assertThat().statusCode(HttpStatus.SC_OK).and().assertThat().header(HttpHeaders.CONTENT_TYPE, SCIM_CONTENT_TYPE).log().ifValidationFails().extract();
    Assert.assertNotNull(scimResponse);
    Object resourcesAttribute = scimResponse.path("Resources");
    Assert.assertTrue(resourcesAttribute instanceof ArrayList, "'Resources' attribute is not a list of " + "objects");
    Optional<LinkedHashMap> targetSpApplicationRole = ((ArrayList<LinkedHashMap>) resourcesAttribute).stream().filter(resource -> ((String) resource.get("displayName")).contains(APPLICATION_ROLE_NAME)).findFirst();
    Assert.assertTrue(targetSpApplicationRole.isPresent(), "Application role not found for the " + "Service Provider: " + APPLICATION_NAME);
    groupId = (String) targetSpApplicationRole.get().get("id");
    Optional<LinkedHashMap> targetMemberAttribute = ((ArrayList<LinkedHashMap>) targetSpApplicationRole.get().get("members")).stream().filter(member -> StringUtils.equals((String) member.get("display"), USERNAME_OF_THE_NEW_USER)).findFirst();
    Assert.assertTrue(targetMemberAttribute.isPresent(), "User: " + USERNAME_OF_THE_NEW_USER + " is not " + "assigned to the role: " + APPLICATION_ROLE_NAME);
    String targetUserId = (String) targetMemberAttribute.get().get("value");
    UserStoreConfigAdminServiceClient userStoreConfigAdminServiceClient = new UserStoreConfigAdminServiceClient(backendURL, sessionCookie);
    userStoreConfigAdminServiceClient.changeUserStoreState(USER_STORE_DOMAIN, true);
    Thread.sleep(20000);
    endpointURL += "/" + groupId;
    scimResponse = getResponseOfGet(endpointURL, SCIM_CONTENT_TYPE).then().assertThat().statusCode(HttpStatus.SC_OK).and().assertThat().header(HttpHeaders.CONTENT_TYPE, SCIM_CONTENT_TYPE).log().ifValidationFails().extract();
    Assert.assertNotNull(scimResponse);
    Object membersAttribute = scimResponse.path("members");
    Assert.assertTrue(membersAttribute instanceof ArrayList, "'members' attribute is not a list of " + "objects");
    targetMemberAttribute = ((ArrayList<LinkedHashMap>) membersAttribute).stream().filter(member -> StringUtils.equals((String) member.get("value"), targetUserId)).findAny();
    Assert.assertFalse(targetMemberAttribute.isPresent(), "User: " + USERNAME_OF_THE_NEW_USER + " of the disabled user store: " + USER_STORE_DOMAIN + " is assigned to the  application role: " + APPLICATION_ROLE_NAME);
    if (ISTestUtils.nameExists(userMgtClient.listAllUsers(USERNAME_OF_THE_NEW_USER, 10), USERNAME_OF_THE_NEW_USER)) {
        userMgtClient.deleteUser(USERNAME_OF_THE_NEW_USER);
    }
    userStoreConfigAdminServiceClient.changeUserStoreState(USER_STORE_DOMAIN, false);
    Thread.sleep(20000);
}
Also used : ConfigurationContextFactory(org.apache.axis2.context.ConfigurationContextFactory) IntStream(java.util.stream.IntStream) StringUtils(org.apache.commons.lang.StringUtils) UserStoreConfigAdminServiceClient(org.wso2.identity.integration.common.clients.user.store.config.UserStoreConfigAdminServiceClient) GROUPS_ENDPOINT(org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.GROUPS_ENDPOINT) DataProvider(org.testng.annotations.DataProvider) HttpStatus(org.apache.http.HttpStatus) Test(org.testng.annotations.Test) ISTestUtils(org.wso2.identity.integration.test.utils.ISTestUtils) H2DataBaseManager(org.wso2.carbon.automation.test.utils.dbutils.H2DataBaseManager) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) SQLException(java.sql.SQLException) Assert(org.testng.Assert) ServerConfigurationManager(org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager) UserManagementClient(org.wso2.identity.integration.common.clients.UserManagementClient) HttpHeaders(org.apache.http.HttpHeaders) ServiceProvider(org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider) AfterClass(org.testng.annotations.AfterClass) Factory(org.testng.annotations.Factory) PERMISSIONS_ENDPOINT(org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.PERMISSIONS_ENDPOINT) BeforeClass(org.testng.annotations.BeforeClass) BeforeMethod(org.testng.annotations.BeforeMethod) TestUserMode(org.wso2.carbon.automation.engine.context.TestUserMode) IOException(java.io.IOException) PropertyDTO(org.wso2.carbon.identity.user.store.configuration.stub.dto.PropertyDTO) File(java.io.File) ExtractableResponse(io.restassured.response.ExtractableResponse) Response(io.restassured.response.Response) ApplicationManagementServiceClient(org.wso2.identity.integration.common.clients.application.mgt.ApplicationManagementServiceClient) IsNull.notNullValue(org.hamcrest.core.IsNull.notNullValue) Optional(java.util.Optional) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) RestAssured(io.restassured.RestAssured) ServiceProvider(org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider) ExtractableResponse(io.restassured.response.ExtractableResponse) ApplicationManagementServiceClient(org.wso2.identity.integration.common.clients.application.mgt.ApplicationManagementServiceClient) ArrayList(java.util.ArrayList) UserManagementClient(org.wso2.identity.integration.common.clients.UserManagementClient) UserStoreConfigAdminServiceClient(org.wso2.identity.integration.common.clients.user.store.config.UserStoreConfigAdminServiceClient) LinkedHashMap(java.util.LinkedHashMap) Test(org.testng.annotations.Test)

Aggregations

ArrayList (java.util.ArrayList)17 ComplexAttribute (org.wso2.charon3.core.attributes.ComplexAttribute)13 SimpleAttribute (org.wso2.charon3.core.attributes.SimpleAttribute)13 HashMap (java.util.HashMap)12 Test (org.testng.annotations.Test)9 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)9 MultiValuedAttribute (org.wso2.charon3.core.attributes.MultiValuedAttribute)9 Map (java.util.Map)8 Attribute (org.wso2.charon3.core.attributes.Attribute)7 OMElement (org.apache.axiom.om.OMElement)4 User (org.wso2.charon3.core.objects.User)4 Response (feign.Response)3 HashSet (java.util.HashSet)3 Iterator (java.util.Iterator)3 List (java.util.List)3 Properties (java.util.Properties)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 JSONObject (org.json.JSONObject)3 UserStoreException (org.wso2.carbon.user.core.UserStoreException)3 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)3