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

The following are Jave code examples for showing how to use setRunAsUser() 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: InviteServiceTest.java   View Source Code Vote up 6 votes
private JSONObject getInviteInfo(String inviteId, String inviteTicket, String inviteeUid) throws Exception
{
    String url = "/api/invite/" + inviteId + "/" + inviteTicket + "?inviteeUserName=" + inviteeUid;

    String runAsUser = AuthenticationUtil.getRunAsUser();

    Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);

    if (!runAsUser.equals(AuthenticationUtil.getRunAsUser()))
    {
        AuthenticationUtil.setRunAsUser(runAsUser);
    }

    JSONObject result = new JSONObject(response.getContentAsString());

    return result;
}
 
Example 2
Project: alfresco-remote-api   File: NodeApiTest.java   View Source Code Vote up 6 votes
/**
 * Creates authority context
 *
 * @param user
 * @return
 */
private void createAuthorityContext(String user)
{
    String groupName = "Group_ROOT" + GUID.generate();

    AuthenticationUtil.setRunAsUser(user);
    if (rootGroupName == null)
    {
        rootGroupName = authorityService.getName(AuthorityType.GROUP, groupName);
    }

    if (!authorityService.authorityExists(rootGroupName))
    {
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        rootGroupName = authorityService.createAuthority(AuthorityType.GROUP, groupName);
        groupA = authorityService.createAuthority(AuthorityType.GROUP, "Test_GroupA");
        authorityService.addAuthority(rootGroupName, groupA);
        groupB = authorityService.createAuthority(AuthorityType.GROUP, "Test_GroupB");
        authorityService.addAuthority(rootGroupName, groupB);
        authorityService.addAuthority(groupA, user1);
        authorityService.addAuthority(groupB, user2);
    }
}
 
Example 3
Project: alfresco-remote-api   File: ProcessesImplTest.java   View Source Code Vote up 6 votes
@Before
public void setUp() throws Exception
{
    applicationContext = ApplicationContextHelper.getApplicationContext(CONFIG_LOCATIONS);

    processes = (Processes) applicationContext.getBean(PROCESSES_BEAN_NAME);

    ServiceRegistry registry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY);
    workflowService = registry.getWorkflowService();
    personService = registry.getPersonService();

    transaction = registry.getTransactionService().getUserTransaction();
    transaction.begin();

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    AuthenticationUtil.setRunAsUser(AuthenticationUtil.getAdminUserName());

    NodeRef adminUserNodeRef = personService.getPerson(AuthenticationUtil.getAdminUserName());

    WorkflowDefinition workflowDefinition = findAppropriateWorkflowDefinitionId();

    for (int i = 0; i < ACTIVE_WORKFLOWS_INITIAL_AMOUNT; i++)
    {
        startWorkflow(workflowDefinition, adminUserNodeRef);
    }
}
 
Example 4
Project: alfresco-deauth   File: DeauthoriseInactiveUsers.java   View Source Code Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Override
public void beforeProcess() throws Throwable
{
    AuthenticationUtil.setRunAsUser(this.runAsUser);
    this.deauthorisedTxn.remove();
}
 
Example 5
Project: alfresco-repository   File: CifsAuthenticatorKerberosTest.java   View Source Code Vote up 5 votes
@Test
public void testMissingUserMappingWhenAutoCreateAllowed()
{
    UserRegistrySynchronizer userRegistrySynchronizer = makeUserRegistrySynchronizerStub(true);
    ((AbstractAuthenticationComponent) cifsAuthenticator.getAuthenticationComponent()).setUserRegistrySynchronizer(userRegistrySynchronizer);
    String username = cifsAuthenticator.mapUserNameToPerson(userMissingLocal, false);
    assertEquals("User that does not exist in repository can login when autoCreatePeopleOnLogin is allowed", username, userMissingLocal);
    // personService.personExists requires RunAsUser to be set
    AuthenticationUtil.setRunAsUser(AuthenticationUtil.getSystemUserName());
    assertTrue(personService.personExists(userMissingLocal));
}
 
Example 6
Project: alfresco-repository   File: LocalTestRunAsAuthenticatorFactory.java   View Source Code Vote up 5 votes
@Override
public boolean authenticate(RequiredAuthentication required, boolean isGuest)
{
    if (! emptyCredentials())
    {
        AuthenticationUtil.setRunAsUser(userName);
        return true;
    }
    return false;
}
 
Example 7
Project: alfresco-repository   File: RuleTriggerTest.java   View Source Code Vote up 5 votes
@Override
protected void onSetUpInTransaction() throws Exception
{
    ServiceRegistry serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY);
    this.nodeService = serviceRegistry.getNodeService();
    this.contentService = serviceRegistry.getContentService();
    
    AuthenticationUtil.setRunAsUser(AuthenticationUtil.getSystemUserName());
    
    this.testStoreRef = this.nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
    this.rootNodeRef = this.nodeService.getRootNode(this.testStoreRef);
}
 
Example 8
Project: alfresco-repository   File: CopyServiceImplTest.java   View Source Code Vote up 5 votes
/**
 * https://issues.alfresco.com/jira/browse/ALF-17549
 */
public void testALF17549() throws Exception
{
    permissionService.setPermission(rootNodeRef, USER_1, PermissionService.COORDINATOR, true);

    AuthenticationUtil.setRunAsUser(USER_1);

    String sourceName = "sourceNode.txt";
    Map<QName, Serializable> props = new HashMap<QName, Serializable>();

    props.put(ContentModel.PROP_NAME, sourceName);

    NodeRef sourceNodeRef = nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}" + sourceName), ContentModel.TYPE_CONTENT, props)
            .getChildRef();

    ContentWriter writer = contentService.getWriter(sourceNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setEncoding("UTF-8");
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.putContent("This is sample text content for unit test.");

    NodeRef targetNodeRef = nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}targetNode"), ContentModel.TYPE_FOLDER)
            .getChildRef();

    List<ChildAssociationRef> childAssoc = nodeService.getChildAssocs(targetNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}sourceNode.html"));

    assertEquals(0, childAssoc.size());

    Action action = this.actionService.createAction(TransformActionExecuter.NAME);

    action.setParameterValue(TransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_HTML);
    action.setParameterValue(TransformActionExecuter.PARAM_DESTINATION_FOLDER, targetNodeRef);
    action.setParameterValue(TransformActionExecuter.PARAM_ASSOC_QNAME, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy"));
    action.setParameterValue(TransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CONTAINS);
    actionService.executeAction(action, sourceNodeRef);

    childAssoc = nodeService.getChildAssocs(targetNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}sourceNode.html"));

    assertEquals(1, childAssoc.size());
}
 
Example 9
Project: alfresco-repository   File: ActionServiceImplTest.java   View Source Code Vote up 5 votes
/**
 * http://issues.alfresco.com/jira/browse/ALF-5027
 */
public void testALF5027() throws Exception
{
    String userName = "bob" + GUID.generate();
    createUser(userName);
    PermissionService permissionService = (PermissionService)applicationContext.getBean("PermissionService");
    permissionService.setPermission(rootNodeRef, userName, PermissionService.COORDINATOR, true);
    
    AuthenticationUtil.setRunAsUser(userName);
    
    NodeRef myNodeRef = nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}myTestNode" + GUID.generate()),
            ContentModel.TYPE_CONTENT).getChildRef();
    
    CheckOutCheckInService coci = (CheckOutCheckInService)applicationContext.getBean("CheckoutCheckinService");
    NodeRef workingcopy = coci.checkout(myNodeRef);
    assertNotNull(workingcopy);
    
    assertFalse(nodeService.hasAspect(myNodeRef, ContentModel.ASPECT_DUBLINCORE));
    
    Action action1 = this.actionService.createAction(AddFeaturesActionExecuter.NAME);
    action1.setParameterValue(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_DUBLINCORE);        
    actionService.executeAction(action1, myNodeRef);
    
    // The action should have been ignored since the node is locked
    assertFalse(nodeService.hasAspect(myNodeRef, ContentModel.ASPECT_DUBLINCORE));
    
    coci.checkin(workingcopy, null);
    actionService.executeAction(action1, myNodeRef);
    
    assertTrue(nodeService.hasAspect(myNodeRef, ContentModel.ASPECT_DUBLINCORE));
}
 
Example 10
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 11
Project: alfresco-remote-api   File: InviteByTicket.java   View Source Code Vote up 5 votes
@Override
protected Map<String, Object> executeImpl(final WebScriptRequest req, final Status status)
{
    String tenantDomain = TenantService.DEFAULT_DOMAIN;
    
    if (tenantService.isEnabled())
    {
        String inviteeUserName = req.getParameter(PARAM_INVITEE_USER_NAME);
        if (inviteeUserName != null)
        {
            tenantDomain = tenantService.getUserDomain(inviteeUserName);
        }
    }
    
    // run as system user
    String mtAwareSystemUser = tenantService.getDomainUser(AuthenticationUtil.getSystemUserName(), tenantDomain);
    
    Map<String, Object> ret = TenantUtil.runAsSystemTenant(new TenantRunAsWork<Map<String, Object>>()
    {
        public Map<String, Object> doWork() throws Exception
        {
            return execute(req, status);
        }
    }, tenantDomain);
    
    // authenticate as system for the rest of the webscript
    AuthenticationUtil.setRunAsUser(mtAwareSystemUser);
    
    return ret;
}
 
Example 12
Project: alfresco-remote-api   File: NodeLocatorWebScriptTest.java   View Source Code Vote up 5 votes
public void testUserHomeNodeLocator() throws Exception
{
    String url = baseURL + UserHomeNodeLocator.NAME;
    // Run as System User, no User Home.
    AuthenticationUtil.setRunAsUser(AuthenticationUtil.getSystemUserName());
    checkNodeLocator(url, null);
    
    //Run as Admin User
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    
    NodeRef admin = repositoryHelper.getPerson();
    NodeRef userHome = repositoryHelper.getUserHome(admin);
    
    checkNodeLocator(url, userHome);
}
 
Example 13
Project: alfresco-repository   File: ChainingUserRegistrySynchronizer.java   View Source Code Vote up 4 votes
public final void beforeProcess() throws Throwable
{
    // Authentication
    AuthenticationUtil.setRunAsUser(AuthenticationUtil.getSystemUserName());
}
 
Example 14
Project: alfresco-audit   File: AuditUserGet.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 */
@Override
public void beforeProcess() throws Throwable
{
    AuthenticationUtil.setRunAsUser(this.runAsUser);
}
 
Example 15
Project: alfresco-remote-api   File: GroupsTest.java   View Source Code Vote up 4 votes
/**
 * Creates authority context.
 *
 * @param userName
 *            The user to run as.
 */
private void createAuthorityContext(String userName) throws PublicApiException
{
    String groupName = "Group_ROOT" + GUID.generate();

    AuthenticationUtil.setRunAsUser(userName);
    if (rootGroupName == null)
    {
        rootGroupName = authorityService.getName(AuthorityType.GROUP, groupName);
    }

    if (!authorityService.authorityExists(rootGroupName))
    {
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

        rootGroupName = authorityService.createAuthority(AuthorityType.GROUP, groupName);
        authorityService.addAuthorityToZones(rootGroupName, zoneSet("APITEST.MYZONE"));
        authorityService.setAuthorityDisplayName(rootGroupName, "Root Group");

        String groupBAuthorityName = authorityService.createAuthority(AuthorityType.GROUP, "Test_GroupB" + GUID.generate());
        authorityService.setAuthorityDisplayName(groupBAuthorityName, "B Group");
        authorityService.addAuthority(rootGroupName, groupBAuthorityName);
        authorityService.addAuthorityToZones(groupBAuthorityName, zoneSet("APITEST.MYZONE"));
        when(groupBResultSetRow.getNodeRef()).thenReturn(authorityService.getAuthorityNodeRef(groupBAuthorityName));

        String groupAAuthorityName = authorityService.createAuthority(AuthorityType.GROUP, "Test_GroupA" + GUID.generate());
        authorityService.setAuthorityDisplayName(groupAAuthorityName, "A Group");
        authorityService.addAuthority(rootGroupName, groupAAuthorityName);
        authorityService.addAuthorityToZones(groupAAuthorityName, zoneSet("APITEST.MYZONE", "APITEST.ANOTHER"));
        when(groupAResultSetRow.getNodeRef()).thenReturn(authorityService.getAuthorityNodeRef(groupAAuthorityName));

        authorityService.addAuthority(groupAAuthorityName, user1);
        authorityService.addAuthority(groupBAuthorityName, user2);

        rootGroup = new Group();
        rootGroup.setId(rootGroupName);
        rootGroup.setDisplayName("Root Group");

        groupA = new Group();
        groupA.setId(groupAAuthorityName);
        groupA.setDisplayName("A Group");

        groupB = new Group();
        groupB.setId(groupBAuthorityName);
        groupB.setDisplayName("B Group");

        groupMemberA = new GroupMember();
        groupMemberA.setId(groupAAuthorityName);
        groupMemberA.setMemberType(AuthorityType.GROUP.toString());

        groupMemberB = new GroupMember();
        groupMemberB.setId(groupBAuthorityName);
        groupMemberB.setMemberType(AuthorityType.GROUP.toString());
    }

    {
        publicApiClient.setRequestContext(new RequestContext(networkOne.getId(), networkAdmin, "admin"));
        Person personAlice = new Person();
        String aliceId = "alice-" + UUID.randomUUID() + "@" + networkOne.getId();
        personAlice.setUserName(aliceId);
        personAlice.setId(aliceId);
        personAlice.setFirstName("Alice");
        personAlice.setEmail("[email protected]");
        personAlice.setPassword("password");
        personAlice.setEnabled(true);
        PublicApiClient.People people = publicApiClient.people();
        people.create(personAlice);
        personMember = new GroupMember();
        personMember.setId(personAlice.getId());
        personMember.setMemberType(MEMBER_TYPE_PERSON);
    }
}
 
Example 16
Project: alfresco-remote-api   File: NodeApiTest.java   View Source Code Vote up 4 votes
/**
 * Test update permission on a node
 *
 * @throws Exception
 */
private void testUpdatePermissionsOnNode() throws Exception
{
    // create folder with an empty document
    String postUrl = createFolder();
    String dId = createDocument(postUrl);

    // update permissions
    Document dUpdate = new Document();
    NodePermissions nodePermissions = new NodePermissions();
    List<NodePermissions.NodePermission> locallySetPermissions = new ArrayList<>();
    locallySetPermissions.add(new NodePermissions.NodePermission(groupA, PermissionService.CONSUMER, AccessStatus.ALLOWED.toString()));
    nodePermissions.setLocallySet(locallySetPermissions);
    dUpdate.setPermissions(nodePermissions);

    // update node
    HttpResponse response = put(URL_NODES, dId, toJsonAsStringNonNull(dUpdate), null, 200);
    Document documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);

    validatePermissionsAfterUpdate(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, documentResp.getId()), locallySetPermissions);

    // Check permissions on node for user2 (part of groupB)
    AuthenticationUtil.setRunAsUser(user2);
    assertTrue(permissionService.hasPermission(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, documentResp.getId()), PermissionService.CONSUMER) == AccessStatus.DENIED);

    // Check permissions on node for user1 (part of groupA)
    AuthenticationUtil.setRunAsUser(user1);
    assertTrue(permissionService.hasPermission(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, documentResp.getId()), PermissionService.CONSUMER) == AccessStatus.ALLOWED);

    // add two groups with different permissions for each
    locallySetPermissions.clear();
    locallySetPermissions.add(new NodePermissions.NodePermission(groupA, PermissionService.EDITOR, AccessStatus.ALLOWED.toString()));
    locallySetPermissions.add(new NodePermissions.NodePermission(groupB, PermissionService.CONSUMER, AccessStatus.ALLOWED.toString()));
    nodePermissions.setLocallySet(locallySetPermissions);
    dUpdate.setPermissions(nodePermissions);

    // update node
    response = put(URL_NODES, dId, toJsonAsStringNonNull(dUpdate), null, 200);
    documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);

    validatePermissionsAfterUpdate(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, documentResp.getId()), locallySetPermissions);

    // Check permissions on node for user2 (part of groupB)
    AuthenticationUtil.setRunAsUser(user2);
    assertTrue(permissionService.hasPermission(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, documentResp.getId()), PermissionService.CONSUMER) == AccessStatus.ALLOWED);
    assertTrue(permissionService.hasPermission(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, documentResp.getId()), PermissionService.EDITOR) == AccessStatus.DENIED);
    assertTrue(permissionService.hasPermission(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, documentResp.getId()), PermissionService.WRITE) == AccessStatus.DENIED);
    assertTrue(permissionService.hasPermission(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, documentResp.getId()), PermissionService.READ) == AccessStatus.ALLOWED);

    // Check permissions on node for user1 (part of groupA)
    AuthenticationUtil.setRunAsUser(user1);
    assertTrue(permissionService.hasPermission(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, documentResp.getId()), PermissionService.EDITOR) == AccessStatus.ALLOWED);
    assertTrue(permissionService.hasPermission(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, documentResp.getId()), PermissionService.WRITE) == AccessStatus.ALLOWED);
    assertTrue(permissionService.hasPermission(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, documentResp.getId()), PermissionService.READ) == AccessStatus.ALLOWED);
}