Example #1
0
 public static boolean createLink(
     Content content, String link, org.sakaiproject.nakamura.api.lite.Session session)
     throws org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException,
         StorageClientException {
   String userId = session.getUserId();
   if (User.ANON_USER.equals(userId)) {
     throw new org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException(
         Security.ZONE_CONTENT, link, "Cant create a link", userId);
   }
   ContentManager contentManager = session.getContentManager();
   Content linkNode = contentManager.get(link);
   if (linkNode == null) {
     linkNode =
         new Content(
             link,
             ImmutableMap.of(
                 JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY,
                 (Object) RT_SAKAI_LINK,
                 SAKAI_LINK,
                 content.getPath()));
   } else {
     linkNode.setProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, RT_SAKAI_LINK);
     linkNode.setProperty(SAKAI_LINK, content.getPath());
   }
   contentManager.update(linkNode);
   return true;
 }
  /**
   * Process a query string to search using Solr.
   *
   * @param request
   * @param query
   * @param asAnon
   * @param rs
   * @return
   * @throws SolrSearchException
   */
  private SolrSearchResultSet processSolrQuery(
      SlingHttpServletRequest request, Query query, boolean asAnon)
      throws StorageClientException, AccessDeniedException, SolrServerException {
    String queryString = query.getQueryString();
    // apply readers restrictions.
    if (asAnon) {
      queryString = "(" + queryString + ")  AND readers:" + User.ANON_USER;
    } else {
      Session session =
          StorageClientUtils.adaptToSession(
              request.getResourceResolver().adaptTo(javax.jcr.Session.class));
      if (!User.ADMIN_USER.equals(session.getUserId())) {
        AuthorizableManager am = session.getAuthorizableManager();
        Authorizable user = am.findAuthorizable(session.getUserId());
        Set<String> readers = Sets.newHashSet();
        for (Iterator<Group> gi = user.memberOf(am); gi.hasNext(); ) {
          readers.add(gi.next().getId());
        }
        readers.add(session.getUserId());
        queryString =
            "(" + queryString + ") AND readers:(" + StringUtils.join(readers, " OR ") + ")";
      }
    }

    SolrQuery solrQuery = buildQuery(request, queryString, query.getOptions());

    SolrServer solrServer = solrSearchService.getServer();
    try {
      LOGGER.info("Performing Query {} ", URLDecoder.decode(solrQuery.toString(), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
    }
    QueryResponse response = solrServer.query(solrQuery);
    SolrDocumentList resultList = response.getResults();
    LOGGER.info("Got {} hits in {} ms", resultList.size(), response.getElapsedTime());
    return new SolrSearchResultSetImpl(response);
  }
  protected void updateGroupMembership(
      SlingHttpServletRequest request,
      Session session,
      Authorizable authorizable,
      String paramName,
      List<Modification> changes,
      Map<String, Object> toSave)
      throws AccessDeniedException, StorageClientException {
    if (authorizable instanceof Group) {
      Group group = ((Group) authorizable);
      String groupPath =
          LiteAuthorizableResourceProvider.SYSTEM_USER_MANAGER_GROUP_PREFIX + group.getId();

      boolean changed = false;

      AuthorizableManager authorizableManager = session.getAuthorizableManager();

      // first remove any members posted as ":member@Delete"
      String[] membersToDelete =
          request.getParameterValues(paramName + SlingPostConstants.SUFFIX_DELETE);
      if (membersToDelete != null) {
        toSave.put(group.getId(), group);
        LOGGER.info("Members to delete {} ", membersToDelete);
        for (String member : membersToDelete) {
          String memberId = getAuthIdFromParameter(member);
          group.removeMember(memberId);
          changed = true;
        }
      }

      Joinable groupJoin = getJoinable(group);

      // second add any members posted as ":member"
      String[] membersToAdd = request.getParameterValues(paramName);
      if (membersToAdd != null) {
        LOGGER.info("Members to add {} ", membersToAdd);
        Group peerGroup = getPeerGroupOf(group, authorizableManager, toSave);
        List<Authorizable> membersToRemoveFromPeer = new ArrayList<Authorizable>();
        for (String member : membersToAdd) {
          String memberId = getAuthIdFromParameter(member);
          Authorizable memberAuthorizable = (Authorizable) toSave.get(memberId);
          if (memberAuthorizable == null) {
            memberAuthorizable = authorizableManager.findAuthorizable(memberId);
          }
          if (memberAuthorizable != null) {
            if (!User.ADMIN_USER.equals(session.getUserId())
                && !UserConstants.ANON_USERID.equals(session.getUserId())
                && Joinable.yes.equals(groupJoin)
                && memberAuthorizable.getId().equals(session.getUserId())) {
              LOGGER.debug("Is Joinable {} {} ", groupJoin, session.getUserId());
              // we can grab admin session since group allows all users to join
              Session adminSession = getSession();
              try {
                AuthorizableManager adminAuthorizableManager =
                    adminSession.getAuthorizableManager();
                Group adminAuthGroup =
                    (Group) adminAuthorizableManager.findAuthorizable(group.getId());
                if (adminAuthGroup != null) {
                  adminAuthGroup.addMember(memberAuthorizable.getId());
                  adminAuthorizableManager.updateAuthorizable(adminAuthGroup);
                  changed = true;
                }
              } finally {
                ungetSession(adminSession);
              }
            } else {
              LOGGER.info(
                  "Group {} is not Joinable: User {} adding {}  ",
                  new Object[] {
                    group.getId(), session.getUserId(), memberAuthorizable.getId(),
                  });
              // group is restricted, so use the current user's authorization
              // to add the member to the group:

              group.addMember(memberAuthorizable.getId());
              if (LOGGER.isInfoEnabled()) {
                LOGGER.info(
                    "{} Membership now {} {} {}",
                    new Object[] {
                      group.getId(),
                      Arrays.toString(group.getMembers()),
                      Arrays.toString(group.getMembersAdded()),
                      Arrays.toString(group.getMembersRemoved())
                    });
              }
              toSave.put(group.getId(), group);
              Group gt = (Group) toSave.get(group.getId());
              if (LOGGER.isInfoEnabled()) {
                LOGGER.info(
                    "{} Membership now {} {} {}",
                    new Object[] {
                      group.getId(),
                      Arrays.toString(gt.getMembers()),
                      Arrays.toString(gt.getMembersAdded()),
                      Arrays.toString(gt.getMembersRemoved())
                    });
              }
              changed = true;
            }
            if (peerGroup != null && peerGroup.getId() != group.getId()) {
              Set<String> members = ImmutableSet.of(peerGroup.getMembers());
              if (members.contains(memberAuthorizable.getId())) {
                membersToRemoveFromPeer.add(memberAuthorizable);
              }
            }
          } else {
            LOGGER.warn("member not found {} ", memberId);
          }
        }
        if ((peerGroup != null) && (membersToRemoveFromPeer.size() > 0)) {
          for (Authorizable member : membersToRemoveFromPeer) {
            if (LOGGER.isInfoEnabled()) {
              LOGGER.info("Removing Member {} from {} ", member.getId(), peerGroup.getId());
            }
            peerGroup.removeMember(member.getId());
          }
          toSave.put(peerGroup.getId(), peerGroup);
          if (LOGGER.isInfoEnabled()) {
            LOGGER.info(
                "{} Just Updated Peer Group Membership now {} {} {}",
                new Object[] {
                  peerGroup.getId(),
                  Arrays.toString(peerGroup.getMembers()),
                  Arrays.toString(peerGroup.getMembersAdded()),
                  Arrays.toString(peerGroup.getMembersRemoved())
                });
          }
        }
      }

      if (changed) {
        // add an entry to the changes list to record the membership
        // change
        changes.add(Modification.onModified(groupPath + "/members"));
      }
    }
  }
Example #4
0
  public void createActivity(
      Session session, Content targetLocation, String userId, ActivityServiceCallback callback)
      throws AccessDeniedException, StorageClientException, ServletException, IOException {
    if (userId == null) {
      userId = session.getUserId();
    }
    if (!userId.equals(session.getUserId()) && !User.ADMIN_USER.equals(session.getUserId())) {
      throw new IllegalStateException(
          "Only Administrative sessions may act on behalf of another user for activities");
    }
    ContentManager contentManager = session.getContentManager();
    // create activityStore if it does not exist
    String path = StorageClientUtils.newPath(targetLocation.getPath(), ACTIVITY_STORE_NAME);
    if (!contentManager.exists(path)) {
      contentManager.update(
          new Content(
              path,
              ImmutableMap.<String, Object>of(
                  SLING_RESOURCE_TYPE_PROPERTY, ACTIVITY_STORE_RESOURCE_TYPE)));
      // inherit ACL from the target node, but let logged-in users write activities
      session
          .getAccessControlManager()
          .setAcl(
              Security.ZONE_CONTENT,
              path,
              new AclModification[] {
                new AclModification(
                    AclModification.grantKey(Group.EVERYONE),
                    Permissions.CAN_WRITE.getPermission(),
                    Operation.OP_AND)
              });
    }
    // create activity within activityStore
    String activityPath = StorageClientUtils.newPath(path, ActivityUtils.createId());
    String activityFeedPath = StorageClientUtils.newPath(targetLocation.getPath(), "activityFeed");

    if (!contentManager.exists(activityFeedPath)) {
      contentManager.update(new Content(activityFeedPath, null));
    }
    if (!contentManager.exists(activityPath)) {
      contentManager.update(
          new Content(
              activityPath,
              ImmutableMap.of(
                  JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY,
                  (Object) ActivityConstants.ACTIVITY_ITEM_RESOURCE_TYPE)));
    }

    Content activtyNode = contentManager.get(activityPath);
    callback.processRequest(activtyNode);

    activtyNode = contentManager.get(activityPath);
    activtyNode.setProperty(PARAM_ACTOR_ID, userId);
    activtyNode.setProperty(ActivityConstants.PARAM_SOURCE, targetLocation.getPath());

    Session adminSession = repository.loginAdministrative();
    List<String> routesStr = new LinkedList<String>();
    List<String> readers = new LinkedList<String>();
    try {
      List<ActivityRoute> routes =
          activityRouterManager.getActivityRoutes(activtyNode, adminSession);
      if (routes != null) {
        for (ActivityRoute route : routes) {
          routesStr.add(route.getDestination());
          if (route.getReaders() != null && route.getReaders().length > 0) {
            readers.addAll(Arrays.asList(route.getReaders()));
          }
        }
      }

      // store the routes as child content of the activity so we may lock it down to admin. It's
      // common for
      // the activity to be stored within the context of the content to which it pertains (e.g.,
      // within the
      // pooled content item on which the user performed the activity), therefore we could expose
      // user
      // activity routes there -- that is an exposure of potentially sensitive content such as who
      // the user's
      // connections are.
      String routesPath =
          StorageClientUtils.newPath(activtyNode.getPath(), ActivityConstants.PARAM_ROUTES);
      contentManager.update(
          new Content(
              routesPath,
              ImmutableMap.<String, Object>of(
                  ActivityConstants.PARAM_ROUTES,
                  routesStr.toArray(new String[routesStr.size()]))));
      adminSession
          .getAccessControlManager()
          .setAcl(
              Security.ZONE_CONTENT,
              routesPath,
              new AclModification[] {
                new AclModification(
                    AclModification.denyKey(User.ANON_USER),
                    Permissions.ALL.getPermission(),
                    Operation.OP_REPLACE),
                new AclModification(
                    AclModification.denyKey(Group.EVERYONE),
                    Permissions.ALL.getPermission(),
                    Operation.OP_REPLACE),
                new AclModification(
                    AclModification.denyKey(userId),
                    Permissions.ALL.getPermission(),
                    Operation.OP_REPLACE)
              });

      if (!readers.isEmpty()) {
        AclModification[] readerAcls = new AclModification[readers.size()];
        int i = 0;
        for (String reader : readers) {
          // ensure all the necessary readers/routes can read the activity
          readerAcls[i] =
              new AclModification(
                  AclModification.grantKey(reader),
                  Permissions.CAN_READ.getPermission(),
                  Operation.OP_OR);
          i++;
        }

        adminSession
            .getAccessControlManager()
            .setAcl(Security.ZONE_CONTENT, activtyNode.getPath(), readerAcls);
      }
    } finally {
      SparseUtils.logoutQuietly(adminSession);
    }

    // store the activity node
    contentManager.update(activtyNode);

    // post the asynchronous OSGi event
    final Dictionary<String, String> properties = new Hashtable<String, String>();
    properties.put(UserConstants.EVENT_PROP_USERID, userId);
    properties.put(ActivityConstants.EVENT_PROP_PATH, activityPath);
    properties.put("path", activityPath);
    properties.put("resourceType", ActivityConstants.ACTIVITY_ITEM_RESOURCE_TYPE);
    EventUtils.sendOsgiEvent(properties, LITE_EVENT_TOPIC, eventAdmin);
  }
  /**
   * Retrieves the list of members.
   *
   * <p>{@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      // Get hold of the actual file.
      Resource resource = request.getResource();
      javax.jcr.Session jcrSession = request.getResourceResolver().adaptTo(javax.jcr.Session.class);
      Session session = resource.adaptTo(Session.class);

      AuthorizableManager am = session.getAuthorizableManager();
      AccessControlManager acm = session.getAccessControlManager();
      Content node = resource.adaptTo(Content.class);
      Authorizable thisUser = am.findAuthorizable(session.getUserId());

      if (!acm.can(thisUser, Security.ZONE_CONTENT, resource.getPath(), Permissions.CAN_READ)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }

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

      boolean detailed = false;
      boolean tidy = false;
      for (String selector : request.getRequestPathInfo().getSelectors()) {
        if ("detailed".equals(selector)) {
          detailed = true;
        } else if ("tidy".equals(selector)) {
          tidy = true;
        }
      }

      // Loop over the sets and output it.
      ExtendedJSONWriter writer = new ExtendedJSONWriter(response.getWriter());
      writer.setTidy(tidy);
      writer.object();
      writer.key("managers");
      writer.array();
      for (String manager : StorageClientUtils.nonNullStringArray(managers)) {
        try {
          writeProfileMap(jcrSession, am, writer, manager, detailed);
        } catch (AccessDeniedException e) {
          LOGGER.debug("Skipping private manager [{}]", manager);
        }
      }
      writer.endArray();
      writer.key("editors");
      writer.array();
      for (String editor : StorageClientUtils.nonNullStringArray(editors)) {
        try {
          writeProfileMap(jcrSession, am, writer, editor, detailed);
        } catch (AccessDeniedException e) {
          LOGGER.debug("Skipping private editor [{}]", editor);
        }
      }
      writer.endArray();
      writer.key("viewers");
      writer.array();
      for (String viewer : StorageClientUtils.nonNullStringArray(viewers)) {
        try {
          writeProfileMap(jcrSession, am, writer, viewer, detailed);
        } catch (AccessDeniedException e) {
          LOGGER.debug("Skipping private viewer [{}]", viewer);
        }
      }
      writer.endArray();
      writer.endObject();
    } catch (JSONException e) {
      response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON.");
      LOGGER.error(e.getMessage(), e);
    } catch (StorageClientException e) {
      response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON.");
      LOGGER.error(e.getMessage(), e);
    } catch (AccessDeniedException e) {
      response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON.");
      LOGGER.error(e.getMessage(), e);
    } catch (RepositoryException e) {
      response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON.");
      LOGGER.error(e.getMessage(), e);
    }
  }