Java Code Examples for org.alfresco.repo.security.authentication.AuthenticationUtil

The following are top voted examples for showing how to use org.alfresco.repo.security.authentication.AuthenticationUtil. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alfresco-repository   File: NodeMonitor.java   View source code 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
Project: alfresco-remote-api   File: PeopleImpl.java   View source code 6 votes vote down vote up
/**
 * Write the description to a content file and store the content URL in
 * ContentModel.PROP_PERSONDESC
 * 
 * @param description
 * @param nodeRef
 */
private void savePersonDescription(final String description, final NodeRef nodeRef)
{
    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            if (description != null)
            {
                ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_PERSONDESC, true);
                writer.putContent(description);
            }
            else
            {
                nodeService.setProperty(nodeRef, ContentModel.PROP_PERSONDESC, null);
            }
            return null;
        }
    });
}
 
Example 3
Project: alfresco-repository   File: PermissionServiceImpl.java   View source code 6 votes vote down vote up
protected Set<AccessPermission> getAllPermissionsImpl(NodeRef nodeRef, boolean includeTrue, boolean includeFalse)
{
    String userName = AuthenticationUtil.getRunAsUser();
    HashSet<AccessPermission> accessPermissions = new HashSet<AccessPermission>();
    for (PermissionReference pr : getSettablePermissionReferences(nodeRef))
    {
        if (hasPermission(nodeRef, pr) == AccessStatus.ALLOWED)
        {
            accessPermissions.add(new AccessPermissionImpl(getPermission(pr), AccessStatus.ALLOWED, userName, -1));
        }
        else
        {
            if (includeFalse)
            {
                accessPermissions.add(new AccessPermissionImpl(getPermission(pr), AccessStatus.DENIED, userName, -1));
            }
        }
    }
    return accessPermissions;
}
 
Example 4
Project: alfresco-repository   File: PermissionServiceImpl.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class)
public Set<String> getAuthorisations()
{
    // Use TX cache 
    @SuppressWarnings("unchecked")
    Set<String> auths = (Set<String>) AlfrescoTransactionSupport.getResource("MyAuthCache");
    Authentication auth = AuthenticationUtil.getRunAsAuthentication();
    if (auths != null)
    {
        if (auth == null || !auths.contains(((User)auth.getPrincipal()).getUsername()))
        {
            auths = null;
        }
    }
    if (auths == null)
    {
        auths = getCoreAuthorisations(auth);
        AlfrescoTransactionSupport.bindResource("MyAuthCache", auths);
    }
    return Collections.unmodifiableSet(auths);   
}
 
Example 5
Project: alfresco-repository   File: MultiUserRenditionTest.java   View source code 6 votes vote down vote up
public  void initContextAndCreateUser()
{
    appContext = ApplicationContextHelper.getApplicationContext();

    authenticationService = (MutableAuthenticationService) appContext.getBean("AuthenticationService");
    contentService = (ContentService) appContext.getBean("ContentService");
    nodeService = (NodeService) appContext.getBean("NodeService");
    permissionService = (PermissionService) appContext.getBean("PermissionService");
    personService = (PersonService) appContext.getBean("PersonService");
    renditionService = (RenditionService) appContext.getBean("RenditionService");
    repositoryHelper = (Repository) appContext.getBean("repositoryHelper");
    transactionService = (TransactionService) appContext.getBean("TransactionService");
    txnHelper = transactionService.getRetryingTransactionHelper();
    ownableService = (OwnableService) appContext.getBean("ownableService");

    ADMIN_USER = AuthenticationUtil.getAdminUserName();
    
    // Create a nonAdminUser
    createUser(NON_ADMIN_USER);

}
 
Example 6
Project: alfresco-repository   File: DefaultRemoteUserMapper.java   View source code 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.isDebugEnabled())
        logger.debug("The normalized user name is: " + normalized + " for user id " + userId);
    return normalized == null ? userId : normalized;
}
 
Example 7
Project: alfresco-repository   File: RenditionServiceIntegrationTest.java   View source code 6 votes vote down vote up
private RenditionDefinition loadAndValidateRenditionDefinition(String renditionLocalName)
{
    QName renditionQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, renditionLocalName);
    RenditionDefinition renditionDefinition = renditionService.loadRenditionDefinition(renditionQName);
    assertNotNull("'" + renditionLocalName + "' rendition definition was missing.", renditionDefinition);
    assertEquals("'" + renditionLocalName + "' renditionDefinition had wrong renditionName", renditionQName,
                renditionDefinition.getRenditionName());

    assertNotNull("'" + renditionLocalName + "' renditionDefinition had null " +
            RenditionDefinitionImpl.RENDITION_DEFINITION_NAME + " parameter",
                renditionDefinition.getParameterValue(RenditionDefinitionImpl.RENDITION_DEFINITION_NAME));
    
    // All builtin renditions should be "runas" system
    assertEquals(AuthenticationUtil.getSystemUserName(), renditionDefinition.getParameterValue(AbstractRenderingEngine.PARAM_RUN_AS));

    return renditionDefinition;
}
 
Example 8
Project: alfresco-remote-api   File: AbstractBaseApiTest.java   View source code 6 votes vote down vote up
/**
 * TODO implement as remote api call
 */
protected String getOrCreateUser(String usernameIn, String password, TestNetwork network)
{
    final String tenantDomain = (network != null ? network.getId() : TenantService.DEFAULT_DOMAIN);

    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<String>()
    {
        @Override
        public String doWork() throws Exception
        {
            return TenantUtil.runAsTenant(new TenantUtil.TenantRunAsWork<String>()
            {
                public String doWork() throws Exception
                {
                    String username = repoService.getPublicApiContext().createUserName(usernameIn, tenantDomain);
                    PersonInfo personInfo = new PersonInfo(username, username, username, password, null, null, null, null, null, null, null);
                    RepoService.TestPerson person = repoService.getOrCreateUser(personInfo, username, network);
                    return person.getId();
                }
            }, tenantDomain);
        }
    }, networkAdmin);
}
 
Example 9
Project: alfresco-repository   File: DocumentLinkServiceImplTest.java   View source code 6 votes vote down vote up
/**
 * Tests the creation of a document link when the user doesn't have write
 * permission on the destination node
 * 
 * @throws Exception
 */
public void testCreateDocLinkWithoutWritePermissionOnDestination() throws Exception
{
    try
    {
        AuthenticationUtil.runAs(new RunAsWork<Void>()
        {
            @Override
            public Void doWork() throws Exception
            {
                documentLinkService.createDocumentLink(site1File1, site2Folder1);
                return null;
            }
        }, TEST_USER);

        fail("no write permission on the destination node must generate AccessDeniedException.");
    }
    catch (AccessDeniedException ex)
    {
        // Expected
    }
}
 
Example 10
Project: alfresco-repository   File: HomeFolderProviderSynchronizer.java   View source code 6 votes vote down vote up
public void process(final NodeRef person) throws Throwable
{
    // note: runAs before runAsTenant (to avoid clearing tenant context, if no previous auth)
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        @Override
        public Object doWork() throws Exception
        {
            return TenantUtil.runAsTenant(new TenantRunAsWork<Void>()
            {
                public Void doWork() throws Exception
                {
                   RunAsWorker.this.doWork(person);
                    return null;
                }
            }, tenantDomain);
        }
    }, userName);
}
 
Example 11
Project: alfresco-repository   File: RenditionServicePermissionsTest.java   View source code 6 votes vote down vote up
@Before public void initNonStaticData() throws Exception
{
    companyHome = repositoryHelper.getCompanyHome();
    
    // Create the test folder used for these tests
    testFolderName = "Test-folder-"+ System.currentTimeMillis();
    testFolder     = testNodes.createFolder(companyHome, testFolderName, AuthenticationUtil.getAdminUserName());
    
    // Create the node used as a content supplier for one test
    String testImageNodeName = "testImageNode" + System.currentTimeMillis();
    nodeWithImageContent     = testNodes.createQuickFile(MimetypeMap.MIMETYPE_IMAGE_PNG, companyHome, testImageNodeName, AuthenticationUtil.getAdminUserName());
    
    // Create a test site - note that 'admin' is the site creator.
    testSiteInfo = testSites.createTestSiteWithUserPerRole(this.getClass().getSimpleName(),
                                                           "sitePreset",
                                                           SiteVisibility.PRIVATE,
                                                           AuthenticationUtil.getAdminUserName());
    final NodeRef siteDocLib = testSiteInfo.doclib;
    // Put a piece of content in that site - again the creator is admin.
    // This piece of content is malformed and it will not be possible to create thumbnails from it.
    brokenJpg                = testNodes.createQuickFileByName("quickCorrupt.jpg", siteDocLib, AuthenticationUtil.getAdminUserName());
}
 
Example 12
Project: alfresco-repository   File: TemporaryModels.java   View source code 6 votes vote down vote up
@Override protected void after()
{
    final RetryingTransactionHelper transactionHelper = getTransactionHelper();
    final DictionaryDAO dictionaryDAO = getDictionaryDAO();
    
    // Run as system to ensure all non-system nodes can be deleted irrespective of which user created them.
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @Override public Void doWork() throws Exception
        {
            transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
            {
                @Override public Void execute() throws Throwable
                {
                	for (QName model : loadedModels)
                	{
                		dictionaryDAO.removeModel(model);
                	}
                	return null;
                }
            });
            return null;
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example 13
Project: alfresco-repository   File: HTMLRenderingEngineTest.java   View source code 6 votes vote down vote up
private void tidyUpSourceDoc()
{
    // Set the current security context as admin
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
   
    // Clean up the source
    if(sourceDoc != null)
    {
       nodeService.deleteNode(sourceDoc);
    }
  
    // Clean up the target folder
    nodeService.deleteNode(targetFolder);
    targetFolder = null;
    
    // All done
    sourceDoc = null;
    createTargetFolder();
}
 
Example 14
Project: alfresco-repository   File: AuthenticatedPersonDataGenerator.java   View source code 6 votes vote down vote up
/**
 * @return              Returns the full name of the currently-authenticated user
 */
public Serializable getData() throws Throwable
{
    String user = AuthenticationUtil.getFullyAuthenticatedUser();
    NodeRef personNodeRef = personService.getPerson(user);
    String fullName = null;
    if (personNodeRef != null && nodeService.exists(personNodeRef))
    {
        String firstName = (String)nodeService.getProperty(personNodeRef, ContentModel.PROP_FIRSTNAME);
        String lastName = (String)nodeService.getProperty(personNodeRef, ContentModel.PROP_LASTNAME);
        
        fullName = ((firstName != null && firstName.length() > 0) ? firstName : "");
        if (lastName != null && lastName.length() > 0)
        {
            fullName += (fullName.length() > 0 ? " " : "");
            fullName += lastName;
        }
    }
    // Done
    if (logger.isDebugEnabled())
    {
        logger.debug("Generated name '" + fullName + "' for user '" + user + "'.");
    }
    return fullName;
}
 
Example 15
Project: alfresco-repository   File: BaseAlfrescoTestCase.java   View source code 6 votes vote down vote up
/** 
 * @see junit.framework.TestCase#tearDown()
 */
@Override
protected void tearDown() throws Exception
{
    retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
    {
        @Override
        public Object execute() throws Throwable
        {
            // As system user
            AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
            
            if (useSpacesStore() == false)
            {
                // Delete the created store
                nodeService.deleteStore(storeRef);
            }
            
            return null;
        }
    });
    
    super.tearDown();
}
 
Example 16
Project: alfresco-repository   File: Site.java   View source code 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 17
Project: alfresco-remote-api   File: InviteServiceTest.java   View source code 6 votes vote down vote up
/**
 * https://issues.alfresco.com/jira/browse/ETHREEOH-520
 */
public void testETHREEOH_520()
    throws Exception
{
    final String userName = "userInviteServiceTest" + GUID.generate();
    final String emailAddress = " ";

    // Create a person with a blank email address and
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            createPerson(PERSON_FIRSTNAME, PERSON_LASTNAME, userName, " ");
            return null;
        }

    }, AuthenticationUtil.getSystemUserName());

    // Try and add an existing person to the site with no email address
    // Should return bad request since the email address has not been provided
    startInvite(PERSON_FIRSTNAME, PERSON_LASTNAME, emailAddress, INVITEE_SITE_ROLE, SITE_SHORT_NAME_INVITE_1, Status.STATUS_BAD_REQUEST);
}
 
Example 18
Project: alfresco-repository   File: CMMDownloadTestUtil.java   View source code 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 19
Project: alfresco-repository   File: FileFolderLoaderTest.java   View source code 6 votes vote down vote up
/**
 * Zero files
 */
@Test
public void testLoad_ZeroFiles() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        int created = fileFolderLoader.createFiles(
                writeFolderPath,
                0, 256, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        assertEquals("Incorrect number of files generated.", 0, created);
        // Count
        assertEquals(0, nodeService.countChildAssocs(writeFolderNodeRef, true));
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 20
Project: alfresco-repository   File: SiteServiceImpl.java   View source code 6 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.site.SiteService#getSite(java.lang.String)
 */
public SiteInfo getSite(final String shortName)
{
    // MT share - for activity service remote system callback (deprecated)
    if (tenantService.isEnabled() &&
        TenantUtil.isCurrentDomainDefault() &&
        (AuthenticationUtil.SYSTEM_USER_NAME.equals(AuthenticationUtil.getRunAsUser())) &&
        tenantService.isTenantName(shortName))
    {
        final String tenantDomain = tenantService.getDomain(shortName);
        final String sName = tenantService.getBaseName(shortName, true);
        
        return TenantUtil.runAsSystemTenant(new TenantRunAsWork<SiteInfo>()
        {
            public SiteInfo doWork() throws Exception
            {
                SiteInfo site = getSiteImpl(sName);
                return new SiteInfoImpl(site.getSitePreset(), shortName, site.getTitle(), site.getDescription(), site.getVisibility(), site.getCustomProperties(), site.getNodeRef());
            }
        }, tenantDomain);
    }
    else
    {
        return getSiteImpl(shortName);
    }
}
 
Example 21
Project: alfresco-repository   File: SiteServiceImpl.java   View source code 6 votes vote down vote up
public void listMembers(String shortName, final String nameFilter, final String roleFilter, final boolean collapseGroups, final SiteMembersCallback callback)
{
    // MT share - for activity service system callback
    if (tenantService.isEnabled() && (AuthenticationUtil.SYSTEM_USER_NAME.equals(AuthenticationUtil.getRunAsUser())) && tenantService.isTenantName(shortName))
    {
        final String tenantDomain = tenantService.getDomain(shortName);
        final String sName = tenantService.getBaseName(shortName, true);
        
        TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>()
        {
            public Void doWork() throws Exception
            {
                listMembersImpl(sName, nameFilter, roleFilter, collapseGroups, callback);
                return null;
            }
        }, tenantDomain);
    }
    else
    {
        listMembersImpl(shortName, nameFilter, roleFilter, collapseGroups, callback);
    }
}
 
Example 22
Project: alfresco-remote-api   File: ADMRemoteStore.java   View source code 6 votes vote down vote up
/**
 * Get the RunAs user need to execute a Write operation on the given path.
 * 
 * @param path  Document path
 * @return runas user - will be the Full Authenticated User or System as required
 */
protected String getPathRunAsUser(final String path)
{
    // check we actually are the user we are creating a user specific path for
    String runAsUser = AuthenticationUtil.getFullyAuthenticatedUser();
    String userId = null;
    Matcher matcher;
    if ((matcher = USER_PATTERN_1.matcher(path)).matches())
    {
        userId = matcher.group(1);
    }
    else if ((matcher = USER_PATTERN_2.matcher(path)).matches())
    {
        userId = matcher.group(1);
    }
    if (userId != null && userId.equals(runAsUser))
    {
        runAsUser = AuthenticationUtil.getSystemUserName();
    }
    return runAsUser;
}
 
Example 23
Project: alfresco-remote-api   File: QuickShareRestApiTest.java   View source code 6 votes vote down vote up
@Override
public void tearDown() throws Exception
{
    super.tearDown();
    
    AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE);
    
    transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            if (testNode != null && nodeService.exists(testNode))
            {
                nodeService.deleteNode(testNode);
            }
            return null;
        }
    });
    
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
    
    deleteUser(USER_ONE);
    deleteUser(USER_TWO);

    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 24
Project: alfresco-remote-api   File: InviteServiceTest.java   View source code 6 votes vote down vote up
public void testStartInviteForSameInviteeButTwoDifferentSites()
    throws Exception
{
    final String inviteeUsername = INVITEE_FIRSTNAME + "_" + INVITEE_LASTNAME;
    final String inviteeEmail = INVITEE_EMAIL_PREFIX + RandomStringUtils.randomAlphanumeric(6) + "@" + INVITEE_EMAIL_DOMAIN;

    // Create person
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            createPerson(INVITEE_FIRSTNAME, INVITEE_LASTNAME, inviteeUsername, inviteeEmail);
            return null;
        }

    }, AuthenticationUtil.getSystemUserName());

    JSONObject result = startInvite(INVITEE_FIRSTNAME, INVITEE_LASTNAME, inviteeEmail, INVITEE_SITE_ROLE, SITE_SHORT_NAME_INVITE_1,
            Status.STATUS_CREATED);

    startInvite(INVITEE_FIRSTNAME, INVITEE_LASTNAME, inviteeEmail, INVITEE_SITE_ROLE, SITE_SHORT_NAME_INVITE_2, Status.STATUS_CREATED);
}
 
Example 25
Project: alfresco-remote-api   File: RepoStore.java   View source code 6 votes vote down vote up
/**
 * Gets the last modified time of the content
 * 
 * @return  last modified time
 */
public long lastModified()
{
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Long>()
    {
        public Long doWork() throws Exception
        {
            return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Long>()
            {
                public Long execute() throws Exception
                {
                    ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
                    return reader.getLastModified();
                }
            });
        }
    }, AuthenticationUtil.getSystemUserName());            
}
 
Example 26
Project: alfresco-repository   File: AddGroupAuthorityPatch.java   View source code 6 votes vote down vote up
@Override
protected String applyInternal() throws Exception
{
    StringBuilder result = new StringBuilder(I18NUtil.getMessage(MSG_START));

    String groupAuthorityName = PermissionService.GROUP_PREFIX + this.groupAuthorityDetails.groupName;
    if (!authorityService.authorityExists(groupAuthorityName))
    {
        groupAuthorityName = authorityService.createAuthority(AuthorityType.GROUP,
                    this.groupAuthorityDetails.groupName,
                    this.groupAuthorityDetails.groupDisplayName,
                    this.groupAuthorityDetails.authorityZones);

        authorityService.addAuthority(groupAuthorityName, AuthenticationUtil.getAdminUserName());

        result.append(I18NUtil.getMessage(MSG_RESULT, groupAuthorityName));
    }
    else
    {
        result.append(I18NUtil.getMessage(MSG_EXIST, groupAuthorityName));
    }
    return result.toString();
}
 
Example 27
Project: alfresco-repository   File: LockKeeperImplTest.java   View source code 6 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    applicationContext = ApplicationContextHelper.getApplicationContext();
    nodeService = (NodeService)applicationContext.getBean("nodeService");
    repositoryHelper = (Repository)this.applicationContext.getBean("repositoryHelper");
    transactionService = (TransactionService)applicationContext.getBean("transactionService");
    
    ChildApplicationContextFactory fileServersSubSystem = (ChildApplicationContextFactory) applicationContext.getBean("fileServers");
    assertNotNull("fileServers subsystem is null", fileServersSubSystem);
    lockKeeper =  (LockKeeper)fileServersSubSystem.getApplicationContext().getBean("lockKeeper");
    
	assertNotNull("nodeService is null", nodeService);
	assertNotNull("lockKeeper is null", lockKeeper);
	assertNotNull("transactionService is null", transactionService);

    
    AuthenticationUtil.setRunAsUserSystem();
    AuthenticationUtil.setFullyAuthenticatedUser("bugsBunny");
}
 
Example 28
Project: alfresco-repository   File: MultiUserRenditionTest.java   View source code 6 votes vote down vote up
@Before public void createTestFolder()
{
    initContextAndCreateUser();
    AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER);
    final NodeRef companyHome = repositoryHelper.getCompanyHome();
    
    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
    props.put(ContentModel.PROP_NAME, this.getClass() + "_testFolder");
    testFolder = nodeService.createNode(companyHome, 
                                            ContentModel.ASSOC_CONTAINS, 
                                            ContentModel.ASSOC_CONTAINS, 
                                            ContentModel.TYPE_FOLDER,
                                            props).getChildRef();
    // Let anyone (meaning non-admin) do anything (meaning create new content)
    permissionService.setPermission(testFolder, PermissionService.ALL_AUTHORITIES, PermissionService.ALL_PERMISSIONS, true);
    this.nodesToBeTidiedUp.add(testFolder);
}
 
Example 29
Project: alfresco-repository   File: VersionServiceImplTest.java   View source code 6 votes vote down vote up
public void testVersionLockedNode()
{
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Object>()
    {
        public Object execute() throws Exception
        {
            AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
            
            // create versionable node and ensure it has the necessary aspect
            NodeRef versionableNode = createNewVersionableNode();
            assertEquals(true, nodeService.hasAspect(versionableNode, ContentModel.ASPECT_VERSIONABLE));
            
            // add lockable aspect and write lock the node
            dbNodeService.addAspect(versionableNode, ContentModel.ASPECT_LOCKABLE, new HashMap<QName, Serializable>());
            assertEquals(true, nodeService.hasAspect(versionableNode, ContentModel.ASPECT_LOCKABLE));
            
            checkOutCheckInService.checkout(versionableNode);
            
            // try to create a version
            createVersion(versionableNode);
            VersionHistory vh = versionService.getVersionHistory(versionableNode);
            assertEquals(1, vh.getAllVersions().size());
            return null;
        }
    });
}
 
Example 30
Project: alfresco-remote-api   File: TransferWebScriptTest.java   View source code 6 votes vote down vote up
public void testVerify() throws Exception
{
    String url = "/api/transfer/test";
    PostRequest req = new PostRequest(url, new JSONObject().toString(), "application/json");
    
    //First, we'll try the request as a simple, non-admin user (expect a 401)
    AuthenticationUtil.setFullyAuthenticatedUser(USERNAME);
    sendRequest(req, 401);
    
    //Then we'll have a go as the system user (expect a 200)
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.SYSTEM_USER_NAME);
    sendRequest(req, 200);
    
    //Then we'll disable the transfer receiver and try again as the system user (expect a 404)
    TransferWebScript webscript = (TransferWebScript)getServer().getApplicationContext().getBean("webscript.org.alfresco.repository.transfer.transfer.post");
    webscript.setEnabled(false);
    sendRequest(req, 404);
}
 
Example 31
Project: alfresco-repository   File: TestUserComponentImpl.java   View source code 6 votes vote down vote up
@Override public void deleteTestUser(final String userName)
{
    // And tear down afterwards.
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @Override public Void doWork() throws Exception
        {
            try
            {
                if (personService.personExists(userName))
                {
                    log.debug("Deleting person " + userName + "...");
                    personService.deletePerson(userName);
                }
            } catch (InvalidNodeRefException ignoreIfThrown)
            {
                // It seems that in cloud code, asking if a person exists when the tenant they would be in also doesn't
                // exist, can give this exception.
            }
            return null;
        }
    }, AuthenticationUtil.getAdminUserName());
}
 
Example 32
Project: alfresco-repository   File: RemoteCredentialsServicesTest.java   View source code 6 votes vote down vote up
/**
 * Deletes the specified NodeRefs, if they exist.
 * @param nodesToDelete
 */
private static void performDeletionOfNodes(final List<NodeRef> nodesToDelete)
{
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
       @Override
       public Void execute() throws Throwable
       {
          AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER);

          for (NodeRef node : nodesToDelete)
          {
             if (NODE_SERVICE.exists(node))
             {
                NODE_SERVICE.deleteNode(node);
             }
          }

          return null;
       }
    });
}
 
Example 33
Project: alfresco-remote-api   File: TestActions.java   View source code 5 votes vote down vote up
@After
public void tearDown()
{
    // Restore authentication to pre-test state.
    try
    {
        AuthenticationUtil.popAuthentication();
    }
    catch(EmptyStackException e)
    {
        // Nothing to do.
    }
}
 
Example 34
Project: alfresco-repository   File: MultilingualContentServiceImplTest.java   View source code 5 votes vote down vote up
/**
 * Check whether non-admin users can take part in ML document manipulation
 */
public void testPermissions() throws Exception
{
    // Grant the guest user rights to our working folder
    PermissionService permissionService = serviceRegistry.getPermissionService();
    AuthenticationComponent authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    permissionService.setPermission(
            folderNodeRef,
            AuthenticationUtil.getGuestUserName(),
            PermissionService.ALL_PERMISSIONS,
            true);
    // Push the current authentication
    AuthenticationUtil.pushAuthentication();
    try
    {
        authenticationComponent.setGuestUserAsCurrentUser();
        // Create some documents
        NodeRef chineseContentNodeRef = createContent();
        NodeRef frenchContentNodeRef = createContent();
        // Do ML work
        multilingualContentService.makeTranslation(chineseContentNodeRef, Locale.CHINESE);
        multilingualContentService.addTranslation(frenchContentNodeRef, chineseContentNodeRef, Locale.FRENCH);
        multilingualContentService.addEmptyTranslation(chineseContentNodeRef, null, Locale.JAPANESE);
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 35
Project: alfresco-repository   File: TestPersonManager.java   View source code 5 votes vote down vote up
public void deletePerson(final String userName)
{
    AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            personService.deletePerson(userName);
            return null;
        }
    }, AuthenticationUtil.getSystemUserName());
    people.remove(userName);
    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 36
Project: alfresco-remote-api   File: ReadOnlyTransactionInGetRestApiTest.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    ApplicationContext appContext = getServer().getApplicationContext();

    this.siteService = (SiteService)appContext.getBean("SiteService");
    this.nodeService = (NodeService)appContext.getBean("NodeService");
    this.transactionService = (TransactionService)appContext.getBean("TransactionService");
    this.nodeArchiveService = (NodeArchiveService)getServer().getApplicationContext().getBean("nodeArchiveService");
    
    // set admin as current user
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    // delete the test site if it's still hanging around from previous runs
    SiteInfo site = siteService.getSite(TEST_SITE_NAME);
    if (site != null)
    {
        siteService.deleteSite(TEST_SITE_NAME);
        nodeArchiveService.purgeArchivedNode(nodeArchiveService.getArchivedNode(site.getNodeRef()));
    }
    
    // create the test site, this should create a site but it won't have any containers created
    SiteInfo siteInfo = this.siteService.createSite("collaboration", TEST_SITE_NAME, "Read Only Test Site", 
                "Test site for ReadOnlyTransactionRestApiTest", SiteVisibility.PUBLIC);
    this.testSiteNodeRef = siteInfo.getNodeRef();
    this.testSiteNodeRefString = this.testSiteNodeRef.toString().replace("://", "/");
    
    // ensure there are no containers present at the start of the test
    List<ChildAssociationRef> children = nodeService.getChildAssocs(this.testSiteNodeRef);
    assertTrue("The test site should not have any containers", children.isEmpty());
}
 
Example 37
Project: alfresco-remote-api   File: RemoteFileFolderLoaderTest.java   View source code 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 38
Project: alfresco-repository   File: LocalFeedTaskProcessor.java   View source code 5 votes vote down vote up
@Override
protected boolean canReadSite(final RepoCtx ctx, String siteIdIn, final String connectedUser, final String tenantDomain) throws Exception
{
    if (useRemoteCallbacks)
    {
        // note: not implemented
        throw new UnsupportedOperationException("Not implemented");
    }
    
    final String siteId = tenantService.getBaseName(siteIdIn, true);
    
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Boolean>()
    {
        public Boolean doWork() throws Exception
        {
            boolean canRead = false;
            SiteInfo siteInfo = siteService.getSite(siteId);
            if (siteInfo != null)
            {
                switch (siteInfo.getVisibility())
                {
                case MODERATED:
                    // moderated - note: need to check site membership
                    canRead = siteService.isMember(siteId, connectedUser);
                    break;
                case PUBLIC:
                case PRIVATE:
                    // public or private - note: for private site, membership is implied (since getSite did not return null)
                    canRead = true;
                    break;
                default:
                    break;
                }
            }
            return canRead;
        }
    }, connectedUser);
}
 
Example 39
Project: alfresco-repository   File: SiteServiceImplMoreTest.java   View source code 5 votes vote down vote up
@BeforeClass public static void initStaticData() throws Exception
{
    AUTHORITY_SERVICE         = APP_CONTEXT_INIT.getApplicationContext().getBean("AuthorityService", AuthorityService.class);
    NAMESPACE_SERVICE         = APP_CONTEXT_INIT.getApplicationContext().getBean("namespaceService", NamespaceService.class);
    NODE_SERVICE              = APP_CONTEXT_INIT.getApplicationContext().getBean("NodeService", NodeService.class);
    NODE_ARCHIVE_SERVICE      = APP_CONTEXT_INIT.getApplicationContext().getBean("nodeArchiveService", NodeArchiveService.class);
    SITE_SERVICE              = APP_CONTEXT_INIT.getApplicationContext().getBean("siteService", SiteService.class);
    COCI_SERVICE              = APP_CONTEXT_INIT.getApplicationContext().getBean("checkOutCheckInService", CheckOutCheckInService.class);
    TRANSACTION_HELPER        = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    PERMISSION_SERVICE        = APP_CONTEXT_INIT.getApplicationContext().getBean("permissionServiceImpl", PermissionService.class);
    AUTHENTICATION_SERVICE    = APP_CONTEXT_INIT.getApplicationContext().getBean("authenticationService", MutableAuthenticationService.class);
    PERSON_SERVICE            = APP_CONTEXT_INIT.getApplicationContext().getBean("PersonService", PersonService.class);
    FILE_FOLDER_SERVICE       = APP_CONTEXT_INIT.getApplicationContext().getBean("FileFolderService",FileFolderService.class);
    AUTHENTICATION_COMPONENT  = APP_CONTEXT_INIT.getApplicationContext().getBean("authenticationComponent",AuthenticationComponent.class);
    LOCK_SERVICE              = APP_CONTEXT_INIT.getApplicationContext().getBean("lockService",LockService.class);
    
    // We'll create this test content as admin.
    final String admin = AuthenticationUtil.getAdminUserName();
    
    TEST_SITE_NAME = GUID.generate();
    TEST_SUB_SITE_NAME = GUID.generate();
    
    final QName subSiteType = QName.createQName("testsite", "testSubsite", NAMESPACE_SERVICE);
    
    STATIC_TEST_SITES.createSite("sitePreset", TEST_SITE_NAME, "siteTitle", "siteDescription", SiteVisibility.PUBLIC, admin);
    STATIC_TEST_SITES.createSite("sitePreset", TEST_SUB_SITE_NAME, "siteTitle", "siteDescription", SiteVisibility.PUBLIC, subSiteType, admin);
    
    TEST_SITE_WITH_MEMBERS = STATIC_TEST_SITES.createTestSiteWithUserPerRole(SiteServiceImplMoreTest.class.getSimpleName(), "sitePreset", SiteVisibility.PUBLIC, admin);
}
 
Example 40
Project: alfresco-repository   File: MultiTDemoTest.java   View source code 5 votes vote down vote up
private int searchForDataDictionary(String tenantAdminName, final String query)
{
    return AuthenticationUtil.runAs(new RunAsWork<Integer>()
    {
        public Integer doWork() throws Exception
        {
            ResultSet resultSet = searchService.query(SPACES_STORE, SearchService.LANGUAGE_LUCENE, query, null);
            return resultSet.length();
        }
    }, tenantAdminName);
}