Java Code Examples for org.alfresco.repo.security.authentication.AuthenticationUtil#pushAuthentication()

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#pushAuthentication() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileFolderLoaderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 100 files; 10 per txn
 */
@Test
public void testLoad_02() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        int created = fileFolderLoader.createFiles(
                writeFolderPath,
                100, 10, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        assertEquals("Incorrect number of files generated.", 100, created);
        // Count
        assertEquals(100, nodeService.countChildAssocs(writeFolderNodeRef, true));
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 2
Source File: FileFolderLoaderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testNoPermissionsToWriteToFolder() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser("BOB-1");
        fileFolderLoader.createFiles(
                readOnlyFolderPath,
                1, 256, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        fail("Folder is read only.  Should not be able to write to it.");
    }
    catch (AccessDeniedException e)
    {
        // Expected
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 3
Source File: FileFolderLoaderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testNoPermissionsToFindFolder() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser("BOB-1");
        fileFolderLoader.createFiles(
                hiddenFolderPath,
                0, 256, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        fail("No permissions to see folder.");
    }
    catch (AccessDeniedException e)
    {
        // Expected
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 4
Source File: TemporaryNodes.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This method creates a cm:folder NodeRef and adds it to the internal list of NodeRefs to be tidied up by the rule.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the cm:creator of the new node.
 * 
 * @param parentNode the parent node
 * @param nodeCmName the cm:name of the new node
 * @param nodeCreator the username of the person who will create the node
 * @return the newly created NodeRef.
 */
public NodeRef createFolder(final NodeRef parentNode, final String nodeCmName, final String nodeCreator)
{
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) appContextRule.getApplicationContext().getBean("retryingTransactionHelper");
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(nodeCreator);
    
    NodeRef newNodeRef = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            final NodeRef result = createNode(nodeCmName, parentNode, ContentModel.TYPE_FOLDER);
            
            return result;
        }
    });
    
    AuthenticationUtil.popAuthentication();
    
    this.temporaryNodeRefs.add(newNodeRef);
    return newNodeRef;
}
 
Example 5
Source File: SiteLoadPatch.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
  protected String applyInternal() throws Exception
  {
  	//skip sites that we don't want imported automatically
if (isDisabled()) 
{
	 if (logger.isDebugEnabled())
	 {
		 logger.debug("Load of site \"" + siteName + "\" is disabled.");
	 }
	 return I18NUtil.getMessage(MSG_SITE_LOAD_DISABLED, siteName);
}
      AuthenticationUtil.pushAuthentication();
      try
      {
          // The site service is funny about permissions,
          //  so even though we're running as the system we
          //  still need to identify us as the admin user
          AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
          
          return applyInternalImpl();
      }
      finally
      {
          AuthenticationUtil.popAuthentication();
      }
  }
 
Example 6
Source File: LockableAspectInterceptorTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void writeData(String fileName, final NodeRef fileNodeRef) 
{
    nodeService.addAspect(fileNodeRef, ContentModel.ASPECT_NO_CONTENT, null);
    // Access the content
    ContentWriter writer = fileFolderService.getWriter(fileNodeRef);

    // set content properties
    writer.guessMimetype(fileName);
    writer.guessEncoding();

    // Get the input stream from the request data
    InputStream is = getClass().getClassLoader().getResourceAsStream(
          "farmers_markets_list_2003.doc");

    // Write the new data to the content node
    writer.putContent(is);

    // write info about author
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
    this.transactionService.getRetryingTransactionHelper().doInTransaction(
    new RetryingTransactionCallback<Void>() {
       public Void execute() throws Throwable 
       {
          // Create the action
          Action action = actionService.createAction(ContentMetadataExtracter.EXECUTOR_NAME);
          try 
          {
             actionService.executeAction(action, fileNodeRef);
          }
          catch (Throwable th) 
          {
             // do nothing
          }
          return null;
       }
    });
    AuthenticationUtil.popAuthentication();
}
 
Example 7
Source File: RemoteFileFolderLoaderTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    
    this.repositoryHelper = (Repository)getServer().getApplicationContext().getBean("repositoryHelper");
    this.nodeService = (NodeService)getServer().getApplicationContext().getBean("nodeService");
    this.transactionService = (TransactionService) getServer().getApplicationContext().getBean("TransactionService");
    this.fileFolderService = (FileFolderService) getServer().getApplicationContext().getBean("FileFolderService");

    // Get the path of the shared folder home
    final NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome();
    final NodeRef sharedHomeNodeRef = repositoryHelper.getSharedHome();
    RetryingTransactionCallback<NodeRef> createFolderWork = new RetryingTransactionCallback<NodeRef>()
    {
        @Override
        public NodeRef execute() throws Throwable
        {
            List<FileInfo> sharedHomeFileInfos = fileFolderService.getNamePath(companyHomeNodeRef, sharedHomeNodeRef);
            sharedHomePath = "/" + sharedHomeFileInfos.get(0).getName();

            String folderName = UUID.randomUUID().toString();
            // Create a folder
            FileInfo folderInfo = fileFolderService.create(sharedHomeNodeRef, folderName, ContentModel.TYPE_FOLDER);
            loadHomePath = sharedHomePath + "/" + folderName;
            // Done
            return folderInfo.getNodeRef();
        }
    };
    AuthenticationUtil.pushAuthentication();            // Will be cleared later
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    loadHomeNodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(createFolderWork);
}
 
Example 8
Source File: SiteServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testCheckPermissionsAfterCopy()
        throws Exception
{
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    String groupName = AuthorityType.GROUP.getPrefixString() + "_" + GUID.generate().substring(0, 5).trim();
    String createdAuth = authorityService.createAuthority(AuthorityType.GROUP, groupName);
    NodeRef fileNode = null, 
            siteDocLib = null, 
            copiedNode = null, 
            movedNode = null;
    try
    {
        fileNode = createRepoFile();
        siteDocLib = createTestSite();
        addPermissionsToFile(fileNode, createdAuth, SiteModel.SITE_CONTRIBUTOR, true);
        checkPermissions(fileNode, createdAuth, SiteModel.SITE_CONTRIBUTOR, "before copy");
        
        copiedNode = copyToSite(fileNode, siteDocLib);
        checkPermissions(copiedNode, createdAuth, SiteModel.SITE_CONTRIBUTOR, "after copy");
        
        nodeService.deleteNode(copiedNode);
        copiedNode = null;
        checkPermissions(fileNode, createdAuth, SiteModel.SITE_CONTRIBUTOR, "before move");
        movedNode = moveToSite(fileNode, siteDocLib);
        checkPermissions(movedNode, createdAuth, SiteModel.SITE_CONTRIBUTOR, "after move");
    }
    finally
    {
        if (fileNode != null)
        {
            nodeService.deleteNode(fileNode);
        }
        if (siteDocLib != null)
        {
            nodeService.deleteNode(siteDocLib);
        }
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 9
Source File: TemporaryNodes.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * This method creates a cm:content NodeRef whose content is taken from the named Alfresco 'quick' file and adds it to the internal
 * list of NodeRefs to be tidied up by the rule.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the cm:creator of the new node.
 *
 * @param quickFileName the file name of the quick file - will also be the cm:name of the new node.
 * @param parentNode the parent node
 * @param nodeCreator the username of the person who will create the node
 * @return the newly created NodeRef.
 * @since 4.1.4
 */
public NodeRef createQuickFileByName(final String quickFileName, final NodeRef parentNode, final String nodeCreator)
{
    final MimetypeMap mimetypeService = (MimetypeMap) appContextRule.getApplicationContext().getBean("mimetypeService");
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) appContextRule.getApplicationContext().getBean("retryingTransactionHelper");
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(nodeCreator);
    
    NodeRef newNodeRef = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            final NodeRef result = createNode(quickFileName, parentNode, ContentModel.TYPE_CONTENT);
            
            File quickFile = AbstractContentTransformerTest.loadNamedQuickTestFile(quickFileName);
            
            ContentService contentService = appContextRule.getApplicationContext().getBean("contentService", ContentService.class);
            ContentWriter writer = contentService.getWriter(result, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(mimetypeService.guessMimetype(quickFileName));
            writer.setEncoding("UTF-8");
            writer.putContent(quickFile);
            
            return result;
        }
    });
    
    AuthenticationUtil.popAuthentication();
    
    this.temporaryNodeRefs.add(newNodeRef);
    return newNodeRef;
}
 
Example 10
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * ACE-2564
 */
@Test
public void testSendEmailByExternalUser() throws IOException, MessagingException
{
    final Serializable recipients = (Serializable) Arrays.asList(BRITISH_USER.getUsername());
    final String subject = "";
    final String template = "alfresco/templates/mail/test.txt.ftl";
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(EXTERNAL_USER.getUsername());
    MimeMessage message = null;


    try
    {

        // these persons should be without emails
        // testing for GROUP_EVERYONE
        
        final String tenantId = getUsersHomeTenant(BRITISH_USER.getUsername());

        // USER_6 not exist for USER_1, but he will be added to recipients
        message = TenantUtil.runAsTenant(new TenantRunAsWork<MimeMessage>()
        {
            @Override
            public MimeMessage doWork() throws Exception
            {
                return sendMessage(null, recipients, subject, template);
            }
        }, tenantId);

        Assert.assertNotNull(message);
        Assert.assertEquals("Hello 1 Jan 1970", (String) message.getContent());
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 11
Source File: TemporaryNodes.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * This method creates a cm:content NodeRef whose content is taken from an Alfresco 'quick' file and adds it to the internal
 * list of NodeRefs to be tidied up by the rule.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the cm:creator of the new node.
 * 
 * @param mimetype the MimeType of the content to put in the new node.
 * @param parentNode the parent node
 * @param nodeCmName the cm:name of the new node
 * @param nodeCreator the username of the person who will create the node
 * @param isVersionable should the new node be {@link ContentModel#ASPECT_VERSIONABLE versionable}?
 * @return the newly created NodeRef.
 */
public NodeRef createQuickFile(final String mimetype, final NodeRef parentNode, final String nodeCmName, final String nodeCreator, final boolean isVersionable)
{
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) appContextRule.getApplicationContext().getBean("retryingTransactionHelper");
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(nodeCreator);
    
    NodeRef newNodeRef = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            final NodeRef result = createNode(nodeCmName, parentNode, ContentModel.TYPE_CONTENT);
            
            if (isVersionable)
            {
                NodeService nodeService = appContextRule.getApplicationContext().getBean("nodeService", NodeService.class);
                nodeService.addAspect(result, ContentModel.ASPECT_VERSIONABLE, null);
            }
            
            File quickFile = AbstractContentTransformerTest.loadNamedQuickTestFile(getQuickResource(mimetype));
            
            ContentService contentService = appContextRule.getApplicationContext().getBean("contentService", ContentService.class);
            ContentWriter writer = contentService.getWriter(result, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(mimetype);
            writer.setEncoding("UTF-8");
            writer.putContent(quickFile);
            
            return result;
        }
    });
    
    AuthenticationUtil.popAuthentication();
    
    this.temporaryNodeRefs.add(newNodeRef);
    return newNodeRef;
}
 
Example 12
Source File: CMISTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * MNT-11727: move and rename operations should be shown as an UPDATE in the CMIS change log
 */
@Test
public void testMoveRenameWithCMISshouldBeAuditedAsUPDATE() throws Exception
{
    // setUp audit subsystem
    setupAudit();

    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    try
    {
        assertTrue("Audit is not enabled", auditSubsystem.isAuditEnabled());
        assertNotNull("CMIS audit is not enabled", auditSubsystem.getAuditApplicationByName("CMISChangeLog"));

        NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome();

        String folder = GUID.generate();
        FileInfo folderInfo = fileFolderService.create(companyHomeNodeRef, folder, ContentModel.TYPE_FOLDER);

        final String actualToken = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>()
        {
            public String execute() throws Exception
            {
                return cmisConnector.getRepositoryInfo(CmisVersion.CMIS_1_1).getLatestChangeLogToken();
            }
        }, true, false);

        String content = GUID.generate();
        FileInfo document = fileFolderService.create(folderInfo.getNodeRef(), content, ContentModel.TYPE_CONTENT);
        assertNotNull(document);
        nodeService.setProperty(document.getNodeRef(), ContentModel.PROP_NAME, content);

        Holder<String> changeLogToken = new Holder<String>();
        changeLogToken.setValue(actualToken);
        ObjectList changeLog = CMISTest.this.cmisConnector.getContentChanges(changeLogToken, new BigInteger("10"));
        List<ObjectData> events = changeLog.getObjects();
        int count = events.size();
        // it should be 3 entries: 1 for previous folder create, 1 new CREATE (for document create)
        // and 1 NEW UPDATE
        assertEquals(3, count);

        assertEquals(events.get(0).getProperties().getPropertyList().get(0).getValues().get(0), folderInfo.getNodeRef().getId());
        assertEquals(events.get(0).getChangeEventInfo().getChangeType(), ChangeType.CREATED);

        assertTrue(((String) events.get(1).getProperties().getPropertyList().get(0).getValues().get(0)).contains(document.getNodeRef().getId()));
        assertEquals(events.get(1).getChangeEventInfo().getChangeType(), ChangeType.CREATED);

        assertTrue(((String) events.get(2).getProperties().getPropertyList().get(0).getValues().get(0)).contains(document.getNodeRef().getId()));
        assertEquals(events.get(2).getChangeEventInfo().getChangeType(), ChangeType.UPDATED);

        // test rename
        final String actualToken2 = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>()
        {
            public String execute() throws Exception
            {
                return cmisConnector.getRepositoryInfo(CmisVersion.CMIS_1_1).getLatestChangeLogToken();
            }
        }, true, false);
        nodeService.setProperty(document.getNodeRef(), ContentModel.PROP_NAME, content + "-updated");

        changeLogToken = new Holder<String>();
        changeLogToken.setValue(actualToken2);
        changeLog = CMISTest.this.cmisConnector.getContentChanges(changeLogToken, new BigInteger("10"));
        events = changeLog.getObjects();
        count = events.size();
        assertEquals(2, count);
        assertEquals("Rename operation should be shown as an UPDATE in the CMIS change log", events.get(1).getChangeEventInfo().getChangeType(), ChangeType.UPDATED);

        // test move
        String targetFolder = GUID.generate();
        FileInfo targetFolderInfo = fileFolderService.create(companyHomeNodeRef, targetFolder, ContentModel.TYPE_FOLDER);

        final String actualToken3 = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>()
        {
            public String execute() throws Exception
            {
                return cmisConnector.getRepositoryInfo(CmisVersion.CMIS_1_1).getLatestChangeLogToken();
            }
        }, true, false);
        nodeService.moveNode(document.getNodeRef(), targetFolderInfo.getNodeRef(), ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS);

        changeLogToken = new Holder<String>();
        changeLogToken.setValue(actualToken3);
        changeLog = CMISTest.this.cmisConnector.getContentChanges(changeLogToken, new BigInteger("10"));
        events = changeLog.getObjects();
        count = events.size();
        assertEquals(2, count);
        assertEquals("Move operation should be shown as an UPDATE in the CMIS change log", events.get(1).getChangeEventInfo().getChangeType(), ChangeType.UPDATED);
    }
    finally
    {
        auditSubsystem.destroy();
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 13
Source File: RunAsFullyAuthenticatedRule.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override public Statement apply(final Statement base, final Description description)
{
    return new Statement()
    {
        @Override public void evaluate() throws Throwable
        {
            // Store the current authentication
            AuthenticationUtil.pushAuthentication();
            
            // First, try for a username provided on the @Test method itself.
            String runAsUser = getMethodAnnotatedUserName(description);
            
            if (runAsUser != null)
            {
                // There is a @Test method username.
                log.debug("Running as method annotation-provided user: " + runAsUser);
                log.debug("   See " + description.getClassName() + "." + description.getMethodName());
            }
            else
            {
                // There is no @Test method username, so fall back to rule-provided person.
                if (fixedUserName != null)
                {
                    runAsUser = fixedUserName;
                    log.debug("Running as username defined in this rule: " + runAsUser);
                }
                else if (personRule != null)
                {
                    runAsUser = personRule.getUsername();
                    log.debug("Running as username provided by another rule: " + runAsUser);
                }
                else
                {
                    throw new Exception("Illegal rule: must provide username or " +
                                                                    AlfrescoPerson.class.getSimpleName() + " at rule construction or else a " +
                                                                    RunAsUser.class.getSimpleName() + " annotation.");
                }
            }
            AuthenticationUtil.setFullyAuthenticatedUser(runAsUser);
            
            
            try
            {
                // Execute the test method or whatever other rules are configured further down the stack.
                base.evaluate();
            }
            finally
            {
                // After - ensure that pass or fail, the authentication is restored.
                AuthenticationUtil.popAuthentication();
            }
        }
    };
}
 
Example 14
Source File: CMISTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * MNT-14951: Test that the list of parents can be retrieved for a folder.
 */
@Test
public void testCMISGetObjectParents() throws Exception
{
    // setUp audit subsystem
    setupAudit();
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    
    try
    {
        final NodeRef folderWithTwoParents = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<NodeRef>()
        {
            @Override
            public NodeRef execute() throws Throwable
            {
                NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome();

                String folder1 = GUID.generate();
                FileInfo folderInfo1 = fileFolderService.create(companyHomeNodeRef, folder1, ContentModel.TYPE_FOLDER);
                assertNotNull(folderInfo1);
                
                String folder2 = GUID.generate();
                FileInfo folderInfo2 = fileFolderService.create(companyHomeNodeRef, folder2, ContentModel.TYPE_FOLDER);
                assertNotNull(folderInfo2);
                
                // Create folder11 as a subfolder of folder1
                String folder11 = GUID.generate();
                FileInfo folderInfo11 = fileFolderService.create(folderInfo1.getNodeRef(), folder11, ContentModel.TYPE_FOLDER);
                assertNotNull(folderInfo11);
                
                // Add folder2 as second parent for folder11
                nodeService.addChild(folderInfo2.getNodeRef(), folderInfo11.getNodeRef(), ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS);
                
                return folderInfo11.getNodeRef();
            }
        });
        
        withCmisService(new CmisServiceCallback<Void>()
        {
            @Override
            public Void execute(CmisService cmisService)
            {
                List<RepositoryInfo> repositories = cmisService.getRepositoryInfos(null);
                assertNotNull(repositories);
                assertTrue(repositories.size() > 0);
                String repositoryId = repositories.iterator().next().getId();

                List<ObjectParentData> parents = cmisService.getObjectParents(repositoryId, folderWithTwoParents.getId(), null, Boolean.FALSE, IncludeRelationships.NONE,
                                                                              "cmis:none", Boolean.FALSE, null);
                // Check if the second parent was also returned.
                assertEquals(2, parents.size());

                return null;
            }
        }, CmisVersion.CMIS_1_1);
    }
    finally
    {
        auditSubsystem.destroy();
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 15
Source File: AlfrescoCmisServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
    public void beforeCall()
    {
        AuthenticationUtil.pushAuthentication();
        if (authentication != null)
        {
            // Use the previously-obtained authentication
            AuthenticationUtil.setFullAuthentication(authentication);
        }
        else
        {
        	CallContext context = getContext();
            if (context == null)
            {
                // Service not opened, yet
                return;
            }
            // Sticky sessions?
            if (connector.openHttpSession())
            {
                // create a session -> set a cookie
                // if the CMIS client supports cookies that might help in clustered environments
                ((HttpServletRequest)context.get(CallContext.HTTP_SERVLET_REQUEST)).getSession();
            }
            
            // Authenticate
            if (authentication != null)
            {
                // We have already authenticated; just reuse the authentication
                AuthenticationUtil.setFullAuthentication(authentication);
            }
            else
            {
                // First check if we already are authenticated
                if (AuthenticationUtil.getFullyAuthenticatedUser() == null)
                {
                    // We have to go to the repo and authenticate
                    String user = context.getUsername();
                    String password = context.getPassword();
                    Authorization auth = new Authorization(user, password);
                    if (auth.isTicket())
                    {
                        connector.getAuthenticationService().validate(auth.getTicket());
                    }
                    else
                    {
                        connector.getAuthenticationService().authenticate(auth.getUserName(), auth.getPasswordCharArray());
                    }
                }
                this.authentication = AuthenticationUtil.getFullAuthentication();
            }
            
//            // TODO: How is the proxy user working.
//            //       Until we know what it is meant to do, it's not available
//            String currentUser = connector.getAuthenticationService().getCurrentUserName();
//            String user = getContext().getUsername();
//            String password = getContext().getPassword();
//            if (currentUser != null && currentUser.equals(connector.getProxyUser()))
//            {
//                if (user != null && user.length() > 0)
//                {
//                    AuthenticationUtil.setFullyAuthenticatedUser(user);
//                }
//            }
        }
    }
 
Example 16
Source File: GetChildrenCannedQueryTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unused")
public void testAspectFiltering() throws Exception
{
    NodeRef parentNodeRef = repositoryHelper.getCompanyHome();
    NodeRef nodeRef1 = null;
    NodeRef nodeRef2 = null;
    NodeRef nodeRef3 = null;
    NodeRef nodeRef4 = null;
    NodeRef nodeRef5 = null;
    NodeRef nodeRef6 = null;
    NodeRef nodeRef7 = null;
    NodeRef nodeRef8 = null;
    NodeRef nodeRef9 = null;
    NodeRef nodeRef10 = null;
    
    // Create some nodes with integer properties on which to sort, in this case cm:fiveStarRatingScheme and cm:likesRatingScheme
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    try
    {
        nodeRef1 = createContent(parentNodeRef, "node1", ContentModel.TYPE_CONTENT);
        nodeRef2 = createContent(parentNodeRef, "node2", ContentModel.TYPE_CONTENT);
        nodeRef3 = createContent(parentNodeRef, "node3", ContentModel.TYPE_CONTENT);
        nodeRef4 = createContent(parentNodeRef, "node4", ContentModel.TYPE_CONTENT);
        nodeRef5 = createContent(parentNodeRef, "node5", ContentModel.TYPE_CONTENT);
        
        nodeRef6 = createContent(parentNodeRef, "node6", ContentModel.TYPE_CONTENT);
        nodeRef7 = createContent(parentNodeRef, "node7", ContentModel.TYPE_CONTENT);
        nodeRef8 = createContent(parentNodeRef, "node8", ContentModel.TYPE_CONTENT);
        nodeRef9 = createContent(parentNodeRef, "node9", ContentModel.TYPE_CONTENT);
        nodeRef10 = createContent(parentNodeRef, "node10", ContentModel.TYPE_CONTENT);
        
        Map<QName, Serializable> props = Collections.emptyMap();
        
        nodeService.addAspect(nodeRef2, ContentModel.ASPECT_CLASSIFIABLE, props);
        nodeService.addAspect(nodeRef4, ContentModel.ASPECT_CLASSIFIABLE, props);
        nodeService.addAspect(nodeRef4, RenditionModel.ASPECT_RENDITION, props);
        nodeService.addAspect(nodeRef8, ContentModel.ASPECT_CLASSIFIABLE, props);
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
    
    // do children canned query
    PagingResults<NodeRef> results = list(parentNodeRef, -1, -1, 0);
    List<NodeRef> nodeRefs = results.getPage();
    for (NodeRef nodeRef : nodeRefs)
    {
        System.out.print(nodeRef);
        Set<QName> aspects = nodeService.getAspects(nodeRef);
        for (QName aspect : aspects)
        {
            System.out.print(" " + aspect);
        }
        System.out.println();
    }
    Set<QName> includedAspects = new HashSet<QName>(Arrays.asList(new QName[] {ContentModel.ASPECT_CLASSIFIABLE}));
    results = list(parentNodeRef, includedAspects, null, -1, -1, 0);
    assertEquals(3, results.getPage().size());

    Set<QName> excludedAspects = new HashSet<QName>(Arrays.asList(new QName[] {RenditionModel.ASPECT_RENDITION}));
    results = list(parentNodeRef, null, excludedAspects, -1, -1, 0);
    for (NodeRef result : results.getPage())
    {
        assertFalse(nodeService.getAspects(result).contains(RenditionModel.ASPECT_RENDITION));
    }

    results = list(parentNodeRef, includedAspects, excludedAspects, -1, -1, 0);
    assertEquals(2, results.getPage().size());
}
 
Example 17
Source File: CMISTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * MNT-13529: Just-installed Alfresco does not return a CMIS latestChangeLogToken
 * 
 * @throws Exception
 */
@Test
public void testMNT13529() throws Exception
{
    setupAudit();

    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    try
    {
        // Delete the entries, it simulates just installed Alfresco for reproduce the issue
        final Long appId = auditSubsystem.getAuditApplicationByName("CMISChangeLog").getApplicationId();
        RetryingTransactionCallback<Void> deletedCallback = new RetryingTransactionCallback<Void>()
        {
            public Void execute() throws Throwable
            {
                auditDAO.deleteAuditEntries(appId, null, null);
                return null;
            }
        };
        transactionService.getRetryingTransactionHelper().doInTransaction(deletedCallback);

        // Retrieve initial latestChangeLogToken
        final String initialChangeLogToken = withCmisService(new CmisServiceCallback<String>()
        {
            @Override
            public String execute(CmisService cmisService)
            {
                List<RepositoryInfo> repositories = cmisService.getRepositoryInfos(null);
                assertNotNull(repositories);
                assertTrue(repositories.size() > 0);
                RepositoryInfo repo = repositories.iterator().next();

                return repo.getLatestChangeLogToken();
            }
        }, CmisVersion.CMIS_1_1);

        assertNotNull(initialChangeLogToken);
        assertEquals("0", initialChangeLogToken);
    }
    finally
    {
        auditSubsystem.destroy();
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 18
Source File: FileFolderLoaderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 10 files; 10 per txn; force storage; identical
 */
@Test
public void testLoad_04() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        int created = fileFolderLoader.createFiles(
                writeFolderPath,
                10, 10, 1024L, 1024L, 1L, true,
                10, 256L);
        assertEquals("Incorrect number of files generated.", 10, created);
        // Count
        assertEquals(10, nodeService.countChildAssocs(writeFolderNodeRef, true));
        // Check the files
        List<FileInfo> fileInfos = fileFolderService.listFiles(writeFolderNodeRef);
        String lastText = null;
        String lastDescr = null;
        String lastUrl = null;
        for (FileInfo fileInfo : fileInfos)
        {
            NodeRef fileNodeRef = fileInfo.getNodeRef();
            // The URLs must all be unique as we wrote the physical binaries
            ContentReader reader = fileFolderService.getReader(fileNodeRef);
            assertEquals("UTF-8", reader.getEncoding());
            assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, reader.getMimetype());
            assertEquals(1024L, reader.getSize());
            if (lastUrl == null)
            {
                lastUrl = reader.getContentUrl();
            }
            else
            {
                assertNotEquals("We expect unique URLs: ", lastUrl, reader.getContentUrl());
                lastUrl = reader.getContentUrl();
            }
            // Check content
            if (lastText == null)
            {
                lastText = reader.getContentString();
            }
            else
            {
                String currentStr = reader.getContentString();
                assertEquals("All text must be identical due to same seed. ", lastText, currentStr);
                lastText = currentStr;
            }
            // Check description
            if (lastDescr == null)
            {
                lastDescr = DefaultTypeConverter.INSTANCE.convert(String.class, nodeService.getProperty(fileNodeRef, ContentModel.PROP_DESCRIPTION));
                assertEquals("cm:description length is incorrect. ", 256, lastDescr.getBytes().length);
            }
            else
            {
                String currentDescr = DefaultTypeConverter.INSTANCE.convert(String.class, nodeService.getProperty(fileNodeRef, ContentModel.PROP_DESCRIPTION));
                assertEquals("All descriptions must be identical due to varying seed. ", lastDescr, currentDescr);
                lastDescr = currentDescr;
            }
        }
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 19
Source File: HomeFolderProviderSynchronizer.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void beforeProcess() throws Throwable
{
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(userName);
}
 
Example 20
Source File: TemporarySites.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * This method creates a test site (of Alfresco type <code>st:site</code>) and one user for each of the Share Site Roles.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the creator of the new site.
 * The site and its users will be deleted automatically by the rule.
 * 
 * @param sitePreset the site preset.
 * @param visibility the Site visibility.
 * @param siteCreator the username of a user who will be used to create the site (user must exist of course).
 * @return the {@link SiteInfo} object for the newly created site.
 */
public TestSiteAndMemberInfo createTestSiteWithUserPerRole(final String siteShortName, String sitePreset, SiteVisibility visibility, String siteCreator)
{
    // create the site
    SiteInfo result = this.createSite(sitePreset, siteShortName, null, null, visibility, siteCreator);
    
    // create the users
    final RetryingTransactionHelper transactionHelper = appContextRule.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    final SiteService siteService = appContextRule.getApplicationContext().getBean("siteService", SiteService.class);
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(siteCreator);
    
    // Create users for this test site that cover the various roles.
    List<String> userNames = transactionHelper.doInTransaction(new RetryingTransactionCallback<List<String>>()
    {
        public List<String> execute() throws Throwable
        {
            List<String> users = new ArrayList<String>(4);
            
            for (String shareRole : SiteModel.STANDARD_PERMISSIONS)
            {
                final String userName = siteShortName + "_" + shareRole + "_" + GUID.generate();
                
                log.debug("Creating temporary site user " + userName);
                
                createPerson(userName);
                siteService.setMembership(siteShortName, userName, shareRole);
                users.add(userName);
                
                temporarySiteUsers.add(userName);
            }
            
            return users;
        }
    });
    
    NodeRef doclibFolder = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            return siteService.getContainer(siteShortName, SiteService.DOCUMENT_LIBRARY);
        }
    });
    
    AuthenticationUtil.popAuthentication();
     
    
    return new TestSiteAndMemberInfo(result, doclibFolder, userNames.get(0),
                                                           userNames.get(1),
                                                           userNames.get(2),
                                                           userNames.get(3));
}