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

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#runAsSystem() . 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: PersonServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private NodeRef createMissingPersonAsSystem(final String userName, final boolean autoCreateHomeFolder)
{
    return AuthenticationUtil.runAsSystem(new AuthenticationUtil.RunAsWork<NodeRef>()
    {
        @Override
        public NodeRef doWork() throws Exception
        {
            HashMap<QName, Serializable> properties = getDefaultProperties(userName);
            NodeRef person = createPerson(properties);

            // The home folder will ONLY exist after the the person is created if
            // homeFolderCreationEager == true
            if (autoCreateHomeFolder && homeFolderCreationEager == false)
            {
                makeHomeFolderIfRequired(person);
            }

            return person;
        }
    });
}
 
Example 2
Source File: RepoService.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 3
Source File: BasicHttpAuthenticatorFactory.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected boolean isBasicAuthHeaderPresentForAdmin()
{
    if (authorization == null || authorization.isEmpty())
    {
        return false;
    }
    String[] authorizationParts = authorization.split(" ");
    if (!authorizationParts[0].equalsIgnoreCase("basic"))
    {
        return false;
    }

    String decodedAuthorisation = new String(Base64.decode(authorizationParts[1]));
    Authorization auth = new Authorization(decodedAuthorisation);
    if (auth.isTicket() || auth.getUserName() == null || auth.getUserName().isEmpty())
    {
        return false;
    }
    // optimization: check the admin user name first
    if (AuthenticationUtil.getAdminUserName().equals(auth.getUserName()))
    {
        return true;
    }
    // then check the admin group
    return AuthenticationUtil.runAsSystem(() -> authorityService.isAdminAuthority(auth.getUserName()));
}
 
Example 4
Source File: PublicApiTenantAuthentication.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Determine whether tenant exists and enabled
 * 
 * @param tenant String
 * @return  true => it exists, no it doesn't
 */
public boolean tenantExists(final String tenant)
{
    if (tenant == null || TenantService.DEFAULT_DOMAIN.equalsIgnoreCase(tenant))
    {
        return true;
    }
    
    return AuthenticationUtil.runAsSystem(new RunAsWork<Boolean>()
    {
        public Boolean doWork() throws Exception
        {
            return tenantAdminService.existsTenant(tenant) && tenantAdminService.isEnabled();
        }
    });
}
 
Example 5
Source File: CMMDownloadTestUtil.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 6
Source File: EmailHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Gets the user's locale.
 *
 * @param userId the user id
 * @return the default locale or the user's preferred locale, if available
 */
public Locale getUserLocaleOrDefault(String userId)
{
    if (userId != null && personService.personExists(userId))
    {
        String localeString = AuthenticationUtil.runAsSystem(() -> (String) preferenceService.getPreference(userId, "locale"));
        if (localeString != null)
        {
            return I18NUtil.parseLocale(localeString);
        }
    }

    return I18NUtil.getLocale();
}
 
Example 7
Source File: RenditionService2Impl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void failure(NodeRef sourceNodeRef, RenditionDefinition2 renditionDefinition, int transformContentHashCode)
{
    // The original transaction may have already have failed
    AuthenticationUtil.runAsSystem((AuthenticationUtil.RunAsWork<Void>) () ->
            transactionService.getRetryingTransactionHelper().doInTransaction(() ->
            {
                consume(sourceNodeRef, null, renditionDefinition, transformContentHashCode);
                return null;
            }, false, true));
}
 
Example 8
Source File: CustomModelImportTest.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();
    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
Source File: FacetRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override public void tearDown() throws Exception
{
    super.tearDown();

    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            deleteFilters();
            return null;
        }
    }, SEARCH_ADMIN_USER);

    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        @Override public Void doWork() throws Exception
        {
            transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
            {
                public Void execute() throws Throwable
                {
                    deleteUser(SEARCH_ADMIN_USER);
                    deleteUser(NON_SEARCH_ADMIN_USER);
                    return null;
                }
            });
            return null;
        }
    });
    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 10
Source File: ForumPostBehaviours.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void beforeDeleteNode(final NodeRef nodeRef)
{
    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            adjustCommentCount(nodeRef, false);
            return null;
        }
    });
}
 
Example 11
Source File: CommentServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String getSiteId(final NodeRef nodeRef)
 {
     String siteId = AuthenticationUtil.runAsSystem(new RunAsWork<String>()
     {
@Override
public String doWork() throws Exception
{
	return siteService.getSiteShortName(nodeRef);
}
     });

     return siteId;
 }
 
Example 12
Source File: PeopleImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 13
Source File: SharedFolderPatch.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Run the Shared Folder Patch asynchronously after bootstrap.
 */
public void executeAsync()
{
    // Lock the push
    QName lockQName = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "patch.sharedFolder");
    String lockToken = jobLockService.getLock(lockQName, LOCK_TIME_TO_LIVE, 0, 1);
    SharedFolderPatchCallback callback = new SharedFolderPatchCallback();
    jobLockService.refreshLock(lockToken, lockQName, LOCK_REFRESH_TIME, callback);
    
    try
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("SharedFolderPatch: job lock held");
        }
        
        AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
        {
            public Void doWork() throws Exception
            {
                applyAsync();
                return null;
            }
        });
    }
    finally
    {
        if (logger.isTraceEnabled())
        {
            logger.trace("PUSH: job finished");
        }
        
        // Release the locks on the job and stop refreshing
        callback.isActive = false;
        jobLockService.releaseLock(lockToken, lockQName);
    }
}
 
Example 14
Source File: AbstractMultitenantWorkflowTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String createTenant(final String tenantDomain)
{
    // create tenants (if not already created)
    return AuthenticationUtil.runAsSystem(new RunAsWork<String>()
    {
        public String doWork() throws Exception
        {
            if (! tenantAdminService.existsTenant(tenantDomain))
            {
                tenantAdminService.createTenant(tenantDomain, (DEFAULT_ADMIN_PW+" "+tenantDomain).toCharArray(), null); // use default root dir
            }
            return tenantService.getDomainUser(AuthenticationUtil.getAdminUserName(), tenantDomain);
        }
    });
}
 
Example 15
Source File: FileFolderLoaderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@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);
}
 
Example 16
Source File: RepoService.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
public TestPerson getOrCreateUser(final PersonInfo personInfo, final String username, final TestNetwork network, final boolean deletePerson)
{
	return AuthenticationUtil.runAsSystem(new RunAsWork<TestPerson>()
	{
		@Override
		public TestPerson doWork() throws Exception
		{

			final TestPerson testPerson = new TestPerson(personInfo.getFirstName(), personInfo.getLastName(), username, personInfo.getPassword(),
					personInfo.getCompany(), network, personInfo.getSkype(), personInfo.getLocation(), personInfo.getTel(),
					personInfo.getMob(), personInfo.getInstantmsg(), personInfo.getGoogle());

			final Map<QName, Serializable> props = testPerson.toProperties();

               // short-circuit for default/tenant "admin"
               if (! isDefaultAdmin(username, network))
               {
                   NodeRef personNodeRef = personService.getPersonOrNull(username);

                   if ((personNodeRef != null) && deletePerson)
                   {
                       AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
                       {
                           @Override
                           public Void doWork() throws Exception
                           {
                               personService.deletePerson(testPerson.getId());
                               return null;
                           }
                       });
                   }

                   if (personNodeRef == null)
                   {
                       personNodeRef = personService.createPerson(props);

                       // create authentication to represent user
                       authenticationService.createAuthentication(username, personInfo.getPassword().toCharArray());

                       if (EnterpriseTestFixture.WITH_AVATAR.equals(personInfo.getInstantmsg()))
                       {
                           InvitationWebScriptTest.makeAvatar(nodeService, personNodeRef);
                           log("Made avatar for " + testPerson.getId() + (network != null ? " in network " + network : ""));
                       }
                   }
               }
			log("Username " + testPerson.getId() + (network != null ? " in network " + network : ""));

			publicApiContext.addUser(testPerson.getId());
			addPerson(testPerson);
			
			return testPerson;
		}
	});
}
 
Example 17
Source File: SiteRoutingFileContentStore.java    From alfresco-simple-content-stores with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void onMoveNode(final ChildAssociationRef oldChildAssocRef, final ChildAssociationRef newChildAssocRef)
{
    // only act on active nodes which can actually be in a site
    // only act on active nodes which can actually be in a site
    final NodeRef movedNode = oldChildAssocRef.getChildRef();
    final NodeRef oldParent = oldChildAssocRef.getParentRef();
    final NodeRef newParent = newChildAssocRef.getParentRef();
    if (StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.equals(movedNode.getStoreRef()) && !EqualsHelper.nullSafeEquals(oldParent, newParent))
    {
        LOGGER.debug("Processing onMoveNode for {} from {} to {}", movedNode, oldChildAssocRef, newChildAssocRef);

        // check for actual move-relevant site move
        final Boolean moveRelevant = AuthenticationUtil.runAsSystem(() -> {
            final NodeRef sourceSite = this.resolveSiteForNode(oldParent);
            final NodeRef targetSite = this.resolveSiteForNode(newParent);

            final SiteAwareFileContentStore sourceStore = this.resolveStoreForSite(sourceSite);
            final SiteAwareFileContentStore targetStore = this.resolveStoreForSite(targetSite);

            boolean moveRelevantB = sourceStore != targetStore;
            if (!moveRelevantB && !EqualsHelper.nullSafeEquals(sourceSite, targetSite)
                    && targetStore.isUseSiteFolderInGenericDirectories())
            {
                moveRelevantB = true;
            }
            return Boolean.valueOf(moveRelevantB);
        });

        if (Boolean.TRUE.equals(moveRelevant))
        {
            LOGGER.debug("Node {} was moved to a location for which content should be stored in a different store", movedNode);
            this.checkAndProcessContentPropertiesMove(movedNode);
        }
        else
        {
            LOGGER.debug("Node {} was not moved into a location for which content should be stored in a different store", movedNode);
        }
    }
}
 
Example 18
Source File: CMISConnector.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private ObjectData createCMISObjectImpl(final CMISNodeInfo info, Properties nodeProps, String filter,
        boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter,
        boolean includePolicyIds, boolean includeAcl)
{
    final ObjectDataImpl result = new ObjectDataImpl();

    // set allowable actions
    if (includeAllowableActions)
    {
        result.setAllowableActions(getAllowableActions(info));
    }

    // set policy ids
    if (includePolicyIds)
    {
        result.setPolicyIds(new PolicyIdListImpl());
    }

    if (info.isRelationship())
    {
        // set properties
        result.setProperties(getAssocProperties(info, filter));

        // set ACL
        if (includeAcl)
        {
            // association have no ACL - return an empty list of ACEs
            result.setAcl(new AccessControlListImpl((List<Ace>) Collections.EMPTY_LIST));
            result.setIsExactAcl(Boolean.FALSE);
        }
    }
    else
    {
        // set properties
        result.setProperties(nodeProps);

        // set relationships
        if (includeRelationships != IncludeRelationships.NONE)
        {
            result.setRelationships(getRelationships(info.getNodeRef(), includeRelationships));
        }

        // set renditions
        if (!RENDITION_NONE.equals(renditionFilter))
        {
            List<RenditionData> renditions = getRenditions(info.getNodeRef(), renditionFilter, null, null);
            if ((renditions != null) && (!renditions.isEmpty()))
            {
                result.setRenditions(renditions);
            }
            else
            {
            	result.setRenditions(Collections.EMPTY_LIST);
            }
        }

        // set ACL
        if (includeAcl)
        {
        	AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
        	{
	@Override
	public Void doWork() throws Exception
	{
	    Acl acl = getACL(info.getCurrentNodeNodeRef(), false);
              if (acl != null)
              {
	        result.setAcl(acl);
	        result.setIsExactAcl(acl.isExact());
              }
		return null;
	}
        	});
        }

        // add aspects
        List<CmisExtensionElement> extensions = getAspectExtensions(info, filter, result.getProperties()
                .getProperties().keySet());

        if (!extensions.isEmpty())
        {
            result.getProperties().setExtensions(
                    Collections.singletonList((CmisExtensionElement) new CmisExtensionElementImpl(
                            ALFRESCO_EXTENSION_NAMESPACE, ASPECTS, null, extensions)));
        }
    }
    return result;
}
 
Example 19
Source File: CustomModelImportTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@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 20
Source File: EmailServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 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);
}