/**
   * Creates a group if it does not exist, removes all its members otherwise .
   *
   * @param session The Grouper session to use.
   * @param groupUUID The UUID of the group.
   */
  public void resetGroupMembersInternal(final GrouperSession session, final String groupUUID) {

    final Group group = retrieveGroup(session, groupUUID);

    if (group == null) {
      LOGGER.error("Error the group " + groupUUID + " can't be found.");

    } else {
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Resetting group: " + groupUUID);
      }
      final Set<Member> members = group.getImmediateMembers();
      for (Member member : members) {
        try {
          group.deleteMember(new ESCODeletedSubjectImpl(member.getSubjectId()));
        } catch (InsufficientPrivilegeException e) {
          LOGGER.error(e, e);
          throw new DynamicGroupsException(e);
        } catch (MemberDeleteException e) {
          LOGGER.error(e, e);
          throw new DynamicGroupsException(e);
        }
      }
    }
  }
  /**
   * remove objects not allowed to see privileges on
   *
   * @param groupsAndStems
   */
  public static void removeObjectsNotAllowedToSeePrivs(Set<?> groupsAndStems) {

    if (groupsAndStems == null) {
      return;
    }

    // subject who is making the query
    final Subject grouperSessionSubject = GrouperSession.staticGrouperSession().getSubject();

    Iterator<?> iterator = groupsAndStems.iterator();

    while (iterator.hasNext()) {
      Object groupOrStem = iterator.next();

      if (groupOrStem instanceof Group) {

        Group group = (Group) groupOrStem;
        if (!group.hasAdmin(grouperSessionSubject)) {
          iterator.remove();
        }
      } else if (groupOrStem instanceof Stem) {

        Stem stem = (Stem) groupOrStem;
        if (!stem.hasStem(grouperSessionSubject)) {
          iterator.remove();
        }

      } else {
        // this should never happen
        throw new RuntimeException(
            "Not expecting object of type: " + groupOrStem.getClass() + ", " + groupOrStem);
      }
    }
  }
  /** edit the enabled disabled */
  @SuppressWarnings("unchecked")
  public void memberMenuEnabledDisabled() {

    GuiResponseJs guiResponseJs = GuiResponseJs.retrieveGuiResponseJs();

    // lets see which subject we are dealing with:
    HttpServletRequest httpServletRequest = GrouperUiFilter.retrieveHttpServletRequest();
    String menuIdOfMenuTarget = httpServletRequest.getParameter("menuIdOfMenuTarget");
    if (StringUtils.isBlank(menuIdOfMenuTarget)) {
      throw new RuntimeException("Missing id of menu target");
    }
    if (!menuIdOfMenuTarget.startsWith("memberMenuButton_")) {
      throw new RuntimeException("Invalid id of menu target: '" + menuIdOfMenuTarget + "'");
    }
    String memberId = GrouperUtil.prefixOrSuffix(menuIdOfMenuTarget, "memberMenuButton_", false);

    final Subject loggedInSubject = GrouperUiFilter.retrieveSubjectLoggedIn();

    GrouperSession grouperSession = null;
    Group group = null;
    try {

      grouperSession = GrouperSession.start(loggedInSubject);

      Member member = MemberFinder.findByUuid(grouperSession, memberId, true);

      group = new SimpleMembershipUpdate().retrieveGroup(grouperSession);

      Membership membership =
          group.getImmediateMembership(Group.getDefaultList(), member, false, true);

      SimpleMembershipUpdateContainer simpleMembershipUpdateContainer =
          SimpleMembershipUpdateContainer.retrieveFromSession();

      GuiMember guiMember = new GuiMember(member);
      simpleMembershipUpdateContainer.setEnabledDisabledMember(guiMember);

      guiMember.setMembership(membership);

      guiResponseJs.addAction(
          GuiScreenAction.newDialogFromJsp(
              "/WEB-INF/grouperUi/templates/simpleMembershipUpdate/simpleMembershipUpdateEnabledDisabled.jsp"));

    } catch (ControllerDone cd) {
      throw cd;
    } catch (NoSessionException nse) {
      throw nse;
    } catch (Exception se) {
      throw new RuntimeException(
          "Error listing member details: " + menuIdOfMenuTarget + ", " + se.getMessage(), se);
    } finally {
      GrouperSession.stopQuietly(grouperSession);
    }
  }
 /**
  * Assert that the attributes returned from the data connector match the provided attributes.
  *
  * @param dataConnectorName the data connector name
  * @param group the group
  * @param correctMap the correct attributes
  */
 private void runResolveTest(String dataConnectorName, Group group, AttributeMap correctMap) {
   try {
     GenericApplicationContext gContext =
         BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG);
     GroupDataConnector gdc = (GroupDataConnector) gContext.getBean(dataConnectorName);
     AttributeMap currentMap = new AttributeMap(gdc.resolve(getShibContext(group.getName())));
     LOG.debug("correctMap\n{}", correctMap);
     LOG.debug("currentMap\n{}", currentMap);
     assertEquals(correctMap, currentMap);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
  /**
   * Convenience method
   *
   * @param privileges
   * @param s
   * @param group
   * @return
   */
  protected boolean hasAtleastOneOf(String[] privileges, GrouperSession s, Group group) {
    if (privileges == null || privileges.length == 0) return true;

    boolean result = false;
    for (int i = 0; i < privileges.length; i++) {
      if (privileges[i].equals("admin") && group.hasAdmin(s.getSubject())) return true;
      if (privileges[i].equals("update") && group.hasUpdate(s.getSubject())) return true;
      if (privileges[i].equals("read") && group.hasRead(s.getSubject())) return true;
      if (privileges[i].equals("view") && group.hasView(s.getSubject())) return true;
      if (privileges[i].equals("optin") && group.hasOptin(s.getSubject())) return true;
      if (privileges[i].equals("optout") && group.hasOptout(s.getSubject())) return true;
    }
    return result;
  }
  /**
   * handle a click or select from the advanced menu
   *
   * @param httpServletRequest
   * @param httpServletResponse
   */
  public void advancedMenu(
      HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
    GuiResponseJs guiResponseJs = GuiResponseJs.retrieveGuiResponseJs();

    final Subject loggedInSubject = GrouperUiFilter.retrieveSubjectLoggedIn();

    GrouperSession grouperSession = null;

    Group group = null;

    try {

      grouperSession = GrouperSession.start(loggedInSubject);

      // make sure we are on the right group
      group = new SimpleMembershipUpdate().retrieveGroup(grouperSession);

    } catch (NoSessionException se) {
      throw se;
    } catch (ControllerDone cd) {
      throw cd;
    } catch (Exception se) {
      throw new RuntimeException("Error advanced menu: " + group + ", " + se.getMessage(), se);
    } finally {
      GrouperSession.stopQuietly(grouperSession);
    }

    String menuItemId = httpServletRequest.getParameter("menuItemId");
    String menuEvent = httpServletRequest.getParameter("menuEvent");
    boolean isOnClick = StringUtils.equals("onClick", menuEvent);
    // String menuHtmlId = httpServletRequest.getParameter("menuHtmlId");
    // String menuRadioGroup = httpServletRequest.getParameter("menuRadioGroup");
    String menuCheckboxChecked = httpServletRequest.getParameter("menuCheckboxChecked");

    //    guiResponseJs.addAction(GuiScreenAction.newAlert("Menu action: menuItemId: " + menuItemId
    //        + ", menuHtmlId: " + menuHtmlId
    //        + ", menuRadioGroup: "
    //        + menuRadioGroup + ", menuCheckboxChecked: " + menuCheckboxChecked));

    if (StringUtils.equals(menuItemId, "inviteLink")) {
      guiResponseJs.addAction(
          GuiScreenAction.newScript(
              "window.location = 'grouper.html?operation=InviteExternalSubjects.inviteExternalSubject&groupId="
                  + group.getUuid()
                  + "'"));
    } else if (StringUtils.equals(menuItemId, "showGroupDetails")) {
      if (!isOnClick) {
        if (GrouperUtil.booleanValue(menuCheckboxChecked)) {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToShow("simpleMembershipUpdateGroupDetails"));
        } else {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToHide("simpleMembershipUpdateGroupDetails"));
        }
      }
    } else if (StringUtils.equals(menuItemId, "multiDelete")) {
      if (!isOnClick) {
        if (GrouperUtil.booleanValue(menuCheckboxChecked)) {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToShow("simpleMembershipUpdateDeleteMultiple"));
        } else {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToHide("simpleMembershipUpdateDeleteMultiple"));
        }
      }
    } else if (StringUtils.equals(menuItemId, "showMemberFilter")) {
      if (!isOnClick) {
        if (GrouperUtil.booleanValue(menuCheckboxChecked)) {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToShow("simpleMembershipUpdateMemberFilter"));
        } else {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToHide("simpleMembershipUpdateMemberFilter"));
        }
      }
    } else if (StringUtils.equals(menuItemId, "exportSubjectIds")) {
      guiResponseJs.addAction(
          GuiScreenAction.newAlertFromJsp(
              "/WEB-INF/grouperUi/templates/simpleMembershipUpdate/simpleMembershipUpdateExportSubjectIds.jsp"));
    } else if (StringUtils.equals(menuItemId, "exportAll")) {
      guiResponseJs.addAction(
          GuiScreenAction.newAlertFromJsp(
              "/WEB-INF/grouperUi/templates/simpleMembershipUpdate/simpleMembershipUpdateExportAll.jsp"));

    } else if (StringUtils.equals(menuItemId, "import")) {
      guiResponseJs.addAction(
          GuiScreenAction.newDialogFromJsp(
              "/WEB-INF/grouperUi/templates/simpleMembershipUpdate/simpleMembershipUpdateImport.jsp"));
    } else {
      throw new RuntimeException("Unexpected menu id: '" + menuItemId + "'");
    }
  }
  /**
   * @see
   *     edu.internet2.middleware.grouper.changeLog.ChangeLogConsumerBase#processChangeLogEntries(java.util.List,
   *     edu.internet2.middleware.grouper.changeLog.ChangeLogProcessorMetadata)
   */
  @Override
  public long processChangeLogEntries(
      List<ChangeLogEntry> changeLogEntryList,
      ChangeLogProcessorMetadata changeLogProcessorMetadata) {

    long currentId = -1;

    boolean startedGrouperSession = false;
    GrouperSession grouperSession = GrouperSession.staticGrouperSession(false);
    if (grouperSession == null) {
      grouperSession = GrouperSession.startRootSession();
      startedGrouperSession = true;
    } else {
      grouperSession = grouperSession.internal_getRootSession();
    }

    // try catch so we can track that we made some progress
    try {
      for (ChangeLogEntry changeLogEntry : changeLogEntryList) {
        currentId = changeLogEntry.getSequenceNumber();

        // if this is a group add action and category
        if (changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.GROUP_ADD)) {

          String groupName = changeLogEntry.retrieveValueForLabel(ChangeLogLabels.GROUP_ADD.name);
          if (GrouperDuoUtils.validDuoGroupName(groupName)) {
            String groupExtension = GrouperUtil.extensionFromName(groupName);
            // get the group in grouper
            String groupDescription =
                changeLogEntry.retrieveValueForLabel(ChangeLogLabels.GROUP_ADD.description);
            // shouldnt be the case but check anyways
            if (!GrouperDuoCommands.retrieveGroups().containsKey(groupExtension)) {
              GrouperDuoCommands.createDuoGroup(groupExtension, groupDescription, true);
            }
          }
        } else if (changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.GROUP_DELETE)) {
          String groupName =
              changeLogEntry.retrieveValueForLabel(ChangeLogLabels.GROUP_DELETE.name);
          if (GrouperDuoUtils.validDuoGroupName(groupName)) {
            String groupExtension = GrouperUtil.extensionFromName(groupName);
            // shouldnt be the case but check anyways
            GrouperDuoGroup grouperDuoGroup =
                GrouperDuoCommands.retrieveGroups().get(groupExtension);
            if (grouperDuoGroup != null) {
              GrouperDuoCommands.deleteDuoGroup(grouperDuoGroup.getId(), true);
            }
          }
        }
        if (changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.GROUP_UPDATE)) {
          String groupName =
              changeLogEntry.retrieveValueForLabel(ChangeLogLabels.GROUP_UPDATE.name);
          if (GrouperDuoUtils.validDuoGroupName(groupName)) {
            String groupExtension = GrouperUtil.extensionFromName(groupName);
            // get the group in grouper

            Group group = GroupFinder.findByName(grouperSession, groupName, false);

            if (group != null) {

              // shouldnt be the case but check anyways
              Map<String, GrouperDuoGroup> groupNameToDuoGroupMap =
                  GrouperDuoCommands.retrieveGroups();
              GrouperDuoGroup grouperDuoGroup = groupNameToDuoGroupMap.get(groupExtension);
              if (grouperDuoGroup != null) {
                GrouperDuoCommands.updateDuoGroup(
                    grouperDuoGroup.getId(), group.getDescription(), true);
              }
            }
          }
        }

        boolean isMembershipAdd =
            changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.MEMBERSHIP_ADD);
        boolean isMembershipDelete =
            changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.MEMBERSHIP_DELETE);
        boolean isMembershipUpdate =
            changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.MEMBERSHIP_UPDATE);
        if (isMembershipAdd || isMembershipDelete || isMembershipUpdate) {
          String groupName =
              changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_ADD.groupName);

          if (GrouperDuoUtils.validDuoGroupName(groupName)) {
            String sourceId =
                changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_ADD.sourceId);

            boolean inCorrectSubjectSource =
                GrouperDuoUtils.configSourcesForSubjects().contains(sourceId);

            if (inCorrectSubjectSource) {
              String groupExtension = GrouperUtil.extensionFromName(groupName);
              Group group = GroupFinder.findByName(grouperSession, groupName, false);
              Map<String, GrouperDuoGroup> groupNameToDuoGroupMap =
                  GrouperDuoCommands.retrieveGroups();
              GrouperDuoGroup grouperDuoGroup = groupNameToDuoGroupMap.get(groupExtension);
              String subjectId =
                  changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_ADD.subjectId);

              String subjectAttributeForDuoUsername =
                  GrouperDuoUtils.configSubjectAttributeForDuoUsername();

              String username = null;
              Subject subject = SubjectFinder.findByIdAndSource(subjectId, sourceId, false);

              if (StringUtils.equals("id", subjectAttributeForDuoUsername)) {
                username = subjectId;
              } else {

                if (subject != null) {
                  String attributeValue = subject.getAttributeValue(subjectAttributeForDuoUsername);
                  if (!StringUtils.isBlank(attributeValue)) {
                    username = attributeValue;
                  }
                }
              }

              String duoGroupId = grouperDuoGroup != null ? grouperDuoGroup.getId() : null;
              String duoUserId =
                  !StringUtils.isBlank(username)
                      ? GrouperDuoCommands.retrieveUserIdFromUsername(username)
                      : null;

              // cant do anything if missing these things
              if (!StringUtils.isBlank(duoGroupId) && !StringUtils.isBlank(duoUserId)) {

                boolean userInDuoGroup =
                    GrouperDuoCommands.userInGroup(duoUserId, duoGroupId, true);

                boolean addUserToGroup = isMembershipAdd;

                // if update it could have unexpired
                if (isMembershipUpdate
                    && group != null
                    && subject != null
                    && group.hasMember(subject)) {
                  addUserToGroup = true;
                }

                // see if any update is needed
                if (addUserToGroup != userInDuoGroup) {
                  if (addUserToGroup) {
                    GrouperDuoCommands.assignUserToGroup(duoUserId, duoGroupId, true);
                  } else {
                    GrouperDuoCommands.removeUserFromGroup(duoUserId, duoGroupId, true);
                  }
                }
              }
            }
          }
        }

        // we successfully processed this record
      }
    } catch (Exception e) {
      changeLogProcessorMetadata.registerProblem(e, "Error processing record", currentId);
      // we made it to this -1
      return currentId - 1;
    } finally {
      if (startedGrouperSession) {
        GrouperSession.stopQuietly(grouperSession);
      }
    }
    if (currentId == -1) {
      throw new RuntimeException("Couldnt process any records");
    }

    return currentId;
  }
Example #8
0
  /**
   * Check if subject has privilege.
   *
   * <p>
   *
   * @param i BeanShell interpreter.
   * @param stack BeanShell call stack.
   * @param name Check for privilege on this {@link Group} or {@link Stem}.
   * @param subjId Check if this {@link Subject} has privilege.
   * @param priv Check this {@link AccessPrivilege}.
   * @return True if succeeds.
   * @throws GrouperShellException
   * @since 0.0.1
   */
  public static boolean invoke(
      Interpreter i, CallStack stack, String name, String subjId, Privilege priv)
      throws GrouperShellException {
    GrouperShell.setOurCommand(i, true);
    try {
      GrouperSession s = GrouperShell.getSession(i);
      Subject subj = SubjectFinder.findByIdOrIdentifier(subjId, true);
      if (Privilege.isAccess(priv)) {
        Group g = GroupFinder.findByName(s, name, true);
        if (priv.equals(AccessPrivilege.ADMIN)) {
          return g.hasAdmin(subj);
        } else if (priv.equals(AccessPrivilege.OPTIN)) {
          return g.hasOptin(subj);
        } else if (priv.equals(AccessPrivilege.OPTOUT)) {
          return g.hasOptout(subj);
        } else if (priv.equals(AccessPrivilege.READ)) {
          return g.hasRead(subj);
        } else if (priv.equals(AccessPrivilege.UPDATE)) {
          return g.hasUpdate(subj);
        } else if (priv.equals(AccessPrivilege.GROUP_ATTR_READ)) {
          return g.hasGroupAttrRead(subj);
        } else if (priv.equals(AccessPrivilege.GROUP_ATTR_UPDATE)) {
          return g.hasGroupAttrUpdate(subj);
        } else if (priv.equals(AccessPrivilege.VIEW)) {
          return g.hasView(subj);
        } else {
          throw new RuntimeException("Not expecting privilege: " + priv);
        }
      } else if (Privilege.isNaming(priv)) {
        Stem ns = StemFinder.findByName(s, name, true);
        if (priv.equals(NamingPrivilege.CREATE)) {
          return ns.hasCreate(subj);
        } else if (priv.equals(NamingPrivilege.STEM_ATTR_READ)) {
          return ns.hasStemAttrRead(subj);
        } else if (priv.equals(NamingPrivilege.STEM_ATTR_UPDATE)) {
          return ns.hasStemAttrUpdate(subj);
        } else if (priv.equals(NamingPrivilege.STEM) || priv.equals(NamingPrivilege.STEM_ADMIN)) {
          return ns.hasStemAdmin(subj);
        } else {
          throw new RuntimeException("Not expecting privilege: " + priv);
        }
      } else if (Privilege.isAttributeDef(priv)) {
        AttributeDef attributeDef = AttributeDefFinder.findByName(name, true);
        if (priv.equals(AttributeDefPrivilege.ATTR_ADMIN)) {
          return attributeDef.getPrivilegeDelegate().hasAttrAdmin(subj);
        } else if (priv.equals(AttributeDefPrivilege.ATTR_OPTIN)) {
          return attributeDef.getPrivilegeDelegate().hasAttrOptin(subj);
        } else if (priv.equals(AttributeDefPrivilege.ATTR_OPTOUT)) {
          return attributeDef.getPrivilegeDelegate().hasAttrOptout(subj);
        } else if (priv.equals(AttributeDefPrivilege.ATTR_READ)) {
          return attributeDef.getPrivilegeDelegate().hasAttrRead(subj);
        } else if (priv.equals(AttributeDefPrivilege.ATTR_UPDATE)) {
          return attributeDef.getPrivilegeDelegate().hasAttrUpdate(subj);
        } else if (priv.equals(AttributeDefPrivilege.ATTR_DEF_ATTR_READ)) {
          return attributeDef.getPrivilegeDelegate().hasAttrDefAttrRead(subj);
        } else if (priv.equals(AttributeDefPrivilege.ATTR_DEF_ATTR_UPDATE)) {
          return attributeDef.getPrivilegeDelegate().hasAttrDefAttrUpdate(subj);
        } else if (priv.equals(AttributeDefPrivilege.ATTR_VIEW)) {
          return attributeDef.getPrivilegeDelegate().hasAttrView(subj);
        } else {
          throw new RuntimeException("Not expecting privilege: " + priv);
        }

      } else {
        throw new RuntimeException("Invalid privilege type: " + priv);
      }
    } catch (GroupNotFoundException eGNF) {
      GrouperShell.error(i, eGNF);
    } catch (StemNotFoundException eNSNF) {
      GrouperShell.error(i, eNSNF);
    } catch (SubjectNotFoundException eSNF) {
      GrouperShell.error(i, eSNF);
    } catch (SubjectNotUniqueException eSNU) {
      GrouperShell.error(i, eSNU);
    }
    return false;
  } // public static boolean invoke(i, stack, name, subjId, priv)