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

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#runAs() . 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: NodeMonitor.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private StringBuilder calculateDisplayPath(final NodeRef nodeRef)
{
    return AuthenticationUtil.runAs(new RunAsWork<StringBuilder>()
    {
        @Override
        public StringBuilder doWork() throws Exception
        {
            // Get the full path to the file/folder node
            Path nodePath = m_nodeService.getPath(nodeRef);
            String fName = (String) m_nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);

            // Build the share relative path to the node
            StringBuilder result = new StringBuilder();
            result.append(nodePath.toDisplayPath(m_nodeService, m_permissionService));
            if ((0 == result.length()) || ('/' != (result.charAt(result.length() - 1)) && ('\\' != result.charAt(result.length() - 1))))
            {
                result.append("\\");
            }
            return result.append(fName);
        }
    }, AuthenticationUtil.SYSTEM_USER_NAME);
}
 
Example 2
Source File: ScriptSiteService.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Get a site for a provided site short name.
 * <p>
 * Returns null if the site does not exist.
 * 
 * @param shortName short name of the site
 * @return Site the site, null if does not exist
 */
public Site getSite(final String shortName)
{
    SiteInfo siteInfo = null;
    Site site = null;
    if (siteService.isSiteAdmin(AuthenticationUtil.getFullyAuthenticatedUser()))
    {
        siteInfo = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<SiteInfo>()
        {
            public SiteInfo doWork() throws Exception
            {
                return siteService.getSite(shortName);
            }
        }, AuthenticationUtil.getAdminUserName());
    }
    else
    {
        siteInfo = this.siteService.getSite(shortName);
    }

    if (siteInfo != null)
    {
        site = new Site(siteInfo, this.serviceRegistry, this.siteService, getScope());
    }
    return site;
}
 
Example 3
Source File: QuickShareServiceIntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Test for MNT-15654
 * <p> The node is created and shared by user1. Then unshared by user2
 * <p> The modifier should not change to user2 after unsharing.
 */
@Test
public void testModifierAfterUnSharing()
{
    AuthenticationUtil.runAs(new RunAsWork<Void>(){
        @Override
        public Void doWork() throws Exception
        {
            permissionService.setPermission(testNode, user2.getUsername(), PermissionService.CONSUMER, true);
            return null;
        }
    }, user1.getUsername());

    QuickShareDTO dto = share(testNode, user1.getUsername());
    unshare(dto.getId(), user2.getUsername());

    String modifier = AuthenticationUtil.runAsSystem(new RunAsWork<String>(){
        @Override
        public String doWork() throws Exception
        {
            return (String )nodeService.getProperty(testNode, ContentModel.PROP_MODIFIER);
        }
    });

    assertEquals("The modifier has changed after sharing.", user1.getUsername(), modifier);
}
 
Example 4
Source File: MultiTNodeServiceInterceptorTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void tearDown() throws Exception
{
    // If MT is disabled, then disable all tests
    if (!tenantAdminService.isEnabled())
    {
        return;
    }

    // Delete a tenant
    AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>(){
        @Override
        public Void doWork() throws Exception {
            RetryingTransactionCallback<Object> deleteTenantCallback = new RetryingTransactionCallback<Object>()
            {
                public Object execute() throws Throwable
                {
                    tenantAdminService.deleteTenant(tenant1);
                    return null;
                }
            };
            transactionService.getRetryingTransactionHelper().doInTransaction(deleteTenantCallback, false, true);
            return null;
        }
    }, AuthenticationUtil.getAdminUserName());
}
 
Example 5
Source File: DefaultRemoteUserMapper.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Normalizes a user id, taking into account existing user accounts and case sensitivity settings.
 * 
 * @param userId
 *            the user id
 * @return the string
 */
private String normalizeUserId(final String userId)
{
    if (userId == null)
    {
        return null;
    }
    String normalized = AuthenticationUtil.runAs(new RunAsWork<String>()
    {
        public String doWork() throws Exception
        {
            return personService.getUserIdentifier(userId);
        }
    }, AuthenticationUtil.getSystemUserName());
    if (logger.isTraceEnabled())
    {
        logger.trace("The normalized user name is: " + AuthenticationUtil.maskUsername(normalized) + " for user id " + AuthenticationUtil
            .maskUsername(userId));
    }
    return normalized == null ? userId : normalized;
}
 
Example 6
Source File: Site.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Saves any outstanding updates to the site details.
 * <p>
 * If properties of the site are changed and save is not called, those changes will be lost.
 */
public void save()
{
    if (this.isDirty == true)
    {
        if (siteService.isSiteAdmin(AuthenticationUtil.getFullyAuthenticatedUser()))
        {
            AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>()
            {
                public Void doWork() throws Exception
                {
                    // Update the site details as a site-admin
                    siteService.updateSite(siteInfo);
                    return null;
                }
            }, AuthenticationUtil.getAdminUserName());
        }
        else
        {
            // Update the site details
            this.siteService.updateSite(this.siteInfo);
        }
        // Reset the dirty flag
        this.isDirty = false;
    }
}
 
Example 7
Source File: ConfigurationChecker.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void onBootstrap(ApplicationEvent event)
{
    RetryingTransactionCallback<Object> checkWork = new RetryingTransactionCallback<Object>()
    {
        public Object execute() throws Throwable {
            // run as System on bootstrap
            return AuthenticationUtil.runAs(new RunAsWork<Object>()
            {
                public Object doWork()
                {
                    check();
                    return null;
                }
            }, AuthenticationUtil.getSystemUserName());
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(checkWork, true);
}
 
Example 8
Source File: FacetRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testSearchAdminCanGetFacets() throws Exception
{
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @Override public Void doWork() throws Exception
        {
            Response rsp = sendRequest(new GetRequest(GET_FACETS_URL), 200);

            String contentAsString = rsp.getContentAsString();
            JSONObject jsonRsp = new JSONObject(new JSONTokener(contentAsString));

            // FIXME The JSON payload should be contained within a 'data' object.
            JSONArray facetsArray = (JSONArray)jsonRsp.get(FACETS);
            assertNotNull("JSON 'facets' array was null", facetsArray);

            // We'll not add any further assertions on the JSON content. If we've
            // got valid JSON at this point, then that's good enough.
            return null;
        }
    }, SEARCH_ADMIN_USER);
}
 
Example 9
Source File: HomeFolderProviderSynchronizerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void deleteTenant(final String tenantDomain) throws Exception
{
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            if (tenantAdminService.existsTenant(tenantDomain))
            {
                // Can't delete so disable
                // tenantAdminService.deleteTenant(tenantDomain);

                if (tenantAdminService.isEnabledTenant(tenantDomain))
                {
                    tenantAdminService.disableTenant(tenantDomain);
                }
            }
            return null;
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example 10
Source File: QuickShareServiceIntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, Object> getMetadata(final NodeRef nodeRef, AlfrescoPerson user) {
	Map<String, Object> container = AuthenticationUtil.runAs(new RunAsWork<Map<String, Object>>()
       {
           @Override
           public Map<String, Object> doWork() throws Exception
           {
           	return quickShareService.getMetaData(nodeRef);
           }
       }, user.getUsername());
	return (Map<String, Object>)container.get("item");
}
 
Example 11
Source File: RunAsAdvice.java    From alfresco-mvc with Apache License 2.0 5 votes vote down vote up
public Object invoke(final MethodInvocation invocation) throws Throwable {

		Class<?> targetClass = invocation.getThis() != null ? invocation.getThis().getClass() : null;

		Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
		// If we are dealing with method with generic parameters, find the original
		// method.
		specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
		AlfrescoRunAs alfrescounRunAs = parseRunAsAnnotation(specificMethod);
		if (alfrescounRunAs != null) {
			String runAs = alfrescounRunAs.value();
			if (StringUtils.hasText(runAs)) {
				RunAsWork<Object> getUserNameRunAsWork = new RunAsWork<Object>() {
					public Object doWork() throws Exception {
						try {
							return invocation.proceed();
						} catch (Throwable e) {
							throw new Exception(e.getMessage(), e);
						}
					}
				};
				return AuthenticationUtil.runAs(getUserNameRunAsWork, runAs);
			}
		}

		return invocation.proceed();
	}
 
Example 12
Source File: ThumbnailServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void afterCommit()
{
    if (logger.isDebugEnabled())
    {
        logger.debug("Starting aftercommit listener execution.");
    }
    final Set<NodeRef> thumbnailToDelete =  TransactionalResourceHelper.getSet(THUMBNAIL_TO_DELETE_NODES);

    AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
           RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
            txnHelper.setForceWritable(true);
            txnHelper.doInTransaction(new RetryingTransactionCallback<Void>()
            {
                @Override
                public Void execute() throws Throwable
                {
                    for (NodeRef node : thumbnailToDelete)
                    {
                        // Update lastThumbnailModification on parent node
                        // so that the thumbnail will be recreated when browsing share
                        String thumbnailName = (String) nodeService.getProperty(node, ContentModel.PROP_NAME);
                        addThumbnailModificationData(node, thumbnailName);

                        nodeService.deleteNode(node);
                    }
                    return null;
                }
            }, false, true);
            return null;
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example 13
Source File: TenantInterpreter.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String interpretCommand(final String line) throws IOException
{
    String currentUserName = getCurrentUserName();
    if (hasAuthority(currentUserName))
    {
       RunAsWork<String> executeWork = new RunAsWork<String>()
       {
           public String doWork() throws Exception
           {
               RetryingTransactionCallback<String> txnWork = new RetryingTransactionCallback<String>()
               {
                   public String execute() throws Exception
                   {
                       return executeCommand(line);
                   }
               };

               // from Thor
               RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
               txnHelper.setMaxRetries(1);
               
               return txnHelper.doInTransaction(txnWork);
           }
       };
       return AuthenticationUtil.runAs(executeWork, AuthenticationUtil.SYSTEM_USER_NAME);
    }
    else
    {
        return("Error: User '"+ currentUserName + "' not authorised");
    }
}
 
Example 14
Source File: HttpAlfrescoContentReader.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void getInfo()
{
    RunAsWork<Object> getInfoRunAs = new RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            getInfoImpl();
            return null;
        }
    };
    AuthenticationUtil.runAs(getInfoRunAs, AuthenticationUtil.SYSTEM_USER_NAME);
}
 
Example 15
Source File: RefreshTagScopeActionExecuter.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.action.Action, org.alfresco.service.cmr.repository.NodeRef)
 */
@Override
protected void executeImpl(final Action action, final NodeRef actionedUponNodeRef)
{
    if (this.nodeService.exists(actionedUponNodeRef) == true &&
        this.nodeService.hasAspect(actionedUponNodeRef, ContentModel.ASPECT_TAGSCOPE) == true)
    {
        // Run the update as the system user
        AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
        {
            @SuppressWarnings("unchecked")
            public Object doWork() throws Exception
            {
                // Create a new list of tag details
                List<TagDetails> tags = new ArrayList<TagDetails>(10);
                
                // Count the tags found in all the (primary) children of the node
                countTags(actionedUponNodeRef, tags);
                
                // Order the list
                Collections.sort(tags);
                
                // Write new content back to tag scope
                String tagContent = TaggingServiceImpl.tagDetailsToString(tags);
                if(tagContent.length() > 0)
                {
                	// Write out tag content only if non-zero in size
                 ContentWriter contentWriter = contentService.getWriter(actionedUponNodeRef, ContentModel.PROP_TAGSCOPE_CACHE, true);
                 contentWriter.setEncoding("UTF-8");
                 contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
                 contentWriter.putContent(tagContent);
                }

                return null;
            }
            
        }, AuthenticationUtil.getSystemUserName());                      
    }
}
 
Example 16
Source File: RenditionService2IntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testUpgradeRenditionService() throws InterruptedException
{
    String ownerUserName = createRandomUser();
    NodeRef sourceNodeRef = createSource(ownerUserName, "quick.jpg");
    final QName doclibRendDefQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "doclib");
    transactionService.getRetryingTransactionHelper()
            .doInTransaction(() ->
            AuthenticationUtil.runAs(() ->
                    renditionService.render(sourceNodeRef, doclibRendDefQName), ownerUserName));

    NodeRef oldRendition = AuthenticationUtil.runAs(() ->
            renditionService.getRenditionByName(sourceNodeRef, doclibRendDefQName).getChildRef(), ownerUserName);
    assertFalse("The rendition should be generated by old Rendition Service",
            AuthenticationUtil.runAs(() -> nodeService.hasAspect(oldRendition, RenditionModel.ASPECT_RENDITION2), ownerUserName));

    updateContent(ownerUserName, sourceNodeRef, "quick.png");
    NodeRef newRendition = waitForRendition(ownerUserName, sourceNodeRef, DOC_LIB, true);
    assertNotNull("The rendition should be reported via RenditionService2", newRendition);
    Thread.sleep(200);
    boolean hasRenditionedAspect = false;
    for (int i = 0; i < 5; i++)
    {
        hasRenditionedAspect = AuthenticationUtil.runAs(() -> nodeService.hasAspect(newRendition, RenditionModel.ASPECT_RENDITION2), ownerUserName);
        if (hasRenditionedAspect)
        {
            break;
        }
        else
        {
            Thread.sleep(500);
        }
    }
    assertTrue("The rendition should be generated by new Rendition Service", hasRenditionedAspect);
}
 
Example 17
Source File: NodeArchiveServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get all the nodes that were archived <b>from</b> the given store.
 * 
 * @param originalStoreRef      the original store to process
 */
private List<NodeRef> getArchivedNodes(StoreRef originalStoreRef)
{
    // Get the archive location
    final NodeRef archiveParentNodeRef = nodeService.getStoreArchiveNode(originalStoreRef);
    RunAsWork<List<ChildAssociationRef>> runAsWork = new RunAsWork<List<ChildAssociationRef>>()
    {
        @Override
        public List<ChildAssociationRef> doWork() throws Exception
        {
            String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
            if (currentUser == null)
            {
                throw new AccessDeniedException("No authenticated user; cannot get archived nodes.");
            }
            return nodeService.getChildAssocs(
                    archiveParentNodeRef,
                    ContentModel.ASSOC_CHILDREN,
                    NodeArchiveService.QNAME_ARCHIVED_ITEM);
        }
    };
    // Fetch all children as 'system' user to bypass permission checks
    List<ChildAssociationRef> archivedAssocs = AuthenticationUtil.runAs(runAsWork, AuthenticationUtil.getSystemUserName());
    // Iterate and pull out NodeRefs with a permission check
    List<NodeRef> nodeRefs = new ArrayList<NodeRef>(archivedAssocs.size());
    for (ChildAssociationRef childAssociationRef : archivedAssocs)
    {
        NodeRef nodeRef = childAssociationRef.getChildRef();
        // Eliminate if the current user doesn't have permission to delete
        if (permissionService.hasPermission(nodeRef, PermissionService.DELETE) == AccessStatus.ALLOWED)
        {
            nodeRefs.add(nodeRef);
        }
    }
    return nodeRefs;
}
 
Example 18
Source File: FixedAclUpdater.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void process(final NodeRef nodeRef) throws Throwable
{
    RunAsWork<Void> findAndUpdateAclRunAsWork = new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            if (log.isDebugEnabled())
            {
                log.debug(String.format("Processing node %s", nodeRef));
            }
            final Long nodeId = nodeDAO.getNodePair(nodeRef).getFirst();

            // retrieve acl properties from node
            Long inheritFrom = (Long) nodeDAO.getNodeProperty(nodeId,
                    ContentModel.PROP_INHERIT_FROM_ACL);
            Long sharedAclToReplace = (Long) nodeDAO.getNodeProperty(nodeId,
                    ContentModel.PROP_SHARED_ACL_TO_REPLACE);

            // set inheritance using retrieved prop
            accessControlListDAO.setInheritanceForChildren(nodeRef, inheritFrom, sharedAclToReplace,
                    true);

            nodeDAO.removeNodeAspects(nodeId, aspects);
            nodeDAO.removeNodeProperties(nodeId, PENDING_FIX_ACL_ASPECT_PROPS);
            
            if (!policyIgnoreUtil.ignorePolicy(nodeRef))
            {
                boolean transformedToAsyncOperation = toBoolean((Boolean) AlfrescoTransactionSupport.getResource(FixedAclUpdater.FIXED_ACL_ASYNC_REQUIRED_KEY));

                OnInheritPermissionsDisabled onInheritPermissionsDisabledPolicy = onInheritPermissionsDisabledDelegate.get(ContentModel.TYPE_BASE);
                onInheritPermissionsDisabledPolicy.onInheritPermissionsDisabled(nodeRef, transformedToAsyncOperation);
            }

            if (log.isDebugEnabled())
            {
                log.debug(String.format("Node processed %s", nodeRef));
            }

            return null;
        }

    };

    AuthenticationUtil.runAs(findAndUpdateAclRunAsWork, AuthenticationUtil.getSystemUserName());
}
 
Example 19
Source File: RepoStore.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
public String[] getAllDocumentPaths()
    {
        return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<String[]>()
        {
            public String[] doWork() throws Exception
            {
                return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<String[]>()
                {
                    public String[] execute() throws Exception
                    {
                        int baseDirLength = getBaseDir().length() +1;
                        
                        List<String> documentPaths;
                        
                        NodeRef repoStoreRootNodeRef = nodeService.getRootNode(repoStore);
                        List<NodeRef> nodeRefs = searchService.selectNodes(
                                repoStoreRootNodeRef,
                                repoPath +
                                "//*[subtypeOf('{http://www.alfresco.org/model/content/1.0}content')]\"",
                                new QueryParameterDefinition[] {},
                                namespaceService,
                                false,
                                SearchService.LANGUAGE_XPATH);
                        documentPaths = new ArrayList<String>(nodeRefs.size());
                      for (NodeRef nodeRef : nodeRefs)
                      {
                          if (isContentPresent(nodeRef))
                          {
                                String nodeDir = getPath(nodeRef);
                                documentPaths.add(nodeDir.substring(baseDirLength));
                          }
                      }
                        
//                        String query = "+PATH:\"" + repoPath +
//                                       "//*\" +TYPE:\"{http://www.alfresco.org/model/content/1.0}content\"";
//                        ResultSet resultSet = searchService.query(repoStore, SearchService.LANGUAGE_LUCENE, query);
//                        try
//                        {
//                            documentPaths = new ArrayList<String>(resultSet.length());
//                            List<NodeRef> nodes = resultSet.getNodeRefs();
//                            for (NodeRef nodeRef : nodes)
//                            {
//                                String nodeDir = getPath(nodeRef);
//                                documentPaths.add(nodeDir.substring(baseDirLength));
//                            }
//                        }
//                        finally
//                        {
//                            resultSet.close();
//                        }
                        
                        return documentPaths.toArray(new String[documentPaths.size()]);
                    }
                }, true, false);
            }
        }, AuthenticationUtil.getSystemUserName());
    }
 
Example 20
Source File: MultiTDemoTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void test16DeleteArchiveAndRestoreContent()
{
    logger.info("test delete/archive & restore content");
    
    // note: CLOUD-1349 - ownership is based on fully authenticated user (else restoreNode fails for non-Admin user)
    AuthenticationUtil.clearCurrentSecurityContext();
    
    final String superAdmin = AuthenticationUtil.getAdminUserName();
    
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            // super tenant - admin user
            deleteArchiveAndRestoreContent(superAdmin, TenantService.DEFAULT_DOMAIN);
            return null;
        }
        
    }, superAdmin);
    
    final String superAnoUser = "superAnoUser";
    
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            createUser(superAnoUser, TenantService.DEFAULT_DOMAIN, superAnoUser);
            return null;
        }
    }, superAdmin);
    
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            // super tenant - ano user
            deleteArchiveAndRestoreContent(superAnoUser, TenantService.DEFAULT_DOMAIN);
            
            return null;
        }
    }, superAnoUser);
    
    for (final String tenantDomain : tenants)
    {
        final String tenantUserName = tenantService.getDomainUser(TEST_USER1, tenantDomain);
        
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Object>()
        {
            public Object doWork() throws Exception
            {
                deleteArchiveAndRestoreContent(tenantUserName, tenantDomain);
                
                return null;
            }
        }, tenantUserName, tenantDomain);
    }
}