Пример #1
0
 protected void getAllTasks() {
   error = null;
   errorMessage = null;
   userTasks = new ArrayList<>();
   CoreSession coreSession = getCoreSession();
   boolean filterTrashDocs = getFilterDocumentsInTrash();
   NuxeoPrincipal pal = (NuxeoPrincipal) coreSession.getPrincipal();
   TaskService taskService = Framework.getService(TaskService.class);
   List<Task> tasks = taskService.getAllCurrentTaskInstances(coreSession, getSortInfos());
   if (tasks != null) {
     for (Task task : tasks) {
       List<String> targetDocumentsIds = task.getTargetDocumentsIds();
       boolean hasTargetDocuments = targetDocumentsIds != null && !targetDocumentsIds.isEmpty();
       if (task.hasEnded() || task.isCancelled() || !hasTargetDocuments) {
         continue;
       }
       DocumentModel doc = taskService.getTargetDocumentModel(task, coreSession);
       if (doc != null) {
         if (filterTrashDocs
             && LifeCycleConstants.DELETED_STATE.equals(doc.getCurrentLifeCycleState())) {
           continue;
         } else {
           userTasks.add(new DashBoardItemImpl(task, doc, getLocale()));
         }
       } else {
         log.warn(
             String.format(
                 "User '%s' has a task of type '%s' on a missing or deleted document",
                 pal.getName(), task.getName()));
       }
     }
   }
 }
Пример #2
0
 protected void checkCurrentUserCanCreateArtifact(T artifact) {
   NuxeoPrincipal currentUser = (NuxeoPrincipal) getContext().getCoreSession().getPrincipal();
   if (!currentUser.isAdministrator()) {
     if (!currentUser.isMemberOf("powerusers") || !isAPowerUserEditableArtifact(artifact)) {
       throw new WebSecurityException("Cannot create artifact");
     }
   }
 }
 @Override
 public String findOrCreateNuxeoUser(OpenIDUserInfo userInfo) {
   NuxeoPrincipal principal =
       Framework.getService(UserMapper.class).getOrCreateAndUpdateNuxeoPrincipal(userInfo);
   if (principal != null) {
     return principal.getName();
   } else {
     return null;
   }
 }
  @Override
  public String endTask(
      CoreSession coreSession,
      NuxeoPrincipal principal,
      Task task,
      String comment,
      String eventName,
      boolean isValidated)
      throws ClientException {

    // put user comment on the task
    if (!StringUtils.isEmpty(comment)) {
      task.addComment(principal.getName(), comment);
    }

    // end the task, adding boolean marker that task was validated or
    // rejected
    task.setVariable(TaskService.VariableName.validated.name(), String.valueOf(isValidated));
    task.end(coreSession);
    coreSession.saveDocument(task.getDocument());
    // notify
    Map<String, Serializable> eventProperties = new HashMap<String, Serializable>();
    ArrayList<String> notificationRecipients = new ArrayList<String>();
    notificationRecipients.add(task.getInitiator());
    notificationRecipients.addAll(task.getActors());
    eventProperties.put(NotificationConstants.RECIPIENTS_KEY, notificationRecipients);
    // try to resolve document when notifying
    DocumentModel document = null;
    String docId = task.getVariable(TaskService.VariableName.documentId.name());
    String docRepo = task.getVariable(TaskService.VariableName.documentRepositoryName.name());
    if (coreSession.getRepositoryName().equals(docRepo)) {
      try {
        document = coreSession.getDocument(new IdRef(docId));
      } catch (Exception e) {
        log.error(
            String.format(
                "Could not fetch document with id '%s:%s' for notification", docRepo, docId),
            e);
      }
    } else {
      log.error(
          String.format(
              "Could not resolve document for notification: "
                  + "document is on repository '%s' and given session is on "
                  + "repository '%s'",
              docRepo, coreSession.getRepositoryName()));
    }

    TaskEventNotificationHelper.notifyEvent(
        coreSession, document, principal, task, eventName, eventProperties, comment, null);

    String seamEventName =
        isValidated
            ? TaskEventNames.WORKFLOW_TASK_COMPLETED
            : TaskEventNames.WORKFLOW_TASK_REJECTED;
    return seamEventName;
  }
  @Test
  public void testIntegrationTestsSetupAndTearDown() throws Exception {

    // ---------------------------------------------------------
    // Setup the integration tests environment as Administrator
    // ---------------------------------------------------------
    Blob testUserCredentialsBlob =
        (Blob)
            clientSession
                .newRequest(NuxeoDriveSetupIntegrationTests.ID)
                .set("userNames", "joe,jack")
                .execute();
    assertNotNull(testUserCredentialsBlob);

    // Check test users
    String testUserCredentials = IOUtils.toString(testUserCredentialsBlob.getStream(), "UTF-8");
    assertNotNull(testUserCredentials);
    String[] testUserCrendentialsArray = StringUtils.split(testUserCredentials, ",");
    assertEquals(2, testUserCrendentialsArray.length);
    assertTrue(testUserCrendentialsArray[0].startsWith("nuxeoDriveTestUser_joe:"));
    assertTrue(testUserCrendentialsArray[1].startsWith("nuxeoDriveTestUser_jack:"));

    // useMembersGroup is false by default
    NuxeoPrincipal joePrincipal = userManager.getPrincipal("nuxeoDriveTestUser_joe");
    assertNotNull(joePrincipal);
    assertFalse(joePrincipal.getGroups().contains("members"));
    NuxeoPrincipal jackPrincipal = userManager.getPrincipal("nuxeoDriveTestUser_jack");
    assertNotNull(jackPrincipal);
    assertFalse(jackPrincipal.getGroups().contains("members"));

    // Check test workspace
    DocumentRef testWorkspaceRef = new PathRef(TEST_WORKSPACE_PATH);
    DocumentModel testWorkspace = session.getDocument(testWorkspaceRef);
    assertEquals("Workspace", testWorkspace.getType());
    assertEquals("Nuxeo Drive Test Workspace", testWorkspace.getTitle());
    assertTrue(session.hasPermission(joePrincipal, testWorkspaceRef, SecurityConstants.WRITE));
    assertTrue(session.hasPermission(jackPrincipal, testWorkspaceRef, SecurityConstants.WRITE));

    // Create test users' personal workspaces for cleanup check
    userWorkspaceService.getUserPersonalWorkspace(
        "nuxeoDriveTestUser_joe", session.getRootDocument());
    userWorkspaceService.getUserPersonalWorkspace(
        "nuxeoDriveTestUser_jack", session.getRootDocument());
    assertNotNull(
        session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe")));
    assertNotNull(
        session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack")));

    // ----------------------------------------------------------------------
    // Setup the integration tests environment with other user names without
    // having teared it down previously => should start by cleaning it up
    // ----------------------------------------------------------------------
    testUserCredentialsBlob =
        (Blob)
            clientSession
                .newRequest(NuxeoDriveSetupIntegrationTests.ID)
                .set("userNames", "sarah")
                .set("useMembersGroup", true)
                .execute();
    assertNotNull(testUserCredentialsBlob);

    // Check cleanup
    assertNull(userManager.getPrincipal("nuxeoDriveTestUser_joe"));
    assertNull(userManager.getPrincipal("nuxeoDriveTestUser_jack"));
    // Invalid VCS cache
    session.save();
    try {
      session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe"));
      fail("User workspace should not exist.");
    } catch (ClientException e) {
      assertEquals(
          "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe",
          e.getMessage());
    }
    try {
      session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack"));
      fail("User workspace should not exist.");
    } catch (ClientException e) {
      assertEquals(
          "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack",
          e.getMessage());
    }

    // Check test users
    testUserCredentials = IOUtils.toString(testUserCredentialsBlob.getStream(), "UTF-8");
    assertNotNull(testUserCredentials);
    testUserCrendentialsArray = StringUtils.split(testUserCredentials, ",");
    assertEquals(1, testUserCrendentialsArray.length);
    assertTrue(testUserCrendentialsArray[0].startsWith("nuxeoDriveTestUser_sarah:"));

    NuxeoPrincipal sarahPrincipal = userManager.getPrincipal("nuxeoDriveTestUser_sarah");
    assertNotNull(sarahPrincipal);
    assertTrue(sarahPrincipal.getGroups().contains("members"));

    // Check test workspace
    testWorkspace = session.getDocument(testWorkspaceRef);
    assertEquals("Nuxeo Drive Test Workspace", testWorkspace.getTitle());
    assertTrue(session.hasPermission(sarahPrincipal, testWorkspaceRef, SecurityConstants.WRITE));

    // Create test users' personal workspaces for cleanup check
    userWorkspaceService.getUserPersonalWorkspace(
        "nuxeoDriveTestUser_sarah", session.getRootDocument());
    assertNotNull(
        session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah")));

    // ----------------------------------------------------------------------
    // Try to setup the integration tests environment as an unauthorized
    // user => should fail
    // ----------------------------------------------------------------------
    Session unauthorizedSession =
        automationClient.getSession("nuxeoDriveTestUser_sarah", testUserCrendentialsArray[0]);
    try {
      unauthorizedSession
          .newRequest(NuxeoDriveSetupIntegrationTests.ID)
          .set("userNames", "john,bob")
          .execute();
      fail(
          "NuxeoDrive.SetupIntegrationTests operation should not be callable by a non administrator.");
    } catch (Exception e) {
      // Expected
    }

    // ----------------------------------------------------------------------
    // Try to tear down the integration tests environment as an unauthorized
    // user => should fail
    // ----------------------------------------------------------------------
    try {
      unauthorizedSession.newRequest(NuxeoDriveTearDownIntegrationTests.ID).execute();
      fail(
          "NuxeoDrive.TearDownIntegrationTests operation should not be callable by a non administrator.");
    } catch (Exception e) {
      // Expected
    }

    // ----------------------------------------------------------------------
    // Tear down the integration tests environment as Administrator
    // ----------------------------------------------------------------------
    clientSession.newRequest(NuxeoDriveTearDownIntegrationTests.ID).execute();
    assertTrue(userManager.searchUsers("nuxeoDriveTestUser_").isEmpty());
    // Invalid VCS cache
    session.save();
    try {
      session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah"));
      fail("User workspace should not exist.");
    } catch (ClientException e) {
      assertEquals(
          "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah",
          e.getMessage());
    }
    assertFalse(session.exists(testWorkspaceRef));
  }
  @Override
  public void handle(Request req, Response res) {
    UserManager userMgr = null;
    String user = null;
    try {

      userMgr = Framework.getService(UserManager.class);
      if (userMgr == null) {
        handleError(res, "User Manager can't be loaded");
        return;
      }

      user = (String) req.getAttributes().get("username");
      if (user == null) {
        handleError(res, "you must specify an user to search");
        return;
      }
    } catch (ClientException e) {
      handleError(res, e);
      return;
    } catch (Exception e) {
      handleError(res, "User Manager can't be loaded");
      return;
    }

    try {
      DocumentModel userModel = null;
      if (user != null && !user.isEmpty()) {
        userModel = userMgr.getUserModel(user);
      }

      // build the XML response document holding the ref
      DOMDocumentFactory domfactory = new DOMDocumentFactory();
      DOMDocument resultDocument = (DOMDocument) domfactory.createDocument();

      if (userModel == null) {
        handleError(res, "User is not found");
        return;
      }

      NuxeoPrincipal principal =
          userMgr.getPrincipal((String) userModel.getProperty("user", "username"));
      Element userElement = resultDocument.addElement("user");
      userElement.addAttribute("username", principal.getName());
      userElement.addAttribute("firstName", principal.getFirstName());
      userElement.addAttribute("lastName", principal.getLastName());
      userElement.addAttribute("email", (String) userModel.getProperty("user", "email"));
      userElement.addAttribute("company", principal.getCompany());

      List<String> groups = principal.getAllGroups();
      if (groups != null && groups.size() > 0) {
        for (String groupName : groups) {
          Element groupElement = userElement.addElement("group");
          groupElement.addAttribute("name", groupName);
        }
      }

      Representation rep =
          new StringRepresentation(resultDocument.asXML(), MediaType.APPLICATION_XML);
      rep.setCharacterSet(CharacterSet.UTF_8);
      res.setEntity(rep);
    } catch (ClientException e) {
      handleError(res, e);
    }
  }
Пример #7
0
 @Override
 protected NuxeoPrincipal updateArtifact(NuxeoPrincipal principal) {
   um.updateUser(principal.getModel());
   return um.getPrincipal(principal.getName());
 }
Пример #8
0
 protected static String newSessionId(String repositoryName, NuxeoPrincipal principal) {
   return repositoryName + '/' + principal.getName() + '#' + SID_COUNTER.incrementAndGet();
 }