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

The following are Jave code examples for showing how to use clearCurrentSecurityContext() of the org.alfresco.repo.security.authentication.AuthenticationUtil class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: alfresco-remote-api   File: BaseCustomModelApiTest.java   View Source Code Vote up 6 votes
@After
public void tearDown() throws Exception
{
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    for (final String user : users)
    {
        transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                deleteUser(user, null);
                return null;
            }
        });
    }
    users.clear();
    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 2
Project: alfresco-repository   File: ImporterActionExecuterTest.java   View Source Code Vote up 6 votes
@AfterClass
public static void tearDown()
{
    try
    {
        serviceRegistry.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
        {
            public Void execute()
            {
                if (storeRef != null)
                {
                    nodeService.deleteStore(storeRef);
                }
                return null;
            }
        });
    }
    finally
    {
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}
 
Example 3
Project: alfresco-repository   File: AuthorityServiceTest.java   View Source Code Vote up 6 votes
public void testNoUser()
{
    pubAuthorityService.createAuthority(AuthorityType.GROUP, "DEFAULT");

    authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    PagingResults<String> results = pubAuthorityService.getAuthorities(
            AuthorityType.GROUP, null, null, true, true, new PagingRequest(10));
    AuthenticationUtil.clearCurrentSecurityContext();
    try
    {
        pubAuthorityService.getAuthorities(
                AuthorityType.GROUP, null, null, true, true, new PagingRequest(10));
        fail("Public AuthorityService should reject unauthorized use.");
    }
    catch (AuthenticationCredentialsNotFoundException e)
    {
        // Expected
    }
    PagingResults<String> resultsCheck = authorityService.getAuthorities(
            AuthorityType.GROUP, null, null, true, true, new PagingRequest(10));
    assertEquals(
            "Unauthorized use of private service should work just like 'admin'",
            results.getPage().size(), resultsCheck.getPage().size());
}
 
Example 4
Project: alfresco-audit   File: ConsolidateActiveUsersAuditJob.java   View Source Code Vote up 5 votes
protected void recordTimeframes(final String userName, final Set<Pair<String, String>> timeframes)
{
    for (final Pair<String, String> timeframe : timeframes)
    {
        final String timeframeStart = timeframe.getFirst();
        final String timeframeEnd = timeframe.getSecond();

        final boolean exists = this.checkEntryExists(userName, timeframeStart, timeframeEnd);

        if (!exists)
        {
            // recording should be done using the proper user name
            AuthenticationUtil.clearCurrentSecurityContext();
            AuthenticationUtil.setRunAsUser(userName);

            final String rootPath = AuditApplication.buildPath(AuditModuleConstants.AUDIT_PRODUCER_ROOT_PATH,
                    ConsolidateActiveUsersAuditJob.class.getSimpleName());
            final Map<String, Serializable> auditMap = new HashMap<>();
            auditMap.put("userName", userName);
            auditMap.put("timeframeStart", timeframeStart);
            auditMap.put("timeframeEnd", timeframeEnd);

            LOGGER.debug("Recording 'new' active user time frame {} to {}", timeframeStart, timeframeEnd);
            this.auditComponent.recordAuditValuesWithUserFilter(rootPath, auditMap, false);

            // reset for next iteration
            AuthenticationUtil.clearCurrentSecurityContext();
            AuthenticationUtil.setRunAsUserSystem();
        }
    }
}
 
Example 5
Project: alfresco-repository   File: UserAuditFilterTest.java   View Source Code Vote up 5 votes
@Override
public void tearDown() throws Exception
{
    AuthenticationUtil.clearCurrentSecurityContext();
    // Throw away the reconfigured registry state
    auditModelRegistry.destroy();
}
 
Example 6
Project: alfresco-repository   File: AuditComponentTest.java   View Source Code Vote up 5 votes
@Override
public void tearDown() throws Exception
{
    AuthenticationUtil.clearCurrentSecurityContext();
    // Throw away the reconfigured registry state
    auditModelRegistry.destroy();
}
 
Example 7
Project: alfresco-repository   File: PermissionServiceTest.java   View Source Code Vote up 5 votes
public void testRunAsRealAndEffectiveUsersWithNoPriorAuthentication()
{
    runAs(AuthenticationUtil.getAdminUserName());

    final NodeRef n1 = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}one"), ContentModel.TYPE_FOLDER).getChildRef();

    AuthenticationUtil.clearCurrentSecurityContext();

    assertNull(AuthenticationUtil.getFullyAuthenticatedUser());
    assertNull(AuthenticationUtil.getRunAsUser());

    AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
            {

        public Object doWork() throws Exception
        {
            assertTrue(permissionService.hasPermission(n1, getPermission(PermissionService.CONTRIBUTOR)) == AccessStatus.ALLOWED);

            assertEquals(AuthenticationUtil.getAdminUserName(), AuthenticationUtil.getFullyAuthenticatedUser());
            assertEquals(AuthenticationUtil.getAdminUserName(), AuthenticationUtil.getRunAsUser());
            return null;
        }
            }, AuthenticationUtil.getAdminUserName());

    assertNull(AuthenticationUtil.getFullyAuthenticatedUser());
    assertNull(AuthenticationUtil.getRunAsUser());
}
 
Example 8
Project: alfresco-repository   File: TestPersonManager.java   View Source Code Vote up 5 votes
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 9
Project: alfresco-remote-api   File: AbstractBaseApiTest.java   View Source Code Vote up 5 votes
@After
public void tearDown() throws Exception
{
    if ((networkOne != null) && (user1 != null) && (tSiteId != null))
    {
        setRequestContext(networkOne.getId(), user1, null);
        deleteSite(tSiteId, true, 204);
    }

    setRequestContext(networkAdmin);
    
    for (final String username : users)
    {
        transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                deleteUser(username, networkOne);
                return null;
            }
        });
    }
    
    users.clear();
    AuthenticationUtil.clearCurrentSecurityContext();
    setRequestContext(null);
}
 
Example 10
Project: alfresco-repository   File: AbstractPermissionTest.java   View Source Code Vote up 5 votes
@Override
protected void tearDown() throws Exception
{
    try
    {
        testTX.rollback();
    }
    catch (Throwable e)
    {
        e.printStackTrace();
    }
    AuthenticationUtil.clearCurrentSecurityContext();
    super.tearDown();
}
 
Example 11
Project: alfresco-remote-api   File: CustomModelImportTest.java   View Source Code Vote up 5 votes
@Override
protected void setUp() throws Exception
{
    super.setUp();
    authenticationService = getServer().getApplicationContext().getBean("AuthenticationService", MutableAuthenticationService.class);
    authorityService = getServer().getApplicationContext().getBean("AuthorityService", AuthorityService.class);
    personService = getServer().getApplicationContext().getBean("PersonService", PersonService.class);
    transactionHelper = getServer().getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    customModelService = getServer().getApplicationContext().getBean("customModelService", CustomModelService.class);

    AuthenticationUtil.clearCurrentSecurityContext();

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

            if (!authorityService.getContainingAuthorities(AuthorityType.GROUP, CUSTOM_MODEL_ADMIN, true).contains(
                        CustomModelServiceImpl.GROUP_ALFRESCO_MODEL_ADMINISTRATORS_AUTHORITY))
            {
                authorityService.addAuthority(CustomModelServiceImpl.GROUP_ALFRESCO_MODEL_ADMINISTRATORS_AUTHORITY, CUSTOM_MODEL_ADMIN);
            }
            return null;
        }
    });
    AuthenticationUtil.setFullyAuthenticatedUser(CUSTOM_MODEL_ADMIN);
}
 
Example 12
Project: alfresco-repository   File: SubscriptionServiceActivitiesTest.java   View Source Code Vote up 4 votes
@AfterClass public static void restartQuartzScheduler() throws SchedulerException
{
    // We put the scheduler in standby mode BeforeClass. Now we must restore it.
    QUARTZ_SCHEDULER.start();
    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 13
Project: alfresco-remote-api   File: CustomModelImportTest.java   View Source Code Vote up 4 votes
@Override
public void tearDown() throws Exception
{
    for (File file : tempFiles)
    {
        file.delete();
    }

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

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

    AuthenticationUtil.clearCurrentSecurityContext();

    super.tearDown();
}
 
Example 14
Project: alfresco-repository   File: HomeFolderProviderSynchronizerTest.java   View Source Code Vote up 4 votes
@After
public void tearDown() throws Exception
{
    if (trans != null)
    {
        try
        {
            trans.commit();
            trans = null;
        }
        catch (Exception e)
        {
            if ((trans.getStatus() == Status.STATUS_ACTIVE) ||
                (trans.getStatus() == Status.STATUS_MARKED_ROLLBACK))
            {
                trans.rollback();
                trans = null;
            }
        }
    }

    RetryingTransactionCallback<Void> cleanup = new RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            Set<NodeRef> adminGuestUserHomeFolders = deleteNonAdminGuestUsers();
            deleteNonAdminGuestFolders(adminGuestUserHomeFolders);
            deleteAllTenants();
            return null;
        }
    };
    try
    {
        transactionService.getRetryingTransactionHelper().doInTransaction(cleanup);
    }
    finally
    {
        AuthenticationUtil.clearCurrentSecurityContext();
        userNameMatcher.setUserNamesAreCaseSensitive(false); // Put back the default
    }
}
 
Example 15
Project: alfresco-repository   File: RetryingTransactionHelperTestCase.java   View Source Code Vote up 4 votes
/**
 * Executes a test in a retrying transaction. 
 * 
 * @param test   failure test object
 * @param asUser user to run test as
 */
protected void doTestInTransaction(final FailureTest test, final String asUser)
{
    String origUser = AuthenticationUtil.getFullyAuthenticatedUser();
    AuthenticationUtil.setFullyAuthenticatedUser(asUser);
    try
    {
        RetryingTransactionCallback<Void> doRun = new RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {         
                Class<?> eType = test.getExpectedExceptionClass();                
                try
                {
                    test.run();
                }
                catch (Throwable exception)
                {   
                    if (eType.isInstance(exception) == false)
                    {
                        // Genuine error so re-throw
                        throw exception;
                    }
                    
                    // Otherwise, it's an expected failure 
                    return null;
                }               
                
                // Fail since not expected to succeed
                fail(test.getMessage());
                return null;
            }            
        };        
        getRetryingTransactionHelper().doInTransaction(doRun);
    }
    finally
    {
        if (origUser != null)
        {
            AuthenticationUtil.setFullyAuthenticatedUser(origUser);
        }
        else
        {
            AuthenticationUtil.clearCurrentSecurityContext();
        }
    } 
}
 
Example 16
Project: alfresco-repository   File: FileFolderLoaderTest.java   View Source Code Vote up 4 votes
@Override
public void setUp() throws Exception
{
    // Make sure we don't get leaked threads from other tests
    AuthenticationUtil.clearCurrentSecurityContext();
    AuthenticationUtil.pushAuthentication();

    RunAsWork<Void> setUpWork = new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            fileFolderLoader = (FileFolderLoader) ctx.getBean("FileFolderLoader");
            fileFolderService = (FileFolderService) ctx.getBean("FileFolderService");
            permissionService = (PermissionService) ctx.getBean("PermissionService");
            transactionService = (TransactionService) ctx.getBean("TransactionService");
            nodeService = (NodeService) ctx.getBean("nodeService");
            NodeRef companyHomeNodeRef = fileFolderLoader.getRepository().getCompanyHome();
            NodeRef sharedHomeNodeRef = fileFolderLoader.getRepository().getSharedHome();
            List<FileInfo> sharedHomeFileInfos = fileFolderService.getNamePath(companyHomeNodeRef, sharedHomeNodeRef);
            sharedHomePath = "/" + sharedHomeFileInfos.get(0).getName();
            
            // Create a folder that will be invisible to all normal users
            FileInfo hiddenFolderInfo = fileFolderService.create(sharedHomeNodeRef, "HideThis", ContentModel.TYPE_FOLDER);
            hiddenFolderNodeRef = hiddenFolderInfo.getNodeRef();
            hiddenFolderPath = sharedHomePath + "/HideThis";
            permissionService.setInheritParentPermissions(hiddenFolderNodeRef, false);
            
            // Create a folder that will be read-only
            FileInfo readOnlyFolderInfo = fileFolderService.create(sharedHomeNodeRef, "ReadOnlyThis", ContentModel.TYPE_FOLDER);
            readOnlyFolderNodeRef = readOnlyFolderInfo.getNodeRef();
            readOnlyFolderPath = sharedHomePath + "/ReadOnlyThis";
            permissionService.setInheritParentPermissions(readOnlyFolderNodeRef, false);
            permissionService.setPermission(readOnlyFolderNodeRef, PermissionService.ALL_AUTHORITIES, PermissionService.READ, true);
            
            // Create a folder to write to
            FileInfo writeFolderInfo = fileFolderService.create(sharedHomeNodeRef, "WriteThis", ContentModel.TYPE_FOLDER);
            writeFolderNodeRef = writeFolderInfo.getNodeRef();
            writeFolderPath = sharedHomePath + "/WriteThis";
            
            // Done
            return null;
        }
    };
    AuthenticationUtil.runAsSystem(setUpWork);
}
 
Example 17
Project: alfresco-repository   File: GetChildrenCannedQueryTest.java   View Source Code Vote up 4 votes
public void testPagingGetChildrenCannedQueryWithoutProps() throws Exception
{
    try
    {
        long startTime = System.currentTimeMillis();

        int itemCount = 1500;
        int repeatListCount = 5;

        Set<QName> assocTypeQNames = new HashSet<>(1);
        assocTypeQNames.add(ContentModel.ASSOC_CONTAINS);

        Set<QName> childTypeQNames = new HashSet<>(1);
        childTypeQNames.add(ContentModel.TYPE_FOLDER);

        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

        NodeRef testFolder = repositoryHelper.getCompanyHome();

        NodeRef parentFolder = createFolder(testFolder, "testCreateList-"+ GUID.generate(), ContentModel.TYPE_FOLDER);

        for (int i = 1; i <= itemCount; i++)
        {
            String folderName = "folder_" + GUID.generate();
            createFolder(parentFolder, folderName, ContentModel.TYPE_FOLDER);
        }

        for (int j = 1; j <= repeatListCount; j++)
        {
            // page/iterate through the children
            boolean hasMore = true;
            int skipCount = 0;
            int maxItems = 100;

            int count = 0;
            Set<String> docIds = new HashSet<>(itemCount);

            while (hasMore)
            {
                // note: mimic similar to AlfrescoServiceCmisServiceImpl
                PagingResults<NodeRef> results = list(parentFolder, skipCount, maxItems, skipCount + 10000, assocTypeQNames, childTypeQNames, null, null, null, null);
                hasMore = results.hasMoreItems();
                skipCount = skipCount + maxItems;

                for (NodeRef nodeRef : results.getPage())
                {
                    docIds.add(nodeRef.getId());
                    count++;
                }
            }

            assertEquals(itemCount, count);
            assertEquals(itemCount, docIds.size());
        }

        System.out.println("Test time: " + (System.currentTimeMillis() - startTime) + " ms");
    } 
    finally
    {
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}
 
Example 18
Project: alfresco-remote-api   File: RepositoryContainerTest.java   View Source Code Vote up 4 votes
@Override
protected void tearDown() throws Exception
{
    AuthenticationUtil.clearCurrentSecurityContext();
    super.tearDown();
}
 
Example 19
Project: alfresco-repository   File: RetryingTransactionHelperTestCase.java   View Source Code Vote up 4 votes
/**
 * Executes a test in a retrying transaction as the admin user.
 * 
 * @param <A>    type of the object resulting from the test, can be set to {@link Void} if none.
 * @param test   test object to be executed within a retrying transaction
 * @param asUser user to execute the test as
 * @return A     the result of the test
 */
protected <A> A doTestInTransaction(final Test<A> test, final String asUser)
{    
    String origUser = AuthenticationUtil.getFullyAuthenticatedUser();
    AuthenticationUtil.setFullyAuthenticatedUser(asUser);
    try
    {        
        // Execute the run() method within a retrying transaction
        RetryingTransactionCallback<A> doRun = new RetryingTransactionCallback<A>()
        {
            @Override
            public A execute() throws Throwable
            {
                // Run test as user
                return test.run();              
            }            
        };                
        final A result = getRetryingTransactionHelper().doInTransaction(doRun);
        
        // Execute the test() method within a retrying transaction
        RetryingTransactionCallback<Void> doTest = new RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                // pass the result of the run into the test
                test.test(result);
                return null;                    
            }
            
        };
        getRetryingTransactionHelper().doInTransaction(doTest);
        
        return result;
    }
    finally
    {
        if (origUser != null)
        {
            AuthenticationUtil.setFullyAuthenticatedUser(origUser);
        }
        else
        {
            AuthenticationUtil.clearCurrentSecurityContext();
        }
    }                   
}
 
Example 20
Project: alfresco-repository   File: SolrFacetQueriesDisplayHandlersTest.java   View Source Code Vote up 2 votes
/**
 * Perform post-test clean-up.
 *
 * @throws Exception
 *         if the clean-up fails for some reason
 *
 */
@After
public void tearDown() throws Exception
{
    AuthenticationUtil.clearCurrentSecurityContext();
}