Package org.wso2.carbon.user.core

Examples of org.wso2.carbon.user.core.UserStoreException


            value = realmConfig.getAuthorizationManagerClass();
            if (value == null) {
                String message = "System cannot continue. Authorization writer is null";
                log.error(message);
                throw new UserStoreException(message);
            }
            this.authzManager = (AuthorizationManager) createObjectWithOptions(value);

        } catch (UserStoreException e) {
            // all user store exceptions are logged at the place it is created.
            throw e;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new UserStoreException(e.getMessage(), e);
        }

    }
View Full Code Here


                return newObject;
            } catch (NoSuchMethodException e) {
                // cannot initialize in any of the methods. Throw exception.
                String message = "Cannot initialize " + className + ". Error " + e.getMessage();
                log.error(message);
                throw new UserStoreException(message);
            }

        } catch (Throwable e) {
            log.error("Cannot create " + className + " . Error is : " + e.getMessage(), e);
            throw new UserStoreException(e.getMessage() + "Type " + e.getClass(), e);
        }

    }
View Full Code Here

            Map<String, ClaimMapping> claimMapping = claimBuilder
                    .buildClaimMappingsFromConfigFile();
            return claimMapping;
        } catch (ClaimBuilderException e) {
            log.error(e.getMessage(), e);
            throw new UserStoreException(e.getMessage(), e);
        }
    }
View Full Code Here

            Map<String, ProfileConfiguration> profileConfig = profilBuilder
                    .buildProfileConfigurationFromConfigFile();
            return profileConfig;
        } catch (ProfileBuilderException e) {
            log.error(e.getMessage(), e);
            throw new UserStoreException(e.getMessage(), e);
        }
    }
View Full Code Here

            try {
                claimMappings.putAll(claimBuilder.buildClaimMappingsFromConfigFile());
            } catch (ClaimBuilderException e) {
                String msg = "Error in building claims.";
                log.error(msg);
                throw new UserStoreException(msg, e);
            }
            claimDAO.addCliamMappings(claimMappings.values().toArray(
                    new ClaimMapping[claimMappings.size()]));
            try {
                profileConfigs.putAll(profileBilder.buildProfileConfigurationFromConfigFile());
            } catch (ProfileBuilderException e) {
                String msg = "Error in building the profile.";
                log.error(msg);
                throw new UserStoreException(msg, e);
            }
            profileDAO.addProfileConfig(profileConfigs.values().toArray(
                    new ProfileConfiguration[profileConfigs.size()]));
        } else {
            try {
                claimMappings.putAll(claimBuilder.buildClaimMappingsFromDatabase(dataSource,
                        UserCoreConstants.INTERNAL_USERSTORE));
            } catch (ClaimBuilderException e) {
                String msg = "Error in building claims.";
                log.error(msg);
                throw new UserStoreException(msg, e);
            }
            try {
                profileConfigs.putAll(profileBilder.buildProfileConfigurationFromDatabase(dataSource,
                        UserCoreConstants.INTERNAL_USERSTORE));
            } catch (ProfileBuilderException e) {
                String msg = "Error in building the profile.";
                log.error(msg);
                throw new UserStoreException(msg, e);
            }
        }
    }
View Full Code Here

    public void addUser(String userName, Object credential, String[] roleList,
                        Map<String, String> claims, String profileName,
                        boolean requirePasswordChange) throws UserStoreException {

        if (!checkUserNameValid(userName)) {
            throw new UserStoreException(
                    "User name not valid. User name must be a non null string with following format, " +
                    realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_USER_NAME_JAVA_REG_EX));

        }

        if (!checkUserPasswordValid(credential)) {
            throw new UserStoreException(
                    "Credential not valid. Credential must be a non null string with following format, " +
                    realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_JAVA_REG_EX));

        }

        DirContext mainDirContext = this.connectionSource.getContext();
        DirContext dirContext = null;
        String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
        try {

            dirContext = (DirContext) mainDirContext.lookup(searchBase);
            //above this the search base or base directory for this storage. we assume users
            // are stored under ou=users folder here

            BasicAttributes basicAttributes = new BasicAttributes(true);
            //read the object class for saving user entries in LDAP.
            String userObjectClass = realmConfig.getUserStoreProperty(
                    LDAPConstants.USER_ENTRY_OBJECT_CLASS);
            // set the objectClass type for schema
            BasicAttribute objectClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
            objectClass.add(userObjectClass);

            //If KDC is enabled we have to set KDC specific object classes also
            if (isKdcEnabled()) {
                // Add Kerberos specific object classes
                objectClass.add("krb5principal");
                objectClass.add("krb5kdcentry");
                objectClass.add("subschema");
            }

            basicAttributes.put(objectClass);

            BasicAttribute uid = new BasicAttribute("uid");
            uid.add(userName);
            basicAttributes.put(uid);

            if (isKdcEnabled()) {
                String principal = userName + "@" + this.getRealmName();

                BasicAttribute principalAttribute = new BasicAttribute(KRB5_PRINCIPAL_NAME_ATTRIBUTE);
                principalAttribute.add(principal);
                basicAttributes.put(principalAttribute);

                BasicAttribute versionNumberAttribute = new BasicAttribute(KRB5_KEY_VERSION_NUMBER_ATTRIBUTE);
                versionNumberAttribute.add("0");
                basicAttributes.put(versionNumberAttribute);
            }

            BasicAttribute userPassword = new BasicAttribute("userPassword");
            userPassword.add(getPasswordToStore((String) credential,
                                                this.realmConfig.getUserStoreProperty(
                                                        PASSWORD_HASH_METHOD)));
            basicAttributes.put(userPassword);

            BasicAttribute claim;

            /*we keep boolean values to know whether compulsory attributes 'sn' and 'cn' are set
            during setting claims.*/
            boolean isSNExists = false;
            boolean isCNExists = false;

            for (Map.Entry<String, String> entry : claims.entrySet()) {
                /*LDAP does not allow for empty values. If an attribute has a value it’s stored
                 with the entry, otherwise it is not. Hence needs to check for empty values before
                 storing the attribute.*/
                if (EMPTY_ATTRIBUTE_STRING.equals(entry.getValue())) {
                    continue;
                }
                //needs to get attribute name from claim mapping
                String claimURI = entry.getKey();
                ClaimMapping claimMapping = null;
                claimMapping = (ClaimMapping) claimManager.getClaimMapping(claimURI);

                String attributeName = null;
                if (claimMapping != null) {
                    attributeName = claimMapping.getMappedAttribute();
                    if (ATTR_NAME_CN.equals(attributeName)) {
                        isCNExists = true;
                    } else if (ATTR_NAME_SN.equals(attributeName)) {
                        isSNExists = true;
                    }
                } else {
                    attributeName = claimURI;
                }
                claim = new BasicAttribute(attributeName);
                claim.add(claims.get(entry.getKey()));
                basicAttributes.put(claim);
            }
            //following attribute is not added to attributes. May be it could be removed.
            BasicAttribute isChangePassword = new BasicAttribute("requirePasswordChange");
            isChangePassword.add(requirePasswordChange);

            // If required attributes cn, sn are not set during claim mapping, set them as user names

            if (!isCNExists) {
                BasicAttribute cn = new BasicAttribute("cn");
                cn.add(userName);
                basicAttributes.put(cn);
            }

            if (!isSNExists) {
                BasicAttribute sn = new BasicAttribute("sn");
                sn.add(userName);
                basicAttributes.put(sn);
            }

            dirContext.bind("uid=" + userName, null, basicAttributes);

            if ((roleList != null) || (roleList.length != 0)) {
                //add user to role according to the group configuration in user-mgt.xml
                for (String role : roleList) {
                    if (("true".equals(READ_LDAP_USER_GROUPS)) &&
                        ("true".equals(WRITE_LDAP_USER_GROUPS))) {
                        if (!isInternalRole(role)) {
                            this.updateRoleListOfUser(userName, new String[]{}, new String[]{role});
                        } else if (isInternalRole(role)) {
                            this.hybridRoleManager.addHybridRole(role, new String[]{userName});
                        }
                    }
                    if (("false".equals(READ_LDAP_USER_GROUPS)) &&
                        ("false".equals(WRITE_LDAP_USER_GROUPS))
                        || (("true".equals(READ_LDAP_USER_GROUPS)) &&
                            ("false".equals(WRITE_LDAP_USER_GROUPS)))) {
                        this.hybridRoleManager.addHybridRole(role, new String[]{userName});
                    }
                }
            }

        } catch (NamingException e) {
            String errorMessage = "Can not access the directory context or" +
                                  "user already exists in the system";
            logger.error(errorMessage, e);
            throw new UserStoreException(errorMessage, e);
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            String errorMessage = "Error in obtaining claim mapping.";
            logger.error(errorMessage, e);
            throw new UserStoreException(errorMessage, e);
        } finally {
            JNDIUtil.closeContext(dirContext);
            JNDIUtil.closeContext(mainDirContext);
        }
    }
View Full Code Here

            try {
                MessageDigest messageDigest = MessageDigest.getInstance(passwordHashMethod);
                byte[] digestValue = messageDigest.digest(password.getBytes());
                passwordToStore = "{" + passwordHashMethod + "}" + Base64.encode(digestValue);
            } catch (NoSuchAlgorithmException e) {
                throw new UserStoreException("Invalid hashMethod", e);
            }
        }
        return passwordToStore;
    }
View Full Code Here

    }

    public void deleteUser(String userName) throws UserStoreException {

        if (realmConfig.getAdminUserName().equals(userName)) {
            throw new UserStoreException("Cannot delete admin user");
        }

        if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equals(userName)) {
            throw new UserStoreException("Cannot delete anonymous user");
        }

        if (("false".equals(READ_LDAP_USER_GROUPS)) && ("false".equals(WRITE_LDAP_USER_GROUPS))
            || (("true".equals(READ_LDAP_USER_GROUPS)) &&
                ("false".equals(WRITE_LDAP_USER_GROUPS)))) {
            if (this.hybridRoleManager != null) {
                this.hybridRoleManager.deleteUser(userName);
            }
        }
        //delete user from LDAP group if read-write enabled.
        String userNameAttribute = realmConfig.getUserStoreProperty(
                LDAPConstants.USER_NAME_ATTRIBUTE_NAME);
        String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_FILTER);
        searchFilter = searchFilter.replace("?", userName);
        String[] returningUserAttributes = new String[]{userNameAttribute};

        DirContext mainDirContext = this.connectionSource.getContext();

        NamingEnumeration<SearchResult> userResults = searchInUserBase(
                searchFilter, returningUserAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext);
        NamingEnumeration<SearchResult> groupResults = null;

        DirContext subDirContext = null;
        try {
            SearchResult userResult = null;
            String userDN = null;
            // here we assume only one user
            // TODO: what to do if there are more than one user
            while (userResults.hasMore()) {
                userResult = userResults.next();
                userDN = userResult.getName();
            }

            if (("true".equals(READ_LDAP_USER_GROUPS)) &&
                ("true".equals(WRITE_LDAP_USER_GROUPS))) {
                String[] rolesOfUser = getRoleListOfUser(userName);

                if (rolesOfUser.length != 0) {
                    String roleNameSearchFilter = realmConfig.getUserStoreProperty(
                            LDAPConstants.ROLE_NAME_FILTER);
                    String[] returningGroupAttributes = new String[]{
                            realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE)};
                    for (String role : rolesOfUser) {
                        if (!isInternalRole(role)) {
                            String groupSearchFilter = roleNameSearchFilter.replace("?", role);
                            groupResults = searchInGroupBase(
                                    groupSearchFilter, returningGroupAttributes,
                                    SearchControls.SUBTREE_SCOPE, mainDirContext);
                            SearchResult groupResult = null;
                            while (groupResults.hasMore()) {
                                groupResult = groupResults.next();
                            }
                            if ((isOnlyUserInRole(userDN, groupResult)) && (!EMPTY_ROLES_ALLOWED)) {
                                String errorMessage = "User: " + userName + " is the only user " +
                                                      "in " + role + "." + "There should be at " +
                                                      "least one user" + " in the role. Hence can" +
                                                      " not delete the user.";
                                logger.error(errorMessage);
                                throw new UserStoreException(errorMessage);
                            }

                        }
                    }
                    for (String role : rolesOfUser) {
                        //no need to update entries related to internal roles when deleting user.
                        if (!isInternalRole(role)) {
                            updateRoleListOfUser(userName, new String[]{role}, new String[]{});
                        } else if (isInternalRole(role)) {
                            hybridRoleManager.deleteUser(userName);
                        }
                    }
                }
            }
            //delete user entry
            if (userResult.getAttributes().get(userNameAttribute).get().equals(userName)) {
                subDirContext = (DirContext) mainDirContext.lookup(USER_SEARCH_BASE);
                subDirContext.destroySubcontext(userDN);
            }
            this.userRealm.getAuthorizationManager().clearUserAuthorization(userName);
        } catch (NamingException e) {
            String errorMessage = "Error occurred while deleting the user. ";
            logger.error(errorMessage, e);
            throw new UserStoreException(errorMessage, e);
        } finally {
            JNDIUtil.closeNamingEnumeration(groupResults);
            JNDIUtil.closeNamingEnumeration(userResults);

            JNDIUtil.closeContext(subDirContext);
View Full Code Here

                                                                    1, password.indexOf("}"));
                        }

                        if (!password.equals(getPasswordToStore((String) oldCredential,
                                                                passwordHashMethod))) {
                            throw new UserStoreException("Old password does not match");
                        }
                    }
                }

                String dnName = searchResult.getName();
                subDirContext = (DirContext) dirContext.lookup(searchBase);

                Attribute passwordAttribute = new BasicAttribute("userPassword");
                passwordAttribute.add(getPasswordToStore((String) newCredential,
                                                         passwordHashMethod));
                BasicAttributes basicAttributes = new BasicAttributes(true);
                basicAttributes.put(passwordAttribute);
                subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE,
                                               basicAttributes);
            }
            //we check whether both carbon admin entry and ldap connection entry are the same
            if (searchResult.getNameInNamespace().equals(realmConfig.getUserStoreProperty(
                    LDAPConstants.CONNECTION_NAME))) {
                this.connectionSource.updateCredential((String) newCredential);
            }

        } catch (NamingException e) {
            throw new UserStoreException("Can not access the directory service", e);
        } finally {
            JNDIUtil.closeNamingEnumeration(passwords);
            JNDIUtil.closeNamingEnumeration(namingEnumeration);

            JNDIUtil.closeContext(subDirContext);
View Full Code Here

            //TODO:what if more than one user is returned
            returnedUserEntry = returnedResultList.next().getName();

        } catch (NamingException e) {

            throw new UserStoreException("Results could not be retrieved from the directory " +
                                         "context", e);
        } finally {
            JNDIUtil.closeNamingEnumeration(returnedResultList);
        }


        if (profileName == null) {

            profileName = UserCoreConstants.DEFAULT_PROFILE;
        }

        if (claims.get(UserCoreConstants.PROFILE_CONFIGURATION) == null) {

            claims.put(UserCoreConstants.PROFILE_CONFIGURATION, UserCoreConstants.
                    DEFAULT_PROFILE_CONFIGURATION);
        }
        try {
            Attributes updatedAttributes = new BasicAttributes(true);
            for (Map.Entry<String, String> claimEntry : claims.entrySet()) {
                String claimURI = claimEntry.getKey();
                //if there is no attribute for profile configuration in LDAP, skip updating it.
                if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) {
                    continue;
                }
                //get the claimMapping related to this claimURI
                ClaimMapping claimMapping = (ClaimMapping) claimManager.getClaimMapping(claimURI);
                String attributeName = null;

                if (claimMapping != null) {
                    attributeName = claimMapping.getMappedAttribute();
                } else {
                    attributeName = claimURI;
                }
                Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
                /*if updated attribute value is null, remove its values.*/
                if (EMPTY_ATTRIBUTE_STRING.equals(claimEntry.getValue())) {
                    currentUpdatedAttribute.clear();
                } else {
                    currentUpdatedAttribute.add(claimEntry.getValue());
                }
                updatedAttributes.put(currentUpdatedAttribute);
            }
            //update the attributes in the relevant entry of the directory store

            subDirContext = (DirContext) dirContext.lookup(userSearchBase);
            subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes);

        } catch (InvalidAttributeValueException e) {
            String errorMessage = "One or more attribute values provided are incompatible. " +
                                  "Please check and try again.";
            logger.error(errorMessage, e);
            throw new UserStoreException(errorMessage, e);

        } catch (NoSuchAttributeException e) {
            String errorMessage = "One or more attributes you are trying to add/update are not " +
                                  "supported by underlying LDAP.";
            logger.error(errorMessage, e);
            throw new UserStoreException(errorMessage, e);

        } catch (NamingException e) {
            String errorMessage = "Profile information could not be updated in ApacheDS " +
                                  "LDAP user store";
            logger.error(errorMessage, e);
            throw new UserStoreException(errorMessage, e);

        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            String errorMessage = "Error in obtaining claim mapping.";
            logger.error(errorMessage, e);
            throw new UserStoreException(errorMessage, e);
        } finally {
            JNDIUtil.closeContext(subDirContext);
            JNDIUtil.closeContext(dirContext);
        }

View Full Code Here

TOP

Related Classes of org.wso2.carbon.user.core.UserStoreException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.