Search in sources :

Example 1 with ExtSource

use of cz.metacentrum.perun.core.api.ExtSource in project perun by CESNET.

the class VosManagerBlImpl method findCandidates.

public List<Candidate> findCandidates(PerunSession sess, Vo vo, String searchString, int maxNumOfResults) throws InternalErrorException {
    List<Candidate> candidates = new ArrayList<Candidate>();
    int numOfResults = 0;
    try {
        // Iterate through all registered extSources
        for (ExtSource source : getPerunBl().getExtSourcesManagerBl().getVoExtSources(sess, vo)) {
            // Info if this is only simple ext source, change behavior if not
            boolean simpleExtSource = true;
            // Get potential subjects from the extSource
            List<Map<String, String>> subjects;
            try {
                if (source instanceof ExtSourceApi) {
                    // find subjects with all their properties
                    subjects = ((ExtSourceApi) source).findSubjects(searchString, maxNumOfResults);
                    simpleExtSource = false;
                } else {
                    // find subjects only with logins - they then must be retrieved by login
                    subjects = ((ExtSourceSimpleApi) source).findSubjectsLogins(searchString, maxNumOfResults);
                }
            } catch (ExtSourceUnsupportedOperationException e1) {
                log.warn("ExtSource {} doesn't support findSubjects", source.getName());
                continue;
            } catch (InternalErrorException e) {
                log.error("Error occurred on ExtSource {},  Exception {}.", source.getName(), e);
                continue;
            } finally {
                try {
                    ((ExtSourceSimpleApi) source).close();
                } catch (ExtSourceUnsupportedOperationException e) {
                // ExtSource doesn't support that functionality, so silently skip it.
                } catch (InternalErrorException e) {
                    log.error("Can't close extSource connection. Cause: {}", e);
                }
            }
            Set<String> uniqueLogins = new HashSet<>();
            for (Map<String, String> s : subjects) {
                // Check if the user has unique identifier within extSource
                if ((s.get("login") == null) || (s.get("login") != null && ((String) s.get("login")).isEmpty())) {
                    log.error("User '{}' cannot be added, because he/she doesn't have a unique identifier (login)", s);
                    // Skip to another user
                    continue;
                }
                String extLogin = (String) s.get("login");
                // check uniqueness of every login in extSource
                if (uniqueLogins.contains(extLogin)) {
                    throw new InternalErrorException("There are more than 1 login '" + extLogin + "' getting from extSource '" + source + "'");
                } else {
                    uniqueLogins.add(extLogin);
                }
                // Get Candidate
                Candidate candidate;
                try {
                    if (simpleExtSource) {
                        // retrieve data about subjects from ext source based on ext. login
                        candidate = getPerunBl().getExtSourcesManagerBl().getCandidate(sess, source, extLogin);
                    } else {
                        // retrieve data about subjects from subjects we already have locally
                        candidate = getPerunBl().getExtSourcesManagerBl().getCandidate(sess, s, source, extLogin);
                    }
                } catch (ExtSourceNotExistsException e) {
                    throw new ConsistencyErrorException("Getting candidate from non-existing extSource " + source, e);
                } catch (CandidateNotExistsException e) {
                    throw new ConsistencyErrorException("findSubjects returned that candidate, but getCandidate cannot find him using login " + extLogin, e);
                } catch (ExtSourceUnsupportedOperationException e) {
                    throw new InternalErrorException("extSource supports findSubjects but not getCandidate???", e);
                }
                try {
                    getPerunBl().getMembersManagerBl().getMemberByUserExtSources(sess, vo, candidate.getUserExtSources());
                    // Candidate is already a member of the VO, so do not add him to the list of candidates
                    continue;
                } catch (MemberNotExistsException e) {
                // This is OK
                }
                // Add candidate to the list of candidates
                log.debug("findCandidates: returning candidate: {}", candidate);
                candidates.add(candidate);
                numOfResults++;
                // Stop getting new members if the number of already retrieved members exceeded the maxNumOfResults
                if (maxNumOfResults > 0 && numOfResults >= maxNumOfResults) {
                    break;
                }
            }
            // Stop walking through next sources if the number of already retrieved members exceeded the maxNumOfResults
            if (maxNumOfResults > 0 && numOfResults >= maxNumOfResults) {
                break;
            }
        }
        log.debug("Returning {} potential members for vo {}", candidates.size(), vo);
        return candidates;
    } catch (RuntimeException e) {
        throw new InternalErrorException(e);
    }
}
Also used : Candidate(cz.metacentrum.perun.core.api.Candidate) ConsistencyErrorException(cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException) MemberNotExistsException(cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException) ArrayList(java.util.ArrayList) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) ExtSourceApi(cz.metacentrum.perun.core.implApi.ExtSourceApi) ExtSource(cz.metacentrum.perun.core.api.ExtSource) ExtSourceUnsupportedOperationException(cz.metacentrum.perun.core.api.exceptions.ExtSourceUnsupportedOperationException) ExtSourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException) Map(java.util.Map) ExtSourceSimpleApi(cz.metacentrum.perun.core.implApi.ExtSourceSimpleApi) HashSet(java.util.HashSet) CandidateNotExistsException(cz.metacentrum.perun.core.api.exceptions.CandidateNotExistsException)

Example 2 with ExtSource

use of cz.metacentrum.perun.core.api.ExtSource in project perun by CESNET.

the class urn_perun_user_attribute_def_def_login_namespace_bbmri_persistent_shadow method changedAttributeHook.

/**
	 * ChangedAttributeHook() sets UserExtSource with following properties:
	 *  - extSourceType is IdP
	 *  - extSourceName is https://login.bbmri-eric.eu/idp/
	 *  - user's extSource login is the same as his bbmri-persistent attribute
	 *
	 * @param session PerunSession
	 * @param user User to set UserExtSource for
	 * @param attribute Attribute containing bbmriID
	 * @throws cz.metacentrum.perun.core.api.exceptions.InternalErrorException
	 * @throws cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException
	 */
@Override
public void changedAttributeHook(PerunSessionImpl session, User user, Attribute attribute) throws InternalErrorException, WrongReferenceAttributeValueException {
    try {
        String userNamespace = attribute.getFriendlyNameParameter();
        if (userNamespace.equals("bbmri-persistent-shadow") && attribute.getValue() != null) {
            ExtSource extSource = session.getPerunBl().getExtSourcesManagerBl().getExtSourceByName(session, extSourceNameBbmri);
            UserExtSource userExtSource = new UserExtSource(extSource, 0, attribute.getValue().toString());
            session.getPerunBl().getUsersManagerBl().addUserExtSource(session, user, userExtSource);
        }
    } catch (UserExtSourceExistsException ex) {
        log.warn("BBMRI IdP external source already exists for the user.", ex);
    } catch (ExtSourceNotExistsException ex) {
        throw new InternalErrorException("IdP external source for BBMRI doesn't exist.", ex);
    }
}
Also used : UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) ExtSource(cz.metacentrum.perun.core.api.ExtSource)

Example 3 with ExtSource

use of cz.metacentrum.perun.core.api.ExtSource in project perun by CESNET.

the class ExtSourcesManagerBlImpl method checkExtSourceAssignedToVo.

@Override
public void checkExtSourceAssignedToVo(PerunSession sess, ExtSource extSource, int voId) throws ExtSourceNotAssignedException, VoNotExistsException {
    Vo vo = getPerunBl().getVosManagerBl().getVoById(sess, voId);
    List<ExtSource> voExtSources = getPerunBl().getExtSourcesManagerBl().getVoExtSources(sess, vo);
    if (!voExtSources.contains(extSource))
        throw new ExtSourceNotAssignedException("ExtSource " + extSource + " is not assigned to vo " + vo);
}
Also used : Vo(cz.metacentrum.perun.core.api.Vo) ExtSourceAddedToVo(cz.metacentrum.perun.audit.events.ExtSourcesManagerEvents.ExtSourceAddedToVo) ExtSourceRemovedFromVo(cz.metacentrum.perun.audit.events.ExtSourcesManagerEvents.ExtSourceRemovedFromVo) RichUserExtSource(cz.metacentrum.perun.core.api.RichUserExtSource) ExtSource(cz.metacentrum.perun.core.api.ExtSource) UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) ExtSourceNotAssignedException(cz.metacentrum.perun.core.api.exceptions.ExtSourceNotAssignedException)

Example 4 with ExtSource

use of cz.metacentrum.perun.core.api.ExtSource in project perun by CESNET.

the class MembersManagerBlImpl method createMember.

// MAIN METHOD
@Override
public Member createMember(PerunSession sess, Vo vo, SpecificUserType specificUserType, Candidate candidate, List<Group> groups, List<String> overwriteUserAttributes) throws WrongAttributeValueException, WrongReferenceAttributeValueException, AlreadyMemberException, ExtendMembershipException {
    log.debug("Creating member for VO {} from candidate {}", vo, candidate);
    // Get the user
    User user = null;
    if (candidate.getUserExtSources() != null) {
        for (UserExtSource ues : candidate.getUserExtSources()) {
            // Check if the extSource exists
            ExtSource tmpExtSource = getPerunBl().getExtSourcesManagerBl().checkOrCreateExtSource(sess, ues.getExtSource().getName(), ues.getExtSource().getType());
            // Set the extSource ID
            ues.getExtSource().setId(tmpExtSource.getId());
            try {
                // Try to find the user by userExtSource
                user = getPerunBl().getUsersManagerBl().getUserByExtSourceNameAndExtLogin(sess, ues.getExtSource().getName(), ues.getLogin());
            } catch (UserExtSourceNotExistsException e) {
            // This is OK, non-existent userExtSource will be assigned later
            } catch (UserNotExistsException | ExtSourceNotExistsException e) {
            // Ignore, we are only checking if the user exists
            }
        }
    }
    // If user hasn't been found, then create him
    if (user == null) {
        user = new User();
        user.setFirstName(candidate.getFirstName());
        user.setLastName(candidate.getLastName());
        user.setMiddleName(candidate.getMiddleName());
        user.setTitleAfter(candidate.getTitleAfter());
        user.setTitleBefore(candidate.getTitleBefore());
        if (specificUserType.equals(SpecificUserType.SERVICE))
            user.setServiceUser(true);
        if (specificUserType.equals(SpecificUserType.SPONSORED))
            user.setSponsoredUser(true);
        // Store the user, this must be done in separate transaction
        user = getPerunBl().getUsersManagerBl().createUser(sess, user);
        log.debug("createMember: new user: {}", user);
    }
    // Assign missing userExtSource and update LoA
    if (candidate.getUserExtSources() != null) {
        for (UserExtSource userExtSource : candidate.getUserExtSources()) {
            try {
                UserExtSource currentUserExtSource = getPerunBl().getUsersManagerBl().getUserExtSourceByExtLogin(sess, userExtSource.getExtSource(), userExtSource.getLogin());
                // Update LoA
                currentUserExtSource.setLoa(userExtSource.getLoa());
                getPerunBl().getUsersManagerBl().updateUserExtSource(sess, currentUserExtSource);
            } catch (UserExtSourceNotExistsException e) {
                // Create userExtSource
                try {
                    getPerunBl().getUsersManagerBl().addUserExtSource(sess, user, userExtSource);
                } catch (UserExtSourceExistsException e1) {
                    throw new ConsistencyErrorException("Adding userExtSource which already exists: " + userExtSource);
                }
            } catch (UserExtSourceExistsException e1) {
                throw new ConsistencyErrorException("Updating login of userExtSource to value which already exists: " + userExtSource);
            }
        }
    }
    try {
        Member member = getMemberByUser(sess, vo, user);
        throw new AlreadyMemberException(member);
    } catch (MemberNotExistsException IGNORE) {
    }
    // Create the member
    Member member = getMembersManagerImpl().createMember(sess, vo, user);
    getPerunBl().getAuditer().log(sess, new MemberCreated(member));
    // Create the member's attributes
    List<Attribute> membersAttributes = new ArrayList<>();
    List<Attribute> usersAttributesToMerge = new ArrayList<>();
    List<Attribute> usersAttributesToModify = new ArrayList<>();
    if (candidate.getAttributes() != null) {
        for (String attributeName : candidate.getAttributes().keySet()) {
            AttributeDefinition attributeDefinition;
            try {
                attributeDefinition = getPerunBl().getAttributesManagerBl().getAttributeDefinition(sess, attributeName);
            } catch (AttributeNotExistsException ex) {
                throw new InternalErrorException(ex);
            }
            Attribute attribute = new Attribute(attributeDefinition);
            attribute.setValue(getPerunBl().getAttributesManagerBl().stringToAttributeValue(candidate.getAttributes().get(attributeName), attribute.getType()));
            if (getPerunBl().getAttributesManagerBl().isFromNamespace(sess, attribute, AttributesManager.NS_MEMBER_ATTR_DEF) || getPerunBl().getAttributesManagerBl().isFromNamespace(sess, attribute, AttributesManager.NS_MEMBER_ATTR_OPT)) {
                // This is member's attribute
                membersAttributes.add(attribute);
            } else if (getPerunBl().getAttributesManagerBl().isFromNamespace(sess, attribute, AttributesManager.NS_USER_ATTR_DEF) || getPerunBl().getAttributesManagerBl().isFromNamespace(sess, attribute, AttributesManager.NS_USER_ATTR_OPT)) {
                if (overwriteUserAttributes != null && !overwriteUserAttributes.isEmpty() && overwriteUserAttributes.contains(attribute.getName())) {
                    usersAttributesToModify.add(attribute);
                } else {
                    usersAttributesToMerge.add(attribute);
                }
            }
        }
    }
    // Store the attributes
    try {
        // If empty, skip setting or merging empty arrays of attributes at all
        if (!membersAttributes.isEmpty())
            getPerunBl().getAttributesManagerBl().setAttributes(sess, member, membersAttributes);
        if (!usersAttributesToMerge.isEmpty())
            getPerunBl().getAttributesManagerBl().mergeAttributesValues(sess, user, usersAttributesToMerge);
        if (!usersAttributesToModify.isEmpty())
            getPerunBl().getAttributesManagerBl().setAttributes(sess, user, usersAttributesToModify);
    } catch (WrongAttributeAssignmentException e) {
        throw new InternalErrorException(e);
    }
    // Set the initial membershipExpiration
    // Get user LOA
    String memberLoa = null;
    try {
        Attribute loa = getPerunBl().getAttributesManagerBl().getAttribute(sess, user, AttributesManager.NS_USER_ATTR_VIRT + ":loa");
        memberLoa = Integer.toString((Integer) loa.getValue());
    } catch (AttributeNotExistsException e) {
    // user has no loa defined - if required by VO, it will be stopped in checking method later
    } catch (WrongAttributeAssignmentException e) {
        throw new InternalErrorException(e);
    }
    // Check if user can be member
    this.canBeMemberInternal(sess, vo, user, memberLoa, true);
    // set initial membership expiration
    this.extendMembership(sess, member);
    insertToMemberGroup(sess, member, vo);
    // Add member also to all groups in list
    if (groups != null && !groups.isEmpty()) {
        for (Group group : groups) {
            try {
                perunBl.getGroupsManagerBl().addMember(sess, group, member);
            } catch (GroupNotExistsException e) {
                throw new ConsistencyErrorException(e);
            }
        }
    }
    return member;
}
Also used : Group(cz.metacentrum.perun.core.api.Group) ConsistencyErrorException(cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException) User(cz.metacentrum.perun.core.api.User) RichUser(cz.metacentrum.perun.core.api.RichUser) MemberNotExistsException(cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException) GroupNotExistsException(cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException) ParentGroupNotExistsException(cz.metacentrum.perun.core.api.exceptions.ParentGroupNotExistsException) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) Attribute(cz.metacentrum.perun.core.api.Attribute) WrongAttributeAssignmentException(cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException) UserExtSourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserExtSourceNotExistsException) MemberCreated(cz.metacentrum.perun.audit.events.MembersManagerEvents.MemberCreated) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) ArrayList(java.util.ArrayList) AlreadyMemberException(cz.metacentrum.perun.core.api.exceptions.AlreadyMemberException) AttributeDefinition(cz.metacentrum.perun.core.api.AttributeDefinition) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) UserExtSourceExistsException(cz.metacentrum.perun.core.api.exceptions.UserExtSourceExistsException) UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) ExtSource(cz.metacentrum.perun.core.api.ExtSource) UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) ExtSourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException) UserExtSourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserExtSourceNotExistsException) RichMember(cz.metacentrum.perun.core.api.RichMember) Member(cz.metacentrum.perun.core.api.Member)

Example 5 with ExtSource

use of cz.metacentrum.perun.core.api.ExtSource in project perun by CESNET.

the class GroupsManagerBlImpl method synchronizeGroup.

@Override
public List<String> synchronizeGroup(PerunSession sess, Group group) throws AttributeNotExistsException, WrongAttributeAssignmentException, ExtSourceNotExistsException, GroupNotExistsException {
    // needed variables for whole method
    List<String> skippedMembers = new ArrayList<>();
    ExtSource source = null;
    ExtSource membersSource = null;
    try {
        // set Logback's Mapped Diagnostic Context key for the current thread
        MDC.put(MDC_LOG_FILE_NAME, "groupsync/group_" + group.getId());
        long startTime = System.nanoTime();
        getPerunBl().getAuditer().log(sess, new GroupSyncStarted(group));
        log.debug("Group synchronization for {} has been started.", group);
        // Initialization of group extSource
        source = getGroupExtSourceForSynchronization(sess, group);
        // Initialization of groupMembers extSource (if it is set), in other case set membersSource = source
        membersSource = getGroupMembersExtSourceForSynchronization(sess, group, source);
        // Prepare info about userAttributes which need to be overwritten (not just updated) and memberAttributes which need to be merged not overwritten
        List<String> overwriteUserAttributesList = getAttributesListFromExtSource(membersSource, OVERWRITE_USER_ATTRIBUTES);
        List<String> mergeMemberAttributesList = getAttributesListFromExtSource(membersSource, MERGE_MEMBER_ATTRIBUTES);
        // Get info about type of synchronization (with or without update)
        boolean lightweightSynchronization = isThisLightweightSynchronization(sess, group);
        log.debug("Group synchronization {}: using configuration extSource for membership {}, extSource for members {}", group, membersSource, membersSource.getName());
        // Prepare containers for work with group members
        List<Candidate> candidatesToAdd = new ArrayList<>();
        Map<Candidate, RichMember> membersToUpdate = new HashMap<>();
        List<RichMember> membersToRemove = new ArrayList<>();
        // get all direct members of synchronized group (only direct, because we want to set direct membership with this group by synchronization)
        List<RichMember> actualGroupMembers = getPerunBl().getGroupsManagerBl().getGroupDirectRichMembers(sess, group);
        if (lightweightSynchronization) {
            categorizeMembersForLightweightSynchronization(sess, group, source, membersSource, actualGroupMembers, candidatesToAdd, membersToRemove, skippedMembers);
        } else {
            // Get subjects from extSource
            List<Map<String, String>> subjects = getSubjectsFromExtSource(sess, source, group);
            // Convert subjects to candidates
            List<Candidate> candidates = convertSubjectsToCandidates(sess, subjects, membersSource, source, actualGroupMembers, skippedMembers);
            categorizeMembersForSynchronization(sess, actualGroupMembers, candidates, candidatesToAdd, membersToUpdate, membersToRemove);
        }
        // Remove members from group who are not present in synchronized ExtSource
        boolean isAuthoritative = isAuthoritative(sess, group);
        Collections.sort(membersToRemove);
        for (RichMember memberToRemove : membersToRemove) {
            removeFormerMemberWhileSynchronization(sess, group, memberToRemove, isAuthoritative);
        }
        List<AttributeDefinition> attrDefs = new ArrayList<>();
        // Update members already presented in group
        for (Candidate candidate : membersToUpdate.keySet()) {
            RichMember memberToUpdate = membersToUpdate.get(candidate);
            // Load attrDefinitions just once for first candidate
            if (!candidate.getAttributes().isEmpty() && attrDefs.isEmpty()) {
                attrDefs = getAttributesToSynchronizeFromCandidates(sess, group, candidate);
            }
            updateExistingMemberWhileSynchronization(sess, group, candidate, memberToUpdate, overwriteUserAttributesList, mergeMemberAttributesList, attrDefs);
        }
        // Add not presented candidates to group
        Collections.sort(candidatesToAdd);
        for (Candidate candidateToAdd : candidatesToAdd) {
            addMissingMemberWhileSynchronization(sess, group, candidateToAdd, overwriteUserAttributesList, mergeMemberAttributesList, skippedMembers);
        }
        long endTime = System.nanoTime();
        getPerunBl().getAuditer().log(sess, new GroupSyncFinished(group, startTime, endTime));
        log.info("Group synchronization for {} has been finished.", group);
    } finally {
        closeExtSourcesAfterSynchronization(membersSource, source);
        MDC.remove(MDC_LOG_FILE_NAME);
    }
    return skippedMembers;
}
Also used : Candidate(cz.metacentrum.perun.core.api.Candidate) GroupSyncFinished(cz.metacentrum.perun.audit.events.GroupManagerEvents.GroupSyncFinished) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AttributeDefinition(cz.metacentrum.perun.core.api.AttributeDefinition) GroupSyncStarted(cz.metacentrum.perun.audit.events.GroupManagerEvents.GroupSyncStarted) RichMember(cz.metacentrum.perun.core.api.RichMember) RichUserExtSource(cz.metacentrum.perun.core.api.RichUserExtSource) ExtSource(cz.metacentrum.perun.core.api.ExtSource) UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap)

Aggregations

ExtSource (cz.metacentrum.perun.core.api.ExtSource)135 UserExtSource (cz.metacentrum.perun.core.api.UserExtSource)110 Test (org.junit.Test)57 AbstractPerunIntegrationTest (cz.metacentrum.perun.core.AbstractPerunIntegrationTest)52 Attribute (cz.metacentrum.perun.core.api.Attribute)40 User (cz.metacentrum.perun.core.api.User)40 Vo (cz.metacentrum.perun.core.api.Vo)38 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)35 Member (cz.metacentrum.perun.core.api.Member)31 ExtSourceNotExistsException (cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException)30 UserExtSourceExistsException (cz.metacentrum.perun.core.api.exceptions.UserExtSourceExistsException)28 Candidate (cz.metacentrum.perun.core.api.Candidate)27 RichUserExtSource (cz.metacentrum.perun.core.api.RichUserExtSource)27 ArrayList (java.util.ArrayList)25 Group (cz.metacentrum.perun.core.api.Group)23 LinkedHashMap (java.util.LinkedHashMap)20 PerunBl (cz.metacentrum.perun.core.bl.PerunBl)19 RichMember (cz.metacentrum.perun.core.api.RichMember)17 ConsistencyErrorException (cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException)17 AttributeNotExistsException (cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException)16