/**
   * Apply the 'search by role' filter to the lucene query string.
   *
   * @param parametersMap
   * @param filters
   */
  protected void buildSearchByRoleQuery(Map<String, String> parametersMap, List<String> filters) {
    SearchableRole role =
        SearchableRole.valueOf(getSearchParam(parametersMap, REQUEST_PARAMETERS.role.toString()));
    String userid = getSearchParam(parametersMap, REQUEST_PARAMETERS.userid.toString());
    AuthorizableManager authorizableManager = null;
    Session adminSession = null;
    try {
      adminSession = repository.loginAdministrative();
      authorizableManager = adminSession.getAuthorizableManager();
      Authorizable au = authorizableManager.findAuthorizable(userid);
      List<Authorizable> groups = AuthorizableUtil.getUserFacingGroups(au, authorizableManager);
      groups.add(au);

      List<String> groupStrs = new ArrayList<String>(groups.size());
      for (Authorizable memberAuthz : groups) {
        groupStrs.add(ClientUtils.escapeQueryChars(memberAuthz.getId()));
      }

      filters.add(String.format(ROLE_TEMPLATE, role.toString(), JOINER_OR.join(groupStrs)));
      adminSession.logout();
    } catch (ClientPoolException e) {
      throw new RuntimeException(e);
    } catch (StorageClientException e) {
      throw new RuntimeException(e);
    } catch (AccessDeniedException e) {
      throw new RuntimeException(e);
    } finally {
      SparseUtils.logoutQuietly(adminSession);
    }
  }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.sakaiproject.nakamura.api.personal.PersonalTrackingStore#recordActivity(java.lang.String,
  *     java.lang.String, java.lang.String, java.lang.String, java.util.Date)
  */
 public void recordActivity(
     String resourceId,
     String resourceType,
     String activityType,
     String userId,
     Calendar timestamp) {
   Session session = null;
   try {
     session = repository.loginAdministrative();
     final ContentManager cm = session.getContentManager();
     final String trackingNodePath = "/activity/" + resourceType + "/" + resourceId;
     Content trackingNode = null;
     if (cm.exists(trackingNodePath)) {
       trackingNode = cm.get(trackingNodePath);
     } else {
       trackingNode = new Content(trackingNodePath, new HashMap<String, Object>());
     }
     if (!trackingNode.hasProperty("count")) {
       trackingNode.setProperty("count", BigDecimal.ZERO);
     }
     if (!trackingNode.hasProperty("sling:resourceType")) {
       trackingNode.setProperty("sling:resourceType", "sakai/resource-activity");
     }
     final String generatedNodeName =
         Base64.encodeBase64URLSafeString(asShorterByteArray(UUID.randomUUID()));
     final String activityNodePath = trackingNodePath + "/" + generatedNodeName;
     Content activityNode = null;
     if (cm.exists(activityNodePath)) {
       activityNode = cm.get(activityNodePath);
     } else {
       activityNode = new Content(activityNodePath, new HashMap<String, Object>());
     }
     BigDecimal activityCount = (BigDecimal) trackingNode.getProperty("count");
     activityNode.setProperty("sling:resourceType", "sakai/resource-update");
     trackingNode.setProperty("count", activityCount.add(BigDecimal.ONE));
     activityNode.setProperty("resourceId", resourceId);
     activityNode.setProperty("resourcetype", resourceType);
     activityNode.setProperty("activitytype", activityType);
     activityNode.setProperty("timestamp", timestamp);
     activityNode.setProperty("userid", userId);
     cm.update(activityNode);
     cm.update(trackingNode);
   } catch (AccessDeniedException e) {
     LOG.error(e.getLocalizedMessage(), e);
   } catch (StorageClientException e) {
     LOG.error(e.getLocalizedMessage(), e);
   } finally {
     if (session != null) {
       try {
         session.logout();
       } catch (ClientPoolException e) {
         LOG.error(e.getLocalizedMessage(), e);
         throw new IllegalStateException(e);
       }
     }
   }
 }
 /** Return the administrative session and close it. */
 private void ungetSession(final Session session) {
   if (session != null) {
     try {
       session.logout();
     } catch (Throwable t) {
       LOGGER.error("Unable to log out of session: " + t.getMessage(), t);
     }
   }
 }
 public CreateContentPoolServletTest()
     throws ClientPoolException, StorageClientException, AccessDeniedException,
         ClassNotFoundException {
   MockitoAnnotations.initMocks(this);
   BaseMemoryRepository baseMemoryRepository = new BaseMemoryRepository();
   repository = baseMemoryRepository.getRepository();
   Session session = repository.loginAdministrative();
   AuthorizableManager authorizableManager = session.getAuthorizableManager();
   authorizableManager.createUser("ieb", "Ian Boston", "test", ImmutableMap.of("x", (Object) "y"));
   org.sakaiproject.nakamura.api.lite.authorizable.Authorizable authorizable =
       authorizableManager.findAuthorizable("ieb");
   System.err.println("Got ieb as " + authorizable);
   session.logout();
 }
 public void process(FilterChain chain, Request request, Response response) {
   try {
     chain.process(request, response);
     for (Session s : tracker.get()) {
       LOGGER.debug("Committing {} ", s);
       s.commit();
     }
   } finally {
     Set<Session> sessions = tracker.get();
     for (Session s : sessions) {
       try {
         LOGGER.debug("Logout {} ", s);
         s.logout();
       } catch (ClientPoolException e) {
         LOGGER.error(e.getMessage(), e);
       }
     }
     sessions.clear();
   }
 }
Exemple #6
0
  /**
   * Writes commentCount of content
   *
   * @param node
   * @param session
   * @param write
   * @throws RepositoryException
   * @throws JSONException
   */
  public static void writeCommentCountProperty(
      Content content,
      org.sakaiproject.nakamura.api.lite.Session session,
      JSONWriter writer,
      Repository repository)
      throws StorageClientException, JSONException {

    int commentCount = 0;
    String COMMENTCOUNT = "commentCount";

    if (content.hasProperty(COMMENTCOUNT)) {
      commentCount = (Integer) content.getProperty(COMMENTCOUNT);
    } else {
      // no commentCount property on Content, then evaluate count and add property
      Content comments = null;
      org.sakaiproject.nakamura.api.lite.Session adminSession = null;
      try {
        comments = session.getContentManager().get(content.getPath() + "/comments");
        if (comments != null) {
          commentCount = Iterables.size(comments.listChildPaths());
        }
        content.setProperty(COMMENTCOUNT, commentCount);
        // save property
        adminSession = repository.loginAdministrative();
        ContentManager adminContentManager = adminSession.getContentManager();
        adminContentManager.update(content);
      } catch (org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException e) {
        log.error(e.getMessage(), e);
      } finally {
        if (adminSession != null) {
          try {
            adminSession.logout();
          } catch (Exception e) {
            log.error("Could not logout administrative session.");
          }
        }
      }
    }
    writer.key(COMMENTCOUNT);
    writer.value(commentCount);
  }
  @SuppressWarnings("unchecked")
  public void onMessage(Message message) {
    log.debug("Receiving a message on {} : {}", SyncJMSMessageProducer.QUEUE_NAME, message);
    try {

      String topic = message.getJMSType();
      String groupId = (String) message.getStringProperty("path");

      String operation = "UNKNOWN";

      // A group was DELETED
      if ("org/sakaiproject/nakamura/lite/authorizables/DELETE".equals(topic)
          && config.getDeletesEnabled()) {
        Map<String, Object> attributes =
            (Map<String, Object>) message.getObjectProperty(StoreListener.BEFORE_EVENT_PROPERTY);
        grouperManager.deleteGroup(groupId, attributes);
        operation = "DELETED";
      }

      // A new group was ADDED or an existing group was UPDATED
      if ("org/sakaiproject/nakamura/lite/authorizables/ADDED".equals(topic)
          || "org/sakaiproject/nakamura/lite/authorizables/UPDATED".equals(topic)) {
        // These events should be under org/sakaiproject/nakamura/lite/authorizables/UPDATED
        // http://jira.sakaiproject.org/browse/KERN-1795
        String membersAdded =
            (String) message.getStringProperty(GrouperEventUtils.MEMBERS_ADDED_PROP);
        if (membersAdded != null) {
          // membership adds can be attached to the same event for the group add.
          grouperManager.createGroup(groupId, config.getGroupTypes());
          grouperManager.addMemberships(
              groupId, Arrays.asList(StringUtils.split(membersAdded, ",")));
          operation = "ADD_MEMBERS";
        }

        String membersRemoved =
            (String) message.getStringProperty(GrouperEventUtils.MEMBERS_REMOVED_PROP);
        if (membersRemoved != null) {
          grouperManager.removeMemberships(
              groupId, Arrays.asList(StringUtils.split(membersRemoved, ",")));
          operation = "REMOVE_MEMBERS";
        }

        if (membersAdded == null && membersRemoved == null) {
          org.sakaiproject.nakamura.api.lite.Session repositorySession =
              repository.loginAdministrative();
          AuthorizableManager am = repositorySession.getAuthorizableManager();
          Group group = (Group) am.findAuthorizable(groupId);
          repositorySession.logout();

          if (groupId.startsWith(ContactsGrouperNameProviderImpl.CONTACTS_GROUPID_PREFIX)) {
            // TODO Why are we not getting added and removed properties on the Message
            grouperManager.createGroup(groupId, null);
            grouperManager.addMemberships(groupId, Arrays.asList(group.getMembers()));
            operation = "UPDATE CONTACTS";
          } else {
            grouperManager.createGroup(groupId, config.getGroupTypes());
            grouperManager.addMemberships(groupId, Arrays.asList(group.getMembers()));
            operation = "CREATE";
          }
        }
      }

      // The message was processed successfully. No exceptions were thrown.
      // We acknowledge the message and its removed from the queue
      message.acknowledge();

      // We got a message that we didn't know what to do with.
      if (operation.equals("UNKNOWN")) {
        log.error(
            "I don't know what to do with this topic: {}. Turn on debug logs to see the message.",
            topic);
        log.debug(message.toString());
      } else {
        log.info("Successfully processed and acknowledged. {}, {}", operation, groupId);
        log.debug(message.toString());
      }

    } catch (JMSException jmse) {
      log.error("JMSException while processing message.", jmse);
    } catch (Exception e) {
      log.error("Exception while processing message.", e);
    }
  }
  /**
   * Manipulate the member list for this file.
   *
   * <p>{@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @SuppressWarnings("unchecked")
  @Override
  protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    // fail if anonymous
    String remoteUser = request.getRemoteUser();
    if (User.ANON_USER.equals(remoteUser)) {
      response.sendError(SC_FORBIDDEN, "Anonymous users cannot update content members.");
      return;
    }
    Session session = null;
    boolean releaseSession = false;
    try {
      Resource resource = request.getResource();
      session = resource.adaptTo(Session.class);
      Content pooledContent = resource.adaptTo(Content.class);
      AccessControlManager accessControlManager = session.getAccessControlManager();
      AuthorizableManager authorizableManager = session.getAuthorizableManager();
      User thisUser = authorizableManager.getUser();
      if (!accessControlManager.can(
          thisUser, Security.ZONE_CONTENT, pooledContent.getPath(), Permissions.CAN_READ)) {
        response.sendError(SC_FORBIDDEN, "Insufficient permission to read this content.");
      }

      Map<String, Object> properties = pooledContent.getProperties();
      String[] managers =
          StorageClientUtils.nonNullStringArray(
              (String[]) properties.get(POOLED_CONTENT_USER_MANAGER));
      String[] editors =
          StorageClientUtils.nonNullStringArray(
              (String[]) properties.get(POOLED_CONTENT_USER_EDITOR));
      String[] viewers =
          StorageClientUtils.nonNullStringArray(
              (String[]) properties.get(POOLED_CONTENT_USER_VIEWER));

      Set<String> managerSet = Sets.newHashSet(managers);
      Set<String> editorSet = Sets.newHashSet(editors);
      Set<String> viewerSet = Sets.newHashSet(viewers);

      List<String> removeViewers =
          Arrays.asList(
              StorageClientUtils.nonNullStringArray(request.getParameterValues(":viewer@Delete")));
      List<String> removeManagers =
          Arrays.asList(
              StorageClientUtils.nonNullStringArray(request.getParameterValues(":manager@Delete")));
      List<String> removeEditors =
          Arrays.asList(
              StorageClientUtils.nonNullStringArray(request.getParameterValues(":editor@Delete")));
      List<String> addViewers =
          Arrays.asList(
              StorageClientUtils.nonNullStringArray(request.getParameterValues(":viewer")));
      List<String> addManagers =
          Arrays.asList(
              StorageClientUtils.nonNullStringArray(request.getParameterValues(":manager")));
      List<String> addEditors =
          Arrays.asList(
              StorageClientUtils.nonNullStringArray(request.getParameterValues(":editor")));

      if (!accessControlManager.can(
          thisUser, Security.ZONE_CONTENT, pooledContent.getPath(), Permissions.CAN_WRITE)) {
        if (!addManagers.isEmpty()) {
          response.sendError(SC_FORBIDDEN, "Non-managers may not add managers to content.");
          return;
        }

        for (String name : removeManagers) {
          // asking to remove managers who don't exist is harmless
          if (managerSet.contains(name)) {
            response.sendError(SC_FORBIDDEN, "Non-managers may not remove managers from content.");
            return;
          }
        }

        if (addViewers.contains(User.ANON_USER) || addViewers.contains(Group.EVERYONE)) {
          response.sendError(
              SC_FORBIDDEN, "Non-managers may not add 'anonymous' or 'everyone' as viewers.");
          return;
        }

        if (addEditors.contains(User.ANON_USER) || addEditors.contains(Group.EVERYONE)) {
          response.sendError(
              SC_FORBIDDEN, "Non-managers may not add 'anonymous' or 'everyone' as editors.");
          return;
        }

        for (String name : removeViewers) {
          if (!thisUser.getId().equals(name)) {
            Authorizable viewer = authorizableManager.findAuthorizable(name);
            if (viewer != null
                && !accessControlManager.can(
                    thisUser, Security.ZONE_AUTHORIZABLES, name, Permissions.CAN_WRITE)) {
              response.sendError(
                  SC_FORBIDDEN,
                  "Non-managers may not remove any viewer other than themselves or a group which they manage.");
            }
          }
        }

        // the request has passed all the rules that govern non-manager users
        // so we'll grant an administrative session
        session = session.getRepository().loginAdministrative();
        releaseSession = true;
      }
      List<AclModification> aclModifications = Lists.newArrayList();

      for (String addManager : addManagers) {
        if ((addManager.length() > 0) && !managerSet.contains(addManager)) {
          managerSet.add(addManager);
          AclModification.addAcl(true, Permissions.CAN_MANAGE, addManager, aclModifications);
        }
      }

      for (String removeManager : removeManagers) {
        if ((removeManager.length() > 0) && managerSet.contains(removeManager)) {
          managerSet.remove(removeManager);
          AclModification.removeAcl(true, Permissions.CAN_MANAGE, removeManager, aclModifications);
        }
      }

      for (String addEditor : addEditors) {
        if ((addEditor.length() > 0) && !editorSet.contains(addEditor)) {
          editorSet.add(addEditor);
          AclModification.addAcl(true, PERMISSION_EDITOR, addEditor, aclModifications);
        }
      }

      for (String removeEditor : removeEditors) {
        if ((removeEditor.length() > 0) && editorSet.contains(removeEditor)) {
          editorSet.remove(removeEditor);
          AclModification.removeAcl(true, PERMISSION_EDITOR, removeEditor, aclModifications);
        }
      }

      for (String addViewer : addViewers) {
        if ((addViewer.length() > 0) && !viewerSet.contains(addViewer)) {
          viewerSet.add(addViewer);
          AclModification.addAcl(true, Permissions.CAN_READ, addViewer, aclModifications);
        }
      }

      for (String removeViewer : removeViewers) {
        removeViewer = removeViewer.trim();
        if ((removeViewer.length() > 0) && viewerSet.contains(removeViewer)) {
          viewerSet.remove(removeViewer);
          if (!managerSet.contains(removeViewer)) {
            AclModification.removeAcl(true, Permissions.CAN_READ, removeViewer, aclModifications);
          }
        }
      }

      updateContentMembers(session, pooledContent, viewerSet, managerSet, editorSet);
      updateContentAccess(session, pooledContent, aclModifications);

      this.authorizableCountChanger.notify(
          UserConstants.CONTENT_ITEMS_PROP,
          addViewers,
          addEditors,
          addManagers,
          removeViewers,
          removeEditors,
          removeManagers);

      response.setStatus(SC_OK);

    } catch (StorageClientException e) {
      LOGGER.error(e.getMessage());
      response.sendError(
          SC_INTERNAL_SERVER_ERROR, "StorageClientException: " + e.getLocalizedMessage());
    } catch (AccessDeniedException e) {
      response.sendError(
          SC_FORBIDDEN,
          "Insufficient permission to update content members at " + request.getRequestURI());
    } finally {
      if (session != null && releaseSession) {
        try {
          session.logout();
        } catch (ClientPoolException e) {
          LOGGER.error(e.getMessage());
        }
      }
    }
  }