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

The following are Jave code examples for showing how to use runAsSystem() of the org.alfresco.repo.security.authentication.AuthenticationUtil class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: alfresco-repository   File: FileFolderLoaderTest.java   View Source Code Vote up 6 votes
@Override
public void tearDown() throws Exception
{
    RunAsWork<Void> tearDownWork = new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            fileFolderService.delete(hiddenFolderNodeRef);
            fileFolderService.delete(readOnlyFolderNodeRef);
            fileFolderService.delete(writeFolderNodeRef);
            // Done
            return null;
        }
    };
    AuthenticationUtil.runAsSystem(tearDownWork);

    AuthenticationUtil.popAuthentication();
}
 
Example 2
Project: alfresco-repository   File: RemoteCredentialsServiceImpl.java   View Source Code Vote up 6 votes
/**
 * Ensure the appropriate aspect is applied to the node which
 *  will hold the Remote Credentials System 
 */
private void ensureCredentialsSystemContainer(final NodeRef nodeRef)
{
    AuthenticationUtil.runAsSystem(new RunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception
        {
            if (!nodeService.hasAspect(nodeRef, RemoteCredentialsModel.ASPECT_REMOTE_CREDENTIALS_SYSTEM_CONTAINER))
            {
                // Add the aspect
                nodeService.addAspect(nodeRef, RemoteCredentialsModel.ASPECT_REMOTE_CREDENTIALS_SYSTEM_CONTAINER, null);
                
                if (logger.isDebugEnabled())
                    logger.debug("Added the Credentials Container aspect to " + nodeRef);
            }
            return null;
        }
    });
}
 
Example 3
Project: alfresco-remote-api   File: RepoService.java   View Source Code Vote up 6 votes
protected void deleteUser(final String username, final TestNetwork network)
{
	AuthenticationUtil.runAsSystem(new RunAsWork<TestPerson>()
	{
		@Override
		public TestPerson doWork() throws Exception
		{
			if (personService.personExists(username))
			{
				authenticationService.deleteAuthentication(username);
				personService.deletePerson(username);
			}
			return null;
		}
	});
}
 
Example 4
Project: alfresco-remote-api   File: RepoService.java   View Source Code Vote up 6 votes
public NodeRef addUserDescription(final String personId, final TestNetwork network, final String personDescription)
{
	return AuthenticationUtil.runAsSystem(new RunAsWork<NodeRef>()
	{
		//@Override
		public NodeRef doWork() throws Exception
		{
			NodeRef userRef = personService.getPersonOrNull(personId);
			if (userRef == null)
			{
				throw new AuthenticationException("User name does not exist: " + personId);
			}

			ContentWriter writer = contentService.getWriter(userRef, ContentModel.PROP_PERSONDESC, true);
			writer.setMimetype(MimetypeMap.MIMETYPE_HTML);
			writer.putContent(personDescription);

			log("Updated person description " + personId + (network != null ? " in network " + network : ""));
			return userRef;
		}
	});
}
 
Example 5
Project: alfresco-repository   File: InvitationServiceImpl.java   View Source Code Vote up 6 votes
@Override
public void acceptNominatedInvitation(String siteName, final String invitee, String role, String inviter)
{
    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            if (authenticationService.isAuthenticationMutable(invitee))
            {
                authenticationService.setAuthenticationEnabled(invitee, true);
            }
            return null;
        }
    });
    addSiteMembership(invitee, siteName, role, inviter, false);
}
 
Example 6
Project: alfresco-repository   File: QuickShareServiceImpl.java   View Source Code Vote up 6 votes
@Override
public void onRestoreNode(ChildAssociationRef childAssocRef)
{
    final NodeRef childNodeRef = childAssocRef.getChildRef();
    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            if (nodeService.hasAspect(childNodeRef, QuickShareModel.ASPECT_QSHARE))
            {
                // Disable audit to preserve modifier and modified date
                behaviourFilter.disableBehaviour(childNodeRef, ContentModel.ASPECT_AUDITABLE);
                try
                {
                    nodeService.removeAspect(childNodeRef, QuickShareModel.ASPECT_QSHARE);
                }
                finally
                {
                    behaviourFilter.enableBehaviour(childNodeRef, ContentModel.ASPECT_AUDITABLE);
                }
            }
            return null;
        }
    });
}
 
Example 7
Project: alfresco-repository   File: CMMDownloadTestUtil.java   View Source Code Vote up 6 votes
public DownloadStatus getDownloadStatus(final NodeRef downloadNode)
{
    return AuthenticationUtil.runAsSystem(new RunAsWork<DownloadStatus>()
    {
        @Override
        public DownloadStatus doWork() throws Exception
        {
            return transactionHelper.doInTransaction(new RetryingTransactionCallback<DownloadStatus>()
            {
                @Override
                public DownloadStatus execute() throws Throwable
                {
                    return downloadService.getDownloadStatus(downloadNode);
                }
            });
        }
    });

}
 
Example 8
Project: alfresco-remote-api   File: CustomModelImportTest.java   View Source Code Vote up 5 votes
@Override
protected void setUp() throws Exception
{
    super.setUp();
    authenticationService = getServer().getApplicationContext().getBean("AuthenticationService", MutableAuthenticationService.class);
    authorityService = getServer().getApplicationContext().getBean("AuthorityService", AuthorityService.class);
    personService = getServer().getApplicationContext().getBean("PersonService", PersonService.class);
    transactionHelper = getServer().getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    customModelService = getServer().getApplicationContext().getBean("customModelService", CustomModelService.class);

    AuthenticationUtil.clearCurrentSecurityContext();

    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            createUser(NON_ADMIN_USER);
            createUser(CUSTOM_MODEL_ADMIN);

            if (!authorityService.getContainingAuthorities(AuthorityType.GROUP, CUSTOM_MODEL_ADMIN, true).contains(
                        CustomModelServiceImpl.GROUP_ALFRESCO_MODEL_ADMINISTRATORS_AUTHORITY))
            {
                authorityService.addAuthority(CustomModelServiceImpl.GROUP_ALFRESCO_MODEL_ADMINISTRATORS_AUTHORITY, CUSTOM_MODEL_ADMIN);
            }
            return null;
        }
    });
    AuthenticationUtil.setFullyAuthenticatedUser(CUSTOM_MODEL_ADMIN);
}
 
Example 9
Project: alfresco-remote-api   File: FacetRestApiTest.java   View Source Code Vote up 5 votes
@Override protected void setUp() throws Exception
{
    super.setUp();
    authenticationService = getServer().getApplicationContext().getBean("AuthenticationService", MutableAuthenticationService.class);
    authorityService      = getServer().getApplicationContext().getBean("AuthorityService", AuthorityService.class);
    personService         = getServer().getApplicationContext().getBean("PersonService", PersonService.class);
    transactionHelper     = getServer().getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);

    AuthenticationUtil.clearCurrentSecurityContext();
    // Create test users. TODO Create these users @BeforeClass or at a testsuite scope.
    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        @Override public Void doWork() throws Exception
        {
            createUser(SEARCH_ADMIN_USER);
            createUser(NON_SEARCH_ADMIN_USER);

            if ( !authorityService.getContainingAuthorities(AuthorityType.GROUP,
                                                            SEARCH_ADMIN_USER,
                                                            true)
                                .contains(SolrFacetServiceImpl.GROUP_ALFRESCO_SEARCH_ADMINISTRATORS_AUTHORITY))
            {
                authorityService.addAuthority(SolrFacetServiceImpl.GROUP_ALFRESCO_SEARCH_ADMINISTRATORS_AUTHORITY,
                                              SEARCH_ADMIN_USER);
            }
            return null;
        }
    });
}
 
Example 10
Project: alfresco-repository   File: ArchiveAndRestoreTest.java   View Source Code Vote up 5 votes
/**
 * Ensure that nodes are tracking by deleting user
 */
public void testUserTracking()
{
    // We start with one parent assoc for the original node
    assertEquals(1, nodeService.getParentAssocs(a).size());
    
    nodeService.deleteNode(a);
    RunAsWork<List<ChildAssociationRef>> getAssocsWork = new RunAsWork<List<ChildAssociationRef>>()
    {
        @Override
        public List<ChildAssociationRef> doWork() throws Exception
        {
            return nodeService.getChildrenByName(
                    archiveStoreRootNodeRef,
                    ContentModel.ASSOC_ARCHIVE_USER_LINK,
                    Collections.singletonList(AuthenticationUtil.getFullyAuthenticatedUser()));
        }
    };
    List<ChildAssociationRef> assocs = AuthenticationUtil.runAsSystem(getAssocsWork);
    assertEquals("Expected exactly one child association for current user", 1, assocs.size());
    
    // The archived node must have two parents
    assertEquals(2, nodeService.getParentAssocs(a_).size());
    
    // Now restore
    nodeService.restoreNode(a_, null, null, null);
    
    // We should be back to a single parent association
    assertEquals(1, nodeService.getParentAssocs(a).size());
}
 
Example 11
Project: alfresco-remote-api   File: PeopleImpl.java   View Source Code Vote up 5 votes
@Override
public void requestPasswordReset(String userId, String client)
{
    // Validate the userId and the client
    checkRequiredField("userId", userId);
    checkRequiredField("client", client);

    // This is an un-authenticated API call so we wrap it to run as System
    AuthenticationUtil.runAsSystem(() -> {
        try
        {
            resetPasswordService.requestReset(userId, client);
        }
        catch (ResetPasswordWorkflowInvalidUserException ex)
        {
            // we don't throw an exception.
            // For security reason (prevent the attackers to determine that userId exists in the system or not),
            // the endpoint returns a 202 response if the userId does not exist or
            // if the user is disabled by an Administrator.
            if (LOGGER.isDebugEnabled())
            {
                LOGGER.debug("Invalid user. " + ex.getMessage());
            }
        }

        return null;
    });
}
 
Example 12
Project: alfresco-repository   File: CheckOutCheckInServiceImplTest.java   View Source Code Vote up 5 votes
private void createPerson(String userName)
{
    // if user with given user name doesn't already exist then create user
    if (this.authenticationService.authenticationExists(userName) == false)
    {
        // create user
        this.authenticationService.createAuthentication(userName, "password".toCharArray());
    }

    // if person node with given user name doesn't already exist then create
    // person
    if (this.personService.personExists(userName) == false)
    {
        // create person properties
        final PropertyMap personProps = new PropertyMap();
        personProps.put(ContentModel.PROP_USERNAME, userName);
        personProps.put(ContentModel.PROP_FIRSTNAME, userName);
        personProps.put(ContentModel.PROP_LASTNAME, userName);
        personProps.put(ContentModel.PROP_EMAIL, userName + "@gmail.com");
        personProps.put(ContentModel.PROP_JOBTITLE, "jobtitle");
        personProps.put(ContentModel.PROP_ORGANIZATION, "org");

        // create person node for user
        AuthenticationUtil.runAsSystem(new RunAsWork<NodeRef>()
        {
            @Override
            public NodeRef doWork() throws Exception
            {
                return personService.createPerson(personProps);
            }
        });
    }
}
 
Example 13
Project: alfresco-repository   File: EmailServiceImpl.java   View Source Code Vote up 4 votes
/**
 * Method determines target node by recipient e-mail address.
 * 
 * @param recipient         An e-mail address of a recipient
 * @return                  Reference to the target node
 * @throws                  EmailMessageException is thrown if the target node couldn't be determined by some reasons.
 */
private NodeRef getTargetNode(String recipient)
{
    if (logger.isDebugEnabled())
    {
        logger.debug("getTarget node for" + recipient);
    }
    if (recipient == null || recipient.length() == 0)
    {
        throw new EmailMessageException(ERR_INVALID_NODE_ADDRESS, recipient);
    }
    String[] parts = recipient.split("@");
    if (parts.length != 2)
    {
        throw new EmailMessageException(ERR_INVALID_NODE_ADDRESS, recipient);
    }
    
    String alias = parts[0];
    
    /*
     * First lookup via the attributes service
     * 
     * Then lookup by search service - may be old data prior to attributes service
     * 
     * Then see if we can find a node by dbid
     */
    
    // Lookup via the attributes service
    NodeRef ref = (NodeRef)getAttributeService().getAttribute(AliasableAspect.ALIASABLE_ATTRIBUTE_KEY_1, AliasableAspect.ALIASABLE_ATTRIBUTE_KEY_2, AliasableAspect.normaliseAlias(alias));
    
    if(ref != null)
    {
        if(logger.isDebugEnabled())
        {
            logger.debug("found email alias via attribute service alias =" + alias);
        }
        return ref;
    }

    // Ok, alias wasn't found, let's try to interpret recipient address as 'node-bdid' value
    try
    {
        Long nodeId = Long.parseLong(parts[0]);

        // Get recipient by system account
        NodeRef byNodeId = AuthenticationUtil.runAsSystem(() -> nodeService.getNodeRef(nodeId));

        if(byNodeId != null)
        {
            if(logger.isDebugEnabled())
            {
                logger.debug("found email alias via node service =" + alias);
            }
            return byNodeId;
        }
    }
    catch (NumberFormatException ne)
    {
    }
    
    throw new EmailMessageException(ERR_INVALID_NODE_ADDRESS, recipient);
}
 
Example 14
Project: alfresco-remote-api   File: CustomModelImportTest.java   View Source Code Vote up 4 votes
@Override
public void tearDown() throws Exception
{
    for (File file : tempFiles)
    {
        file.delete();
    }

    transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            for (String modelName : importedModels)
            {
                customModelService.deleteCustomModel(modelName);
            }
            return null;
        }
    });

    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
            {
                public Void execute() throws Throwable
                {
                    deleteUser(NON_ADMIN_USER);
                    deleteUser(CUSTOM_MODEL_ADMIN);
                    return null;
                }
            });
            return null;
        }
    });

    AuthenticationUtil.clearCurrentSecurityContext();

    super.tearDown();
}
 
Example 15
Project: alfresco-remote-api   File: PeopleImpl.java   View Source Code Vote up 4 votes
private Person getPersonWithProperties(String personId, List<String> include)
{
    Person person = null;
    NodeRef personNode = personService.getPerson(personId, false);
    if (personNode != null)
    {
        Map<QName, Serializable> nodeProps = nodeService.getProperties(personNode);
        processPersonProperties(personId, nodeProps);
        // TODO this needs to be run as admin but should we do this here?
        final String pId = personId;
        Boolean enabled = AuthenticationUtil.runAsSystem(new RunAsWork<Boolean>()
        {
            public Boolean doWork() throws Exception
            {
                return authenticationService.getAuthenticationEnabled(pId);
            }
        });
        person = new Person(personNode, nodeProps, enabled);

        // Remove the temporary property used to help inline the person description content property.
        // It may be accessed from the person object (person.getDescription()).
        nodeProps.remove(Person.PROP_PERSON_DESCRIPTION);

        // Expose properties
        if (include.contains(PARAM_INCLUDE_PROPERTIES))
        {
            // Note that custProps may be null.
            Map<String, Object> custProps = nodes.mapFromNodeProperties(nodeProps, new ArrayList<>(), new HashMap<>(), EXCLUDED_NS, EXCLUDED_PROPS);
            person.setProperties(custProps);
        }
        if (include.contains(PARAM_INCLUDE_ASPECTNAMES))
        {
            // Expose aspect names
            Set<QName> aspects = nodeService.getAspects(personNode);
            person.setAspectNames(nodes.mapFromNodeAspects(aspects, EXCLUDED_NS, EXCLUDED_ASPECTS));
        }
        
        // get avatar information
        if (hasAvatar(personNode))
        {
            try
            {
                NodeRef avatar = getAvatar(personId);
                person.setAvatarId(avatar);
            }
            catch (EntityNotFoundException e)
            {
                // shouldn't happen, but ok
            }
        }
    }
    else
    {
        throw new EntityNotFoundException(personId);
    }

    return person;
}
 
Example 16
Project: alfresco-repository   File: QuickShareServiceIntegrationTest.java   View Source Code Vote up 4 votes
private Serializable getProperty(NodeRef nodeRef, QName property)
{
    return AuthenticationUtil.runAsSystem(() -> nodeService.getProperty(nodeRef, property));
}
 
Example 17
Project: alfresco-repository   File: QuickShareServiceImpl.java   View Source Code Vote up 4 votes
public void beforeDeleteNode(final NodeRef beforeDeleteNodeRef)
{
    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            String sharedId = (String)nodeService.getProperty(beforeDeleteNodeRef, QuickShareModel.PROP_QSHARE_SHAREDID);
            if (sharedId != null)
            {
                try
                {
                    Pair<String, NodeRef> pair = getTenantNodeRefFromSharedId(sharedId);

                    @SuppressWarnings("unused")
                    final String tenantDomain = pair.getFirst();
                    final NodeRef nodeRef = pair.getSecond();

                    // note: deleted nodeRef might not match, eg. for upload new version -> checkin -> delete working copy
                    if (nodeRef.equals(beforeDeleteNodeRef))
                    {
                        // Disable audit to preserve modifier and modified date
                        behaviourFilter.disableBehaviour(nodeRef, ContentModel.ASPECT_AUDITABLE);
                        try
                        {
                            nodeService.removeAspect(nodeRef, QuickShareModel.ASPECT_QSHARE);
                        }
                        finally
                        {
                            behaviourFilter.enableBehaviour(nodeRef, ContentModel.ASPECT_AUDITABLE);
                        }
                        removeSharedId(sharedId);
                    }
                }
                catch (InvalidSharedIdException ex)
                {
                    logger.warn("Couldn't find shareId, " + sharedId + ", attributes for node " + beforeDeleteNodeRef);
                }
            }
            return null;
        }
    });
}
 
Example 18
Project: alfresco-repository   File: QuickShareServiceIntegrationTest.java   View Source Code Vote up 4 votes
private ScheduledPersistedAction getSchedule(final QuickShareLinkExpiryAction linkExpiryAction)
{
    return AuthenticationUtil.runAsSystem(
                () -> scheduledPersistedActionService.getSchedule(linkExpiryAction));
}
 
Example 19
Project: alfresco-repository   File: SiteServiceImplTest.java   View Source Code Vote up 4 votes
/**
 * ALF-1017 - Non sites in the Sites Space container shouldn't
 *  break the listing methods
 */
public void testALF_1017_nonSitesInSitesSpace() throws Exception
{
   // Initially listing is fine
   List<SiteInfo> sites = this.siteService.listSites(null, null);
   assertNotNull("sites list was null.", sites);
   final int preexistingSitesCount = sites.size();
   
   // Create some sites
   SiteInfo site1 = this.siteService.createSite(TEST_SITE_PRESET, "mySiteOne", TEST_TITLE, TEST_DESCRIPTION, SiteVisibility.PUBLIC);
   SiteInfo site2 = this.siteService.createSite(TEST_SITE_PRESET, "mySiteTwo", TEST_TITLE, TEST_DESCRIPTION, SiteVisibility.PRIVATE);

   // Listing is still ok
   sites = this.siteService.listSites(null, null);
   assertNotNull("sites list was null.", sites);
   assertEquals(preexistingSitesCount+2, sites.size());
   
   // Now add a random folder, and a random document to the sites root
   final NodeRef sitesSpace = this.nodeService.getPrimaryParent(site1.getNodeRef()).getParentRef();
   final NodeRef folder = AuthenticationUtil.runAsSystem(new RunAsWork<NodeRef>() {
       @Override
       public NodeRef doWork() throws Exception {
          return nodeService.createNode(
                sitesSpace, ContentModel.ASSOC_CONTAINS,
                QName.createQName("Folder"), ContentModel.TYPE_FOLDER
          ).getChildRef();
       }
   });
   final NodeRef document = AuthenticationUtil.runAsSystem(new RunAsWork<NodeRef>() {
       @Override
       public NodeRef doWork() throws Exception {
          return nodeService.createNode(
                sitesSpace, ContentModel.ASSOC_CONTAINS,
                QName.createQName("Document"), ContentModel.TYPE_CONTENT
          ).getChildRef();
       }
   });
   
   // Listing should still be fine, and count won't have increased
   sites = this.siteService.listSites(null, null);
   assertNotNull("sites list was null.", sites);
   assertEquals(preexistingSitesCount+2, sites.size());
   
   // Delete one site, listing still ok
   this.siteService.deleteSite(site2.getShortName());
   sites = this.siteService.listSites(null, null);
   assertNotNull("sites list was null.", sites);
   assertEquals(preexistingSitesCount+1, sites.size());
   
   // Tidy up the random nodes, listing still fine
   this.nodeService.deleteNode(folder);
   this.nodeService.deleteNode(document);
   
   sites = this.siteService.listSites(null, null);
   assertNotNull("sites list was null.", sites);
   assertEquals(preexistingSitesCount+1, sites.size());
}
 
Example 20
Project: alfresco-repository   File: FileFolderLoaderTest.java   View Source Code Vote up 4 votes
@Override
public void setUp() throws Exception
{
    // Make sure we don't get leaked threads from other tests
    AuthenticationUtil.clearCurrentSecurityContext();
    AuthenticationUtil.pushAuthentication();

    RunAsWork<Void> setUpWork = new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            fileFolderLoader = (FileFolderLoader) ctx.getBean("FileFolderLoader");
            fileFolderService = (FileFolderService) ctx.getBean("FileFolderService");
            permissionService = (PermissionService) ctx.getBean("PermissionService");
            transactionService = (TransactionService) ctx.getBean("TransactionService");
            nodeService = (NodeService) ctx.getBean("nodeService");
            NodeRef companyHomeNodeRef = fileFolderLoader.getRepository().getCompanyHome();
            NodeRef sharedHomeNodeRef = fileFolderLoader.getRepository().getSharedHome();
            List<FileInfo> sharedHomeFileInfos = fileFolderService.getNamePath(companyHomeNodeRef, sharedHomeNodeRef);
            sharedHomePath = "/" + sharedHomeFileInfos.get(0).getName();
            
            // Create a folder that will be invisible to all normal users
            FileInfo hiddenFolderInfo = fileFolderService.create(sharedHomeNodeRef, "HideThis", ContentModel.TYPE_FOLDER);
            hiddenFolderNodeRef = hiddenFolderInfo.getNodeRef();
            hiddenFolderPath = sharedHomePath + "/HideThis";
            permissionService.setInheritParentPermissions(hiddenFolderNodeRef, false);
            
            // Create a folder that will be read-only
            FileInfo readOnlyFolderInfo = fileFolderService.create(sharedHomeNodeRef, "ReadOnlyThis", ContentModel.TYPE_FOLDER);
            readOnlyFolderNodeRef = readOnlyFolderInfo.getNodeRef();
            readOnlyFolderPath = sharedHomePath + "/ReadOnlyThis";
            permissionService.setInheritParentPermissions(readOnlyFolderNodeRef, false);
            permissionService.setPermission(readOnlyFolderNodeRef, PermissionService.ALL_AUTHORITIES, PermissionService.READ, true);
            
            // Create a folder to write to
            FileInfo writeFolderInfo = fileFolderService.create(sharedHomeNodeRef, "WriteThis", ContentModel.TYPE_FOLDER);
            writeFolderNodeRef = writeFolderInfo.getNodeRef();
            writeFolderPath = sharedHomePath + "/WriteThis";
            
            // Done
            return null;
        }
    };
    AuthenticationUtil.runAsSystem(setUpWork);
}