Search in sources :

Example 16 with RunAsWork

use of org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork in project alfresco-remote-api by Alfresco.

the class NodeArchiveServiceRestApiTest method createTestNode.

private NodeRef createTestNode(final String authenticatedUser, final String cmName, final boolean deleteNode) {
    AuthenticationUtil.setFullyAuthenticatedUser(authenticatedUser);
    return transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>() {

        public NodeRef execute() throws Throwable {
            return AuthenticationUtil.runAs(new RunAsWork<NodeRef>() {

                public NodeRef doWork() throws Exception {
                    // Create the test node.
                    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
                    props.put(ContentModel.PROP_NAME, cmName);
                    props.put(ContentModel.PROP_TITLE, TEST_TITLE);
                    props.put(ContentModel.PROP_DESCRIPTION, TEST_DESCRIPTION);
                    NodeRef nodeRef = nodeService.createNode(workStoreRootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_CONTENT, props).getChildRef();
                    if (deleteNode) {
                        // And intentionally delete it again.
                        // This will move it to the archive store.
                        nodeService.deleteNode(nodeRef);
                        // At his point the chAssRef.getChildRef  NodeRef will point to the
                        // location of the node before it got deleted. We need to store
                        // it's NodeRef *after* deletion, which will point to the archive store.
                        NodeRef archivedNode = nodeArchiveService.getArchivedNode(nodeRef);
                        return archivedNode;
                    }
                    return nodeRef;
                }
            }, AuthenticationUtil.getSystemUserName());
        }
    });
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) Serializable(java.io.Serializable) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) RunAsWork(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork) HashMap(java.util.HashMap) QName(org.alfresco.service.namespace.QName)

Example 17 with RunAsWork

use of org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork in project alfresco-remote-api by Alfresco.

the class InviteServiceTest method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    /**
     * We don't want to be authenticated as 'system' but run as 'InviterUser', because then
     * 'system' will be the creator for the sites and 'inviterUser' will be a nobody.
     */
    AuthenticationUtil.clearCurrentSecurityContext();
    // get references to services
    this.authenticationService = (MutableAuthenticationService) getServer().getApplicationContext().getBean("AuthenticationService");
    this.authenticationComponent = (AuthenticationComponent) getServer().getApplicationContext().getBean("AuthenticationComponent");
    this.personService = (PersonService) getServer().getApplicationContext().getBean("PersonService");
    this.siteService = (SiteService) getServer().getApplicationContext().getBean("SiteService");
    this.nodeService = (NodeService) getServer().getApplicationContext().getBean("NodeService");
    this.workflowService = (WorkflowService) getServer().getApplicationContext().getBean("WorkflowService");
    this.mutableAuthenticationDao = (MutableAuthenticationDao) getServer().getApplicationContext().getBean("authenticationDao");
    this.transactionService = (TransactionService) getServer().getApplicationContext().getBean("TransactionService");
    this.nodeArchiveService = (NodeArchiveService) getServer().getApplicationContext().getBean("nodeArchiveService");
    this.invitationServiceImpl = (InvitationServiceImpl) getServer().getApplicationContext().getBean("invitationService");
    ScriptInvitationService scriptInvitationService = (ScriptInvitationService) getServer().getApplicationContext().getBean("invitationServiceScript");
    scriptInvitationService.setSiteService(this.siteService);
    configureMailExecutorForTestMode(this.getServer());
    // We're using a MailActionExecuter defined in outboundSMTP-test-context.xml which
    // sets the testMode property to true via spring injection. This will prevent emails
    // from being sent from within this test case.
    // This MailExecutorAction bean is named "test-mail" but is in all other respects equivalent to the
    // 'real' executer bean. It is automatically included during OutboundSMTP subsystem startup.
    this.transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            // 
            // various setup operations which need to be run as system user
            // 
            AuthenticationUtil.runAs(new RunAsWork<Object>() {

                public Object doWork() throws Exception {
                    // Create new invitee email address list
                    inviteeEmailAddrs = new ArrayList<String>();
                    // Create inviter person
                    createPerson(PERSON_FIRSTNAME, PERSON_LASTNAME, USER_INVITER, INVITER_EMAIL);
                    // Create inviter2 person
                    createPerson(PERSON_FIRSTNAME, PERSON_LASTNAME, USER_INVITER_2, INVITER_EMAIL_2);
                    return null;
                }
            }, AuthenticationUtil.getSystemUserName());
            // The creation of sites is heavily dependent on the authenticated user.  We must ensure that,
            // when doing the runAs below, the user both 'runAs' and 'fullyAuthenticated'.  In order for
            // this to be the case, the security context MUST BE EMPTY now.  We could do the old
            // "defensive clear", but really there should not be any lurking authentications on this thread
            // after the context starts up.  If there are, that is a bug, and we fail explicitly here.
            String residuallyAuthenticatedUser = AuthenticationUtil.getFullyAuthenticatedUser();
            assertNull("Residual authentication on context-initiating thread (this thread):" + residuallyAuthenticatedUser, residuallyAuthenticatedUser);
            // 
            // various setup operations which need to be run as inviter user
            // 
            AuthenticationUtil.runAs(new RunAsWork<Object>() {

                public Object doWork() throws Exception {
                    // Create first site for Inviter to invite Invitee to
                    SiteInfo siteInfo = siteService.getSite(SITE_SHORT_NAME_INVITE_1);
                    if (siteInfo == null) {
                        siteService.createSite("InviteSitePreset", SITE_SHORT_NAME_INVITE_1, "InviteSiteTitle", "InviteSiteDescription", SiteVisibility.PUBLIC);
                    }
                    // Create second site for inviter to invite invitee to
                    siteInfo = siteService.getSite(SITE_SHORT_NAME_INVITE_2);
                    if (siteInfo == null) {
                        siteService.createSite("InviteSitePreset", SITE_SHORT_NAME_INVITE_2, "InviteSiteTitle", "InviteSiteDescription", SiteVisibility.PUBLIC);
                    }
                    // Create third site for inviter to invite invitee to
                    siteInfo = InviteServiceTest.this.siteService.getSite(SITE_SHORT_NAME_INVITE_3);
                    if (siteInfo == null) {
                        siteService.createSite("InviteSitePreset", SITE_SHORT_NAME_INVITE_3, "InviteSiteTitle", "InviteSiteDescription", SiteVisibility.PUBLIC);
                    }
                    // set inviter2's role on third site to collaborator
                    String inviterSiteRole = siteService.getMembersRole(SITE_SHORT_NAME_INVITE_3, USER_INVITER_2);
                    if ((inviterSiteRole == null) || (inviterSiteRole.equals(SiteModel.SITE_COLLABORATOR) == false)) {
                        siteService.setMembership(SITE_SHORT_NAME_INVITE_3, USER_INVITER_2, SiteModel.SITE_COLLABORATOR);
                    }
                    return null;
                }
            }, USER_INVITER);
            // Do tests as inviter user
            InviteServiceTest.this.authenticationComponent.setCurrentUser(USER_INVITER);
            return null;
        }
    });
}
Also used : ScriptInvitationService(org.alfresco.repo.invitation.script.ScriptInvitationService) SiteInfo(org.alfresco.service.cmr.site.SiteInfo) RunAsWork(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork)

Example 18 with RunAsWork

use of org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork in project alfresco-remote-api by Alfresco.

the class RemoteAuthenticatorFactoryTest method testEnabledUser.

@Test
public void testEnabledUser() throws Exception {
    final String username = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>() {

        @Override
        public String execute() throws Throwable {
            return AuthenticationUtil.runAs(new RunAsWork<String>() {

                @Override
                public String doWork() throws Exception {
                    return createPerson(true);
                }
            }, AuthenticationUtil.SYSTEM_USER_NAME);
        }
    }, false, true);
    // Mock a request with a username in the header
    HttpServletRequest mockHttpRequest = mock(HttpServletRequest.class);
    when(mockHttpRequest.getHeader("X-Alfresco-Remote-User")).thenReturn(username);
    when(mockHttpRequest.getScheme()).thenReturn("http");
    WebScriptServletRequest mockRequest = mock(WebScriptServletRequest.class);
    when(mockRequest.getHttpServletRequest()).thenReturn(mockHttpRequest);
    HttpServletResponse mockHttpResponse = mock(HttpServletResponse.class);
    WebScriptServletResponse mockResponse = mock(WebScriptServletResponse.class);
    when(mockResponse.getHttpServletResponse()).thenReturn(mockHttpResponse);
    Authenticator authenticator = remoteUserAuthenticatorFactory.create(mockRequest, mockResponse);
    assertTrue(authenticator.authenticate(RequiredAuthentication.user, false));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) RunAsWork(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork) HttpServletResponse(javax.servlet.http.HttpServletResponse) WebScriptServletResponse(org.springframework.extensions.webscripts.servlet.WebScriptServletResponse) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) Authenticator(org.springframework.extensions.webscripts.Authenticator) Test(org.junit.Test)

Example 19 with RunAsWork

use of org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork in project alfresco-remote-api by Alfresco.

the class RemoteAuthenticatorFactoryTest method testDisabledUser.

@Test
public void testDisabledUser() throws Exception {
    final String username = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>() {

        @Override
        public String execute() throws Throwable {
            return AuthenticationUtil.runAs(new RunAsWork<String>() {

                @Override
                public String doWork() throws Exception {
                    return createPerson(false);
                }
            }, AuthenticationUtil.SYSTEM_USER_NAME);
        }
    }, false, true);
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            return AuthenticationUtil.runAs(new RunAsWork<Void>() {

                @Override
                public Void doWork() throws Exception {
                    // Mock a request with a username in the header
                    HttpServletRequest mockHttpRequest = mock(HttpServletRequest.class);
                    when(mockHttpRequest.getHeader("X-Alfresco-Remote-User")).thenReturn(username);
                    when(mockHttpRequest.getScheme()).thenReturn("http");
                    WebScriptServletRequest mockRequest = mock(WebScriptServletRequest.class);
                    when(mockRequest.getHttpServletRequest()).thenReturn(mockHttpRequest);
                    HttpServletResponse mockHttpResponse = mock(HttpServletResponse.class);
                    WebScriptServletResponse mockResponse = mock(WebScriptServletResponse.class);
                    when(mockResponse.getHttpServletResponse()).thenReturn(mockHttpResponse);
                    Authenticator authenticator = remoteUserAuthenticatorFactory.create(mockRequest, mockResponse);
                    assertFalse(authenticator.authenticate(RequiredAuthentication.user, false));
                    return null;
                }
            }, AuthenticationUtil.SYSTEM_USER_NAME);
        }
    }, false, true);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) RunAsWork(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork) HttpServletResponse(javax.servlet.http.HttpServletResponse) WebScriptServletResponse(org.springframework.extensions.webscripts.servlet.WebScriptServletResponse) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) Authenticator(org.springframework.extensions.webscripts.Authenticator) Test(org.junit.Test)

Example 20 with RunAsWork

use of org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork in project records-management by Alfresco.

the class NoPermissionsOnTransferFolderTest method testNoPermissionsOnTransferFolder.

public void testNoPermissionsOnTransferFolder() {
    doBehaviourDrivenTest(new BehaviourDrivenTest(testUser1) {

        // Records folder
        private NodeRef recordsFolder = null;

        // Transfer folder
        private NodeRef transferFolder = null;

        /**
         * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#given()
         */
        @Override
        public void given() {
            runAs(new RunAsWork<Void>() {

                public Void doWork() {
                    // Create category
                    NodeRef category = filePlanService.createRecordCategory(filePlan, generate());
                    // Give filing permissions for the test users on the category
                    filePlanPermissionService.setPermission(category, testUser1, FILING);
                    filePlanPermissionService.setPermission(category, testUser2, FILING);
                    // Create disposition schedule
                    utils.createDispositionSchedule(category, DEFAULT_DISPOSITION_INSTRUCTIONS, DEFAULT_DISPOSITION_AUTHORITY, false, true, true);
                    // Create folder
                    recordsFolder = recordFolderService.createRecordFolder(category, generate());
                    // Make eligible for cut off
                    Map<String, Serializable> params = new HashMap<String, Serializable>(1);
                    params.put(PARAM_EVENT_NAME, DEFAULT_EVENT_NAME);
                    rmActionService.executeRecordsManagementAction(recordsFolder, CompleteEventAction.NAME, params);
                    // Cut off folder
                    rmActionService.executeRecordsManagementAction(recordsFolder, CutOffAction.NAME);
                    return null;
                }
            }, getAdminUserName());
            // FIXME: This step should be executed in "when()".
            // See RM-3931
            transferFolder = (NodeRef) rmActionService.executeRecordsManagementAction(recordsFolder, TransferAction.NAME).getValue();
        }

        /**
         * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#when()
         */
        @Override
        public void when() {
        // FIXME: If the transfer step is executed here the test fails. See RM-3931
        // transferFolder = (NodeRef) rmActionService.executeRecordsManagementAction(recordsFolder, TransferAction.NAME).getValue();
        }

        /**
         * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#then()
         */
        @Override
        public void then() {
            // Check transfer folder
            assertNotNull(transferFolder);
            // testUser1 should have read permissions on the transfers container
            assertEquals(ALLOWED, permissionService.hasPermission(transfersContainer, READ_RECORDS));
            // Check if testUser1 has filing permissions on the transfer folder
            assertEquals(ALLOWED, permissionService.hasPermission(transferFolder, FILING));
            runAs(new RunAsWork<Void>() {

                public Void doWork() {
                    // Check transfer folder
                    assertNotNull(transferFolder);
                    // testUser2 should have read permissions on the transfers container
                    assertEquals(ALLOWED, permissionService.hasPermission(transfersContainer, READ_RECORDS));
                    // Check if testUser2 has read permissions on the transfer folder
                    assertEquals(DENIED, permissionService.hasPermission(transferFolder, READ_RECORDS));
                    return null;
                }
            }, testUser2);
        }
    });
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) Serializable(java.io.Serializable) RunAsWork(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork) HashMap(java.util.HashMap)

Aggregations

RunAsWork (org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork)34 NodeRef (org.alfresco.service.cmr.repository.NodeRef)26 HashMap (java.util.HashMap)11 Serializable (java.io.Serializable)8 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)7 FileNotFoundException (org.alfresco.service.cmr.model.FileNotFoundException)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 FileExistsException (org.alfresco.service.cmr.model.FileExistsException)4 ContentWriter (org.alfresco.service.cmr.repository.ContentWriter)4 QName (org.alfresco.service.namespace.QName)4 HashSet (java.util.HashSet)3 Map (java.util.Map)3 Set (java.util.Set)3 AccessDeniedException (org.alfresco.repo.security.permissions.AccessDeniedException)3 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)3 SiteInfo (org.alfresco.service.cmr.site.SiteInfo)3 Version (org.alfresco.service.cmr.version.Version)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2