Search in sources :

Example 71 with Attribute

use of javax.naming.directory.Attribute in project hadoop by apache.

the class TestLdapGroupsMappingWithOneQuery method setupMocks.

@Before
public void setupMocks() throws NamingException {
    Attribute groupDN = mock(Attribute.class);
    NamingEnumeration<SearchResult> groupNames = getGroupNames();
    doReturn(groupNames).when(groupDN).getAll();
    String groupName1 = "CN=abc,DC=foo,DC=bar,DC=com";
    String groupName2 = "CN=xyz,DC=foo,DC=bar,DC=com";
    String groupName3 = "CN=sss,CN=foo,DC=bar,DC=com";
    doReturn(groupName1).doReturn(groupName2).doReturn(groupName3).when(groupNames).next();
    when(groupNames.hasMore()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
    when(getAttributes().get(eq("memberOf"))).thenReturn(groupDN);
}
Also used : Attribute(javax.naming.directory.Attribute) SearchResult(javax.naming.directory.SearchResult) Matchers.anyString(org.mockito.Matchers.anyString) Before(org.junit.Before)

Example 72 with Attribute

use of javax.naming.directory.Attribute in project hadoop by apache.

the class TestLdapGroupsMappingWithPosixGroup method setupMocks.

@Before
public void setupMocks() throws NamingException {
    Attribute uidNumberAttr = mock(Attribute.class);
    Attribute gidNumberAttr = mock(Attribute.class);
    Attribute uidAttr = mock(Attribute.class);
    Attributes attributes = getAttributes();
    when(uidAttr.get()).thenReturn("some_user");
    when(uidNumberAttr.get()).thenReturn("700");
    when(gidNumberAttr.get()).thenReturn("600");
    when(attributes.get(eq("uid"))).thenReturn(uidAttr);
    when(attributes.get(eq("uidNumber"))).thenReturn(uidNumberAttr);
    when(attributes.get(eq("gidNumber"))).thenReturn(gidNumberAttr);
}
Also used : Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) Before(org.junit.Before)

Example 73 with Attribute

use of javax.naming.directory.Attribute in project eureka by Netflix.

the class DnsResolver method resolveARecord.

/**
     * Look into A-record at a specific DNS address.
     *
     * @return resolved IP addresses or null if no A-record was present
     */
@Nullable
public static List<String> resolveARecord(String rootDomainName) {
    if (isLocalOrIp(rootDomainName)) {
        return null;
    }
    try {
        Attributes attrs = dirContext.getAttributes(rootDomainName, new String[] { A_RECORD_TYPE, CNAME_RECORD_TYPE });
        Attribute aRecord = attrs.get(A_RECORD_TYPE);
        Attribute cRecord = attrs.get(CNAME_RECORD_TYPE);
        if (aRecord != null && cRecord == null) {
            List<String> result = new ArrayList<>();
            NamingEnumeration<String> entries = (NamingEnumeration<String>) aRecord.getAll();
            while (entries.hasMore()) {
                result.add(entries.next());
            }
            return result;
        }
    } catch (Exception e) {
        logger.warn("Cannot load A-record for eureka server address " + rootDomainName, e);
        return null;
    }
    return null;
}
Also used : Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) ArrayList(java.util.ArrayList) NamingEnumeration(javax.naming.NamingEnumeration) NamingException(javax.naming.NamingException) Nullable(javax.annotation.Nullable)

Example 74 with Attribute

use of javax.naming.directory.Attribute in project perun by CESNET.

the class EventProcessorImpl method resolveMessage.

/**
	 * Get a message and id of this message.
	 * Parse the message and decide which way will be further processed.
	 * Using patterns and objects to choose the way.
	 *
	 * Additional Information:
	 * -> For user and serviceUser there is the same behavior.
	 * -> If there is only serviceUser (not serviceUser and user) the behavior for serviceUser is the same like for user (in LDAP)
	 * -> If there are 2 groups in one message, expecting the first is subGroup and second is parentGroup
	 *
	 * Possible ways (first and only 1 possible way with the lowest number is choose):
	 * -> 1) GROUP and MEMBER exist
	 *   -> 1.1) if member status is valid => add member to group in LDAP
	 *   -> 1.2) if member was totally removed from group (totally means there is no direct or indirect existence of member in this group yet)
	 *           => remove member from this group in LDAP
	 * -> 2) GROUP and PARENT_GROUP exist
	 *   -> 2.1) if there is message with adding subgroup => add group like subgroup of parentGroup in LDAP
	 * -> 3) GROUP AND RESOURCE exist
	 *   -> 3.1) if there is message with adding group to resource => add resource to group (like attribute) in LDAP
	 *   -> 3.2) if there is message with removing group from resource => remove resource from group (like attribute) in LDAP
	 * -> 4) only RESOURCE exists (resource must be before group because of
	 *   -> 4.1) if there is message with deleting resource => delete this resource from LDAP
	 *   -> 4.2) if there is message with createing resource => create this resource in LDAP
	 *   -> 4.3) if there is message with updating resource => update this resource in LDAP
	 * -> 5) only GROUP exists
	 *   -> 5.1) if there is message with deleting group => delete this group from LDAP
	 *   -> 5.2) if there is message with creating group => create this group in LDAP
	 *   -> 5.3) if there is message with updating group => update this group in LDAP
	 * -> 6) only MEMBER exists (RPC CALLING used)
	 *   -> 6.1) if there is message with changing of member state to valid => add member to all groups in LDAP where he needs to be
	 *   -> 6.2) if there is message with changing of member state to other than valid => remove member from all groups in LDAP where is needed
	 * -> 7) only VO exists
	 *   -> 7.1) if there is message with deleting vo => delete this vo from LDAP
	 *   -> 7.2) if there is message with creating vo => create this vo in LDAP
	 *   -> 7.3) if there is message with updating vo => update this vo in LDAP
	 * -> 8) USER and USER_EXT_SOURCE exist
	 *   -> 8.1) if there is message with adding userExtSource (IDP) to user => create or update attribute of user in LDAP
	 *   -> 8.2) if there is message with removing userExtSource (IDP) from user => remove or update attribute of user in LDAP
	 * -> 9) USER and ATTRIBUTE exist
	 *   -> 9.1) if there is message with setting attribute to user => set Attribute to user in LDAP
	 * -> 10) USER and ATTRIBUTE_DEFINITION exist
	 *   -> 10.1) if there is message with removing attribute from user => remove Attribute from user in LDAP
	 * -> 11) only USER exists
	 *   -> 11.1) if there is message with deleting user => delete user from LDAP
	 *   -> 11.2) if there is message with creating user => create user in LDAP
	 *   -> 11.3) if there is message with updating user => update user in LDAP
	 *   -> 11.4) if there is message with removing all attribute from user => remove all attributes from user in LDAP (only removeable attributes)
	 * -> 12) FACILITY and ATTRIBUTE exist
	 *   -> 12.1) if there is message with setting attribute to facility => set Attribute to resources (assigned to facility) in LDAP
	 * -> 13) FACILITY and ATTRIBUTE_DEF exist
	 *   -> 13.1) if there is message with removing attribute from facility => remove Attribute from resources (assigned to facility) in LDAP
	 * -> 14) in all other cases
	 *   -> 14.1) always => only log some information
	 *
	 * @param msg message which need to be parse and resolve
	 * @param idOfMessage id of paring/resolving message
	 *
	 * @throws InternalErrorException when some internal error in core occurs
	 */
protected void resolveMessage(String msg, Integer idOfMessage) throws InternalErrorException {
    List<PerunBean> listOfBeans = new ArrayList<PerunBean>();
    listOfBeans = AuditParser.parseLog(msg);
    //TemporaryDebug information for controling parsing of message.
    if (!listOfBeans.isEmpty()) {
        int i = 0;
        for (PerunBean p : listOfBeans) {
            i++;
            if (p != null)
                log.debug("There is object number " + i + ") " + p.serializeToString());
            else
                log.debug("There is unknow object which is null");
        }
    }
    //Fill perunBeans
    emptyAndFillPerunBeans(listOfBeans);
    //Log debug data for looking in messages
    log.debug("MessageNumber=" + idOfMessage + " -- OBJECTS: " + this.member + '/' + this.group + '/' + this.facility + "/" + this.parentGroup + '/' + this.vo + '/' + this.resource + '/' + this.user + '/' + this.attribute + '/' + this.attributeDef + '/' + this.userExtSource);
    //If specific user is the only one user in message, so behavior will be same for him like for any other user!
    if (this.specificUser != null && this.user == null)
        this.user = this.specificUser;
    // 1) IF GROUP AND MEMBER WERE FOUND, TRY TO WORK WITH GROUP-MEMBER SPECIFIC OPERATIONS
    if (this.group != null && this.member != null) {
        // 1.1) ONLY FOR VALID MEMBER WE ADD HIM TO THE GROUP IN LDAP
        if (this.member.getStatus().equals(Status.VALID)) {
            Matcher addedTo = addedToPattern.matcher(msg);
            if (addedTo.find()) {
                if (!ldapConnector.isAlreadyMember(this.member, this.group))
                    ldapConnector.addMemberToGroup(this.member, this.group);
            }
        }
        // 1.2) MEMBER WILL BE REMOVED FROM GROUP
        //Matcher removedFrom = removedFromPattern.matcher(msg);
        Matcher totallyRemovedFrom = totallyRemovedFromPatter.matcher(msg);
        if (totallyRemovedFrom.find()) {
            if (ldapConnector.isAlreadyMember(this.member, this.group))
                ldapConnector.removeMemberFromGroup(this.member, this.group);
        }
    // 2) IF 2 GROUPS WERE FOUND, TRY TO WORK WITH PARENTGROUP-SUBGROUP SPECIFIC OPERATIONS
    } else if (this.group != null && this.parentGroup != null) {
        Matcher newSubGroup = subGroupPattern.matcher(msg);
        // 2.1) ADD GROUP AS SUBGROUP TO PARENTGROUP
        if (newSubGroup.find()) {
            ldapConnector.addGroupAsSubGroup(this.group, this.parentGroup);
        }
    // 3) IF GROUP AND RESOURCE WERE FOUND, TRY TO WORK WITH GROUP-RESOURCE SPECIFIC OPERATIONS
    } else if (this.group != null && this.resource != null) {
        Matcher assigned = assignGroupToResource.matcher(msg);
        Matcher removed = removeGroupFromResource.matcher(msg);
        // 3.1) ADD NEW RESOURCE FOR GROUP IN LDAP
        if (assigned.find()) {
            updateGroupAttribute("assignedToResourceId", String.valueOf(this.resource.getId()), LdapOperation.ADD_ATTRIBUTE, this.group);
            updateResourceAttribute("assignedGroupId", String.valueOf(this.group.getId()), LdapOperation.ADD_ATTRIBUTE, this.resource);
        // 3.2) REMOVE RESOURCE FROM GROUP IN LDAP
        } else if (removed.find()) {
            updateGroupAttribute("assignedToResourceId", String.valueOf(this.resource.getId()), LdapOperation.REMOVE_ATTRIBUTE, this.group);
            updateResourceAttribute("assignedGroupId", String.valueOf(this.group.getId()), LdapOperation.REMOVE_ATTRIBUTE, this.resource);
        }
    // 4) IF ONLY RESOURCE WERE FOUND, TRY TO WORK WITH RESOURCE SPECIFIC OPERATIONS
    } else if (this.resource != null) {
        Matcher deleted = deletedResourcePattern.matcher(msg);
        Matcher created = createdPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        // 4.1) RESOURCE WILL BE DELETED
        if (deleted.find()) {
            ldapConnector.deleteResource(resource);
        // 4.2) RESOURCE WILL BE CREATED
        } else if (created.find()) {
            ldapConnector.createResource(resource, getFacilityEntityIdValue(resource.getFacilityId()));
        // 4.3) RESOURCE WILL BE UPDATED
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            replaceList.add(new Pair("cn", this.resource.getName()));
            if (this.resource.getDescription() != null && !this.resource.getDescription().isEmpty())
                replaceList.add(new Pair("description", this.resource.getDescription()));
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateResourceAttributes(attributes, this.resource);
        }
    // 5) IF ONLY GROUP WERE FOUND, TRY TO WORK WITH GROUP SPECIFIC OPERATIONS
    } else if (this.group != null) {
        Matcher deleted = deletedPattern.matcher(msg);
        Matcher newGroup = newGroupPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        // 5.1) GROUP WILL BE DELETED
        if (deleted.find()) {
            ldapConnector.removeGroup(this.group);
        // 5.2) GROUP WILL BE CREATED
        } else if (newGroup.find()) {
            ldapConnector.addGroup(this.group);
        // 5.3) GROUP WILL BE UPDATED
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            replaceList.add(new Pair("cn", this.group.getName()));
            replaceList.add(new Pair("perunUniqueGroupName", ldapConnector.getVoShortName(this.group.getVoId()) + ":" + this.group.getName()));
            if (this.group.getDescription() != null && !this.group.getDescription().isEmpty())
                replaceList.add(new Pair("description", this.group.getDescription()));
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateGroupAttributes(attributes, this.group);
        }
    // 6) IF MEMBER WAS FOUND, TRY TO WORK WITH MEMBER SPECIFIC OPERATIONS (! RPC CALLING used there !)
    } else if (this.member != null) {
        Matcher validated = validatedPattern.matcher(msg);
        Matcher otherStateOfMember = otherStateOfMemberPattern.matcher(msg);
        // 6.1) MEMBER WAS VALIDATED, NEED TO ADD HIM TO ALL GROUPS
        if (validated.find()) {
            List<Group> memberGroups = new ArrayList<Group>();
            try {
                memberGroups = Rpc.GroupsManager.getAllMemberGroups(ldapcManager.getRpcCaller(), this.member);
            } catch (MemberNotExistsException e) {
            //IMPORTATNT this is not problem, if member not exist, we expected that will be deleted in some message after that, in DB is deleted
            } catch (PrivilegeException e) {
                throw new InternalErrorException("There are no privilegies for getting member's groups", e);
            } catch (InternalErrorException e) {
                throw e;
            }
            for (Group g : memberGroups) {
                if (!ldapConnector.isAlreadyMember(this.member, g))
                    ldapConnector.addMemberToGroup(this.member, g);
            }
        // 6.2) MEMBER STATE WAS CHANGED TO OTHER STATE THAN VALIDATE
        } else if (otherStateOfMember.find()) {
            List<Group> memberGroups = new ArrayList<Group>();
            try {
                memberGroups = Rpc.GroupsManager.getAllMemberGroups(ldapcManager.getRpcCaller(), this.member);
            } catch (MemberNotExistsException e) {
            //IMPORTATNT this is not problem, if member not exist, we expected that will be deleted in some message after that, in DB is deleted
            } catch (PrivilegeException e) {
                throw new InternalErrorException("There are no privilegies for getting member's groups", e);
            } catch (InternalErrorException e) {
                throw e;
            }
            for (Group g : memberGroups) {
                if (ldapConnector.isAlreadyMember(this.member, g))
                    ldapConnector.removeMemberFromGroup(this.member, g);
            }
        }
    // 7) IF VO WAS FOUND, TRY TO WORK WITH VO SPECIFIC OPERATIONS
    } else if (this.vo != null) {
        Matcher deleted = deletedPattern.matcher(msg);
        Matcher created = createdPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        // 7.1) VO WILL BE DELETED
        if (deleted.find()) {
            ldapConnector.deleteVo(this.vo);
        // 7.2) VO WILL BE CREATED
        } else if (created.find()) {
            ldapConnector.createVo(this.vo);
        // 7.3) VO WILL BE UPDATED
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            replaceList.add(new Pair("description", this.vo.getName()));
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateVoAttributes(attributes, this.vo);
        }
    // 8) IF USER AND USEREXTSOURCE WERE FOUND, TRY TO WORK WITH USER-USEREXTSOURCE SPECIFIC OPERATIONS (LIKE SET EXT LOGINS FOR IDP EXTSOURCES)
    } else if (this.user != null && this.userExtSource != null) {
        Matcher addExtSource = addUserExtSource.matcher(msg);
        Matcher removeExtSource = removeUserExtSource.matcher(msg);
        // 8.1) ADD ATTRIBUTE WITH IDP EXTSOURCE
        if (addExtSource.find()) {
            if (this.userExtSource.getExtSource() != null && this.userExtSource.getExtSource().getType() != null) {
                String extLogin;
                if (this.userExtSource.getExtSource().getType().equals(ExtSourcesManager.EXTSOURCE_IDP)) {
                    extLogin = this.userExtSource.getLogin();
                    if (extLogin == null)
                        extLogin = "";
                    updateUserAttribute("eduPersonPrincipalNames", extLogin, LdapOperation.ADD_ATTRIBUTE, user);
                }
            }
        // 8.2) REMOVE ATTRIBUTE WITH IDP EXTSOURCE
        } else if (removeExtSource.find()) {
            if (this.userExtSource.getExtSource() != null && this.userExtSource.getExtSource().getType() != null) {
                String extLogin;
                if (this.userExtSource.getExtSource().getType().equals(ExtSourcesManager.EXTSOURCE_IDP)) {
                    extLogin = this.userExtSource.getLogin();
                    if (extLogin == null)
                        extLogin = "";
                    updateUserAttribute("eduPersonPrincipalNames", extLogin, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            }
        }
    // 9) IF USER AND ATTRIBUTE WERE FOUND, TRY TO WORK WITH USER-ATTR SPECIFIC OPERATIONS (LIKE SET USER ATTRIBUTES)
    } else if (this.user != null && this.attribute != null) {
        Matcher set = userSetPattern.matcher(msg);
        // 9.1) SOME USER ATTRIBUTE WILL BE PROBABLY SET (IF IT IS ONE OF SPECIFIC ATTRIBUTES)
        if (set.find()) {
            Matcher uidMatcher = userUidNamespace.matcher(this.attribute.getName());
            Matcher loginMatcher = userLoginNamespace.matcher(this.attribute.getName());
            //USER PREFERREDMAIL WILL BE SET
            if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":preferredMail")) {
                //this mean change of attribute preferredMail in User
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("preferredMail", (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, user);
                    updateUserAttribute("mail", (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, user);
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "preferredMail")) {
                        updateUserAttribute("preferredMail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                    if (ldapConnector.userAttributeExist(this.user, "mail")) {
                        updateUserAttribute("mail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            //USER ORGANIZATION WILL BE SET
            } else if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":organization")) {
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("o", (String) attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "o")) {
                        updateUserAttribute("o", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            //USER CERT DNS WILL BE SET (special method for updating)
            } else if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_VIRT + ":userCertDNs")) {
                Map<String, String> certDNsMap = new HashMap<String, String>();
                if (this.attribute.getValue() != null)
                    certDNsMap = (Map) this.attribute.getValue();
                else
                    certDNsMap = null;
                if (certDNsMap == null || certDNsMap.isEmpty()) {
                    if (ldapConnector.userAttributeExist(this.user, "userCertificateSubject")) {
                        updateUserAttribute("userCertificateSubject", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                } else {
                    Set<String> certSubjectsWithPrefixes = ((Map) this.attribute.getValue()).keySet();
                    Set<String> certSubjectsWithoutPrefixes = new HashSet<>();
                    //remove prefixes from certificates
                    for (String key : certSubjectsWithPrefixes) {
                        certSubjectsWithoutPrefixes.add(key.replaceFirst("^[0-9]+[:]", ""));
                    }
                    String[] subjectsArray = Arrays.copyOf(certSubjectsWithoutPrefixes.toArray(), certSubjectsWithoutPrefixes.toArray().length, String[].class);
                    ldapConnector.updateUsersCertSubjects(String.valueOf(this.user.getId()), subjectsArray);
                }
            //USER LIBRARY IDs WILL BE SET (special method for updating)
            } else if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":libraryIDs")) {
                List<String> libraryIDsList = new ArrayList<>();
                if (this.attribute.getValue() != null)
                    libraryIDsList = (ArrayList) this.attribute.getValue();
                else
                    libraryIDsList = null;
                if (libraryIDsList == null || libraryIDsList.isEmpty()) {
                    if (ldapConnector.userAttributeExist(this.user, "libraryIDs")) {
                        updateUserAttribute("libraryIDs", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                } else {
                    String[] subjectsArray = Arrays.copyOf(libraryIDsList.toArray(), libraryIDsList.toArray().length, String[].class);
                    ldapConnector.updateUsersLibraryIds(String.valueOf(this.user.getId()), subjectsArray);
                }
            //USER UID NUMBER WILL BE SET
            } else if (uidMatcher.find()) {
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("uidNumber;x-ns-" + this.attribute.getFriendlyNameParameter(), String.valueOf((Integer) this.attribute.getValue()), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "uidNumber;x-ns-" + this.attribute.getFriendlyNameParameter())) {
                        updateUserAttribute("uidNumber;x-ns-" + this.attribute.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            //USER LOGIN WILL BE SET
            } else if (loginMatcher.find()) {
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("login;x-ns-" + this.attribute.getFriendlyNameParameter(), (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                    //if login is from loginNamespace (eg. EINFRA) (new value), then userPassword must be set or modified
                    if (ldapProperties.getLdapLoginNamespace().toLowerCase().equals(this.attribute.getFriendlyNameParameter())) {
                        updateUserAttribute("userPassword", "{SASL}" + this.attribute.getValue() + "@" + ldapProperties.getLdapLoginNamespace(), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                    }
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "login;x-ns-" + this.attribute.getFriendlyNameParameter())) {
                        updateUserAttribute("login;x-ns-" + this.attribute.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                    if (ldapProperties.getLdapLoginNamespace().toLowerCase().equals(this.attribute.getFriendlyNameParameter())) {
                        if (ldapConnector.userAttributeExist(this.user, "userPassword")) {
                            updateUserAttribute("userPassword", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                        }
                    }
                }
            }
        }
    // 10) IF USER AND ATTRIBTUE DEFINITION WERE FOUND, TRY TO WORK WITH USER-ATTRDEF SPECIFIC OPERATIONS
    } else if (this.user != null && attributeDef != null) {
        Matcher remove = userRemovePattern.matcher(msg);
        // 10.1) REMOVE SPECIFIC USER ATTRIBUTE
        if (remove.find() && ldapConnector.userExist(this.user)) {
            Matcher uidMatcher = userUidNamespace.matcher(this.attributeDef.getName());
            Matcher loginMatcher = userLoginNamespace.matcher(this.attributeDef.getName());
            if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":preferredMail")) {
                if (ldapConnector.userAttributeExist(this.user, "preferredMail")) {
                    updateUserAttribute("preferredMail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
                if (ldapConnector.userAttributeExist(this.user, "mail")) {
                    updateUserAttribute("mail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            //TODO: organization (user) will not exists
            } else if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":organization")) {
                if (ldapConnector.userAttributeExist(this.user, "o")) {
                    updateUserAttribute("o", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_VIRT + ":userCertDNs")) {
                if (ldapConnector.userAttributeExist(this.user, "userCertificateSubject")) {
                    updateUserAttribute("userCertificateSubject", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":libraryIDs")) {
                if (ldapConnector.userAttributeExist(this.user, "libraryIDs")) {
                    updateUserAttribute("libraryIDs", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (uidMatcher.find()) {
                if (ldapConnector.userAttributeExist(this.user, "uidNumber;x-ns-" + this.attributeDef.getFriendlyNameParameter())) {
                    updateUserAttribute("uidNumber;x-ns-" + this.attributeDef.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (loginMatcher.find()) {
                if (ldapConnector.userAttributeExist(this.user, "login;x-ns-" + this.attributeDef.getFriendlyNameParameter())) {
                    updateUserAttribute("login;x-ns-" + this.attributeDef.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
                if (ldapProperties.getLdapLoginNamespace().toLowerCase().equals(this.attributeDef.getFriendlyNameParameter())) {
                    if (ldapConnector.userPasswordExists(this.user)) {
                        updateUserAttribute("userPassword", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            }
        }
    // 11) IF ONLY USER WAS FOUND, TRY TO WORK WITH USER SPECIFIC OPERATIONS
    } else if (this.user != null) {
        Matcher deleted = deletedPattern.matcher(msg);
        Matcher created = createdPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        Matcher removedAllAttrs = userAllAttrsRemovedPattern.matcher(msg);
        // 11.1) DELETE USER
        if (deleted.find()) {
            ldapConnector.deleteUser(this.user);
        // 11.2) CREATE USER
        } else if (created.find()) {
            ldapConnector.createUser(this.user);
        // 11.3) UPDATE USER
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            String firstName = this.user.getFirstName();
            String lastName = this.user.getLastName();
            if (firstName == null)
                firstName = "";
            if (lastName == null || lastName.isEmpty())
                lastName = "N/A";
            replaceList.add(new Pair("sn", lastName));
            replaceList.add(new Pair("cn", firstName + " " + lastName));
            // IF firstName is empty, maybe need to be removed first
            if (firstName.isEmpty()) {
                //if first name exists and new one is empty, then remove it, else do nothing
                if (ldapConnector.userAttributeExist(this.user, "givenName")) {
                    updateUserAttribute("givenName", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else {
                //if first name is not empty, replace it by new first name
                replaceList.add(new Pair("givenName", firstName));
            }
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateUserAttributes(attributes, this.user);
        // 11.4) REMOVE ALL USER ATTRIBUTES
        } else if (removedAllAttrs.find()) {
            if (ldapConnector.userExist(this.user)) {
                Attributes usersAttrs = ldapConnector.getAllUsersAttributes(this.user);
                List<ModificationItem> listOfItems = new ArrayList<ModificationItem>();
                if (usersAttrs != null) {
                    NamingEnumeration<? extends Attribute> attributesEnumeration;
                    attributesEnumeration = usersAttrs.getAll();
                    try {
                        while (attributesEnumeration.hasMore()) {
                            Attribute attr = attributesEnumeration.nextElement();
                            if (attr != null && attr.getID() != null) {
                                if (isRemovableUserAttribute(attr.getID())) {
                                    ModificationItem item = new ModificationItem(LdapOperation.REMOVE_ATTRIBUTE.getCode(), attr);
                                    listOfItems.add(item);
                                }
                            }
                        }
                    } catch (NamingException ex) {
                        throw new InternalErrorException("Error at Deleting All Users Attribute, throw namingException.", ex);
                    }
                }
                if (!listOfItems.isEmpty()) {
                    ModificationItem[] items = Arrays.copyOf(listOfItems.toArray(), listOfItems.toArray().length, ModificationItem[].class);
                    ldapConnector.updateUser(this.user, items);
                }
            }
        }
    //12) IF FACILITY AND ATTRIBUTE TO SET WAS FOUND
    } else if (this.facility != null && attribute != null) {
        Matcher set = facilitySetPattern.matcher(msg);
        // 12.1) SOME FACILITY ATTRIBUTE WILL BE PROBABLY SET (IF IT IS ONE OF SPECIFIC ATTRIBUTES)
        if (set.find()) {
            //EntityID WILL BE SET
            if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_FACILITY_ATTR_DEF + ":entityID")) {
                try {
                    List<Resource> resources = Rpc.FacilitiesManager.getAssignedResources(ldapcManager.getRpcCaller(), this.facility);
                    //this mean change of attribute entityID in all assigned resources
                    if (this.attribute.getValue() != null) {
                        for (Resource res : resources) {
                            updateResourceAttribute("entityID", (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, res);
                        }
                    } else {
                        for (Resource res : resources) {
                            if (ldapConnector.resourceAttributeExist(res, "entityID")) {
                                updateResourceAttribute("entityID", null, LdapOperation.REMOVE_ATTRIBUTE, res);
                            }
                        }
                    }
                } catch (FacilityNotExistsException ex) {
                    //this probably means that facility is already removed, so also resources are removed and we just delete them in some other message
                    //so skip it just log
                    log.debug("Try to get resources from facility, but facility just not exists. Skip it!");
                } catch (PrivilegeException e) {
                    throw new InternalErrorException("There are no privilegies for getting all assigned resources of facility" + this.facility, e);
                }
            }
        }
    //13) IF FACILITY AND ATTRIBUTE DEF TO REMOVE WAS FOUND
    } else if (this.facility != null && attributeDef != null) {
        Matcher remove = facilityRemovePattern.matcher(msg);
        // 13.1) REMOVE SPECIFIC FACILITY ATTRIBUTE
        if (remove.find()) {
            if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_FACILITY_ATTR_DEF + ":entityID")) {
                try {
                    List<Resource> resources = Rpc.FacilitiesManager.getAssignedResources(ldapcManager.getRpcCaller(), this.facility);
                    for (Resource res : resources) {
                        if (ldapConnector.resourceAttributeExist(res, "entityID")) {
                            updateResourceAttribute("entityID", null, LdapOperation.REMOVE_ATTRIBUTE, res);
                        }
                    }
                } catch (FacilityNotExistsException ex) {
                    //this probably means that facility is already removed, so also resources are removed and we just delete them in some other message
                    //so skip it just log
                    log.debug("Try to get resources from facility, but facility just not exists. Skip it!");
                } catch (PrivilegeException e) {
                    throw new InternalErrorException("There are no privilegies for getting all assigned resources of facility" + this.facility, e);
                }
            }
        }
    // 14) IN OTHER CASES
    } else {
        log.debug("Nothing to resolve for message with number : " + idOfMessage);
    }
}
Also used : LdapOperation(cz.metacentrum.perun.ldapc.beans.LdapOperation) Matcher(java.util.regex.Matcher) HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) NamingEnumeration(javax.naming.NamingEnumeration) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) ArrayList(java.util.ArrayList) List(java.util.List) NamingException(javax.naming.NamingException) HashSet(java.util.HashSet) MemberNotExistsException(cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 75 with Attribute

use of javax.naming.directory.Attribute in project perun by CESNET.

the class LdapConnectorImpl method createUser.

//-----------------------USER MODIFICATION METHODS----------------------------
public void createUser(User user) throws InternalErrorException {
    // Create a set of attributes
    Attributes attributes = new BasicAttributes();
    // Create the objectclass to add
    Attribute objClasses = new BasicAttribute("objectClass");
    objClasses.add("top");
    objClasses.add("person");
    objClasses.add("organizationalPerson");
    objClasses.add("inetOrgPerson");
    objClasses.add("perunUser");
    objClasses.add("tenOperEntry");
    objClasses.add("inetUser");
    String firstName = user.getFirstName();
    String lastName = user.getLastName();
    if (firstName == null)
        firstName = "";
    if (lastName == null || lastName.isEmpty())
        lastName = "N/A";
    // Add attributes
    attributes.put(objClasses);
    attributes.put("entryStatus", "active");
    attributes.put("sn", lastName);
    attributes.put("cn", firstName + " " + lastName);
    if (!firstName.isEmpty())
        attributes.put("givenName", firstName);
    attributes.put("perunUserId", String.valueOf(user.getId()));
    if (user.isServiceUser())
        attributes.put("isServiceUser", "1");
    else
        attributes.put("isServiceUser", "0");
    if (user.isSponsoredUser())
        attributes.put("isSponsoredUser", "1");
    else
        attributes.put("isSponsoredUser", "0");
    // Create the entry
    try {
        ldapTemplate.bind(getUserDN(String.valueOf(user.getId())), null, attributes);
        log.debug("New entry created in LDAP: User {} in Group with Id=" + user.getId() + ".", user);
    } catch (NameNotFoundException e) {
        throw new InternalErrorException(e);
    }
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) BasicAttributes(javax.naming.directory.BasicAttributes) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) NameNotFoundException(org.springframework.ldap.NameNotFoundException) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException)

Aggregations

Attribute (javax.naming.directory.Attribute)110 Attributes (javax.naming.directory.Attributes)57 NamingException (javax.naming.NamingException)39 BasicAttribute (javax.naming.directory.BasicAttribute)39 BasicAttributes (javax.naming.directory.BasicAttributes)30 ArrayList (java.util.ArrayList)29 SearchResult (javax.naming.directory.SearchResult)25 NamingEnumeration (javax.naming.NamingEnumeration)22 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)18 HashSet (java.util.HashSet)17 DirContext (javax.naming.directory.DirContext)17 SearchControls (javax.naming.directory.SearchControls)17 IOException (java.io.IOException)11 InitialDirContext (javax.naming.directory.InitialDirContext)11 ModificationItem (javax.naming.directory.ModificationItem)11 Hashtable (java.util.Hashtable)9 File (java.io.File)7 List (java.util.List)7 MutablePartitionConfiguration (org.apache.directory.server.core.configuration.MutablePartitionConfiguration)7 AbstractBootstrapSchema (org.apache.directory.server.core.schema.bootstrap.AbstractBootstrapSchema)7