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

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultiTDemoTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void test07LoginTenantGuests() throws Throwable
{
    logger.info("Login tenant guests");
    
    try
    {
        AuthenticationUtil.clearCurrentSecurityContext();
        
        for (final String tenantDomain : tenants)
        {
            loginLogoutUser(tenantService.getDomainUser(DEFAULT_GUEST_UN, tenantDomain), DEFAULT_GUEST_UN);
        }
    }   
    catch (Throwable t)
    {
        StringWriter stackTrace = new StringWriter();
        t.printStackTrace(new PrintWriter(stackTrace));
        System.err.println(stackTrace.toString());
        throw t;
    }
}
 
Example #2
Source File: WebDAVLockServiceImplTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void mnt13183LockInfo()
{
    // CIFS lock node to 1 hour
    lockService.lock(nodeRef1, LockType.WRITE_LOCK, 3600, Lifetime.EPHEMERAL, "lock_info_that_is_not_from_webdav");

    // WebDAV get lock info
    LockInfo lockInfoNodeRef1 = davLockService.getLockInfo(nodeRef1);
    assertNull("exclusiveLockToken is null", lockInfoNodeRef1.getExclusiveLockToken());
    
    String user = AuthenticationUtil.getFullyAuthenticatedUser();
    
    // WebDav lock, check marker
    davLockService.lock(nodeRef2, user, 3600);
    
    LockState lockState2 = lockService.getLockState(nodeRef2);
    assertNotNull("lockState is not null", lockState2);
    
    String additionalInfo2 = lockState2.getAdditionalInfo();
    assertNotNull("additionalInfo is not null", additionalInfo2);
    assertTrue("Check WEBDAV_LOCK marker", additionalInfo2.startsWith(LockInfoImpl.ADDINFO_WEBDAV_MARKER));   
}
 
Example #3
Source File: CustomModelImportTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testValidUpload_ExtModuleOnly() throws Exception
{
    File zipFile = getResourceFile("validExtModule.zip");
    PostRequest postRequest = buildMultipartPostRequest(zipFile);

    AuthenticationUtil.setFullyAuthenticatedUser(NON_ADMIN_USER);
    Response response = sendRequest(postRequest, 403);

    AuthenticationUtil.setFullyAuthenticatedUser(CUSTOM_MODEL_ADMIN);
    response = sendRequest(postRequest, 200);

    JSONObject json = new JSONObject(new JSONTokener(response.getContentAsString()));
    assertFalse(json.has("modelName"));

    String extModule = json.getString("shareExtModule");
    Document document = XMLUtil.parse(extModule);
    NodeList nodes = document.getElementsByTagName("id");
    assertEquals(1, nodes.getLength());
    assertNotNull(nodes.item(0).getTextContent());
}
 
Example #4
Source File: FileFolderServicePropagationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testPreservingPropertiesOfFolderMnt8109() throws Exception
{
    try
    {
        Thread.sleep(1000);
    }
    catch (Exception e)
    {
        // Just stop to wait for the end of...
    }

    // Enabling preservation of modification properties data...
    fileFolderService.setPreserveAuditableData(true);
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_NAME);
            moveObjectAndAssert(testFolder);
            return null;
        }
    });
}
 
Example #5
Source File: MoveMethod.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Unlock only if the node was locked in the first place.
 */
private void unlock(final NodeRef nodeRef, LockInfo lockInfo)
{
    if (lockInfo != null && lockInfo.isLocked())
    {
        if (lockInfo.isExpired())
        {
            // If the lock expired unlock as system user
            AuthenticationUtil.runAs(new RunAsWork<Void>()
            {
                public Void doWork() throws Exception
                {
                    getDAVHelper().getLockService().unlock(nodeRef);
                    return null;
                }
            }, AuthenticationUtil.getSystemUserName());
        }
        // else unlock as current user
        else
        {
            getDAVHelper().getLockService().unlock(nodeRef);
        }
    }
}
 
Example #6
Source File: PeopleTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void tearDown() throws Exception
{        
    try
    {
        txn.rollback();
    }
    catch (Throwable e)
    {
        e.printStackTrace();
    }

    AuthenticationUtil.clearCurrentSecurityContext();

    people.setServiceRegistry(serviceRegistry);
}
 
Example #7
Source File: ReadOnlyTransactionInGetRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void tearDown() throws Exception
{
    super.tearDown();
    
    SiteInfo site = siteService.getSite(TEST_SITE_NAME);
    // use retrying transaction to delete the site
    this.transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            // delete the test site
            siteService.deleteSite(TEST_SITE_NAME);
            
            return null;
        }
    });
    nodeArchiveService.purgeArchivedNode(nodeArchiveService.getArchivedNode(site.getNodeRef()));
    
    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example #8
Source File: AuthenticationFilter.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Run the authentication filter
 * 
 * @param context ServletContext
 * @param req ServletRequest
 * @param resp ServletResponse
 * @param chain FilterChain
 * @exception ServletException
 * @exception IOException
 */
@Override
public void doFilter(ServletContext context, ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException
{
    try
    {
        doFilterInternal(context, req, resp, chain);
    }
    finally
    {
        if (logger.isTraceEnabled())
        {
            logger.debug("About to clear the security context");
        }
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}
 
Example #9
Source File: RatingServiceIntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@BeforeClass public static void initStaticData() throws Exception
{
    COPY_SERVICE              = (CopyService)                 APP_CONTEXT_INIT.getApplicationContext().getBean("copyService");
    NODE_SERVICE              = (NodeService)                 APP_CONTEXT_INIT.getApplicationContext().getBean("nodeService");
    RATING_NAMING_CONVENTIONS = (RatingNamingConventionsUtil) APP_CONTEXT_INIT.getApplicationContext().getBean("rollupNamingConventions");
    RATING_SERVICE            = (RatingService)               APP_CONTEXT_INIT.getApplicationContext().getBean("ratingService");
    SCRIPT_SERVICE            = (ScriptService)               APP_CONTEXT_INIT.getApplicationContext().getBean("scriptService");
    TRANSACTION_HELPER        = (RetryingTransactionHelper)   APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper");
    
    Repository repositoryHelper = (Repository) APP_CONTEXT_INIT.getApplicationContext().getBean("repositoryHelper");
    COMPANY_HOME = repositoryHelper.getCompanyHome();
    
    // Create some static test content
    TEST_FOLDER = STATIC_TEST_NODES.createNode(COMPANY_HOME, "testFolder", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
    COPY_DEST_FOLDER = STATIC_TEST_NODES.createNode(COMPANY_HOME, "testCopyDestinationFolder", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());

}
 
Example #10
Source File: ScriptSiteService.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Get a site for a provided site short name.
 * <p>
 * Returns null if the site does not exist.
 * 
 * @param shortName short name of the site
 * @return Site the site, null if does not exist
 */
public Site getSite(final String shortName)
{
    SiteInfo siteInfo = null;
    Site site = null;
    if (siteService.isSiteAdmin(AuthenticationUtil.getFullyAuthenticatedUser()))
    {
        siteInfo = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<SiteInfo>()
        {
            public SiteInfo doWork() throws Exception
            {
                return siteService.getSite(shortName);
            }
        }, AuthenticationUtil.getAdminUserName());
    }
    else
    {
        siteInfo = this.siteService.getSite(shortName);
    }

    if (siteInfo != null)
    {
        site = new Site(siteInfo, this.serviceRegistry, this.siteService, getScope());
    }
    return site;
}
 
Example #11
Source File: RatingRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void tearDown() throws Exception
{
    super.tearDown();

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());

    transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
            {
                public Void execute() throws Throwable
                {
                    if (testNode != null && nodeService.exists(testNode))
                    {
                        nodeService.deleteNode(testNode);
                        deleteUser(USER_ONE);
                        deleteUser(USER_TWO);
                    }
                    return null;
                }          
            });        
}
 
Example #12
Source File: Repository.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Gets the currently authenticated person
 * Includes any overlay authentication set by runas 
 * @return  person node ref
 */
public NodeRef getPerson()
{
    RetryingTransactionCallback<NodeRef> callback = new RetryingTransactionCallback<NodeRef>()
    {
        @Override
        public NodeRef execute() throws Throwable
        {
            NodeRef person = null;
            String currentUserName = AuthenticationUtil.getRunAsUser();
            if (currentUserName != null)
            {
                if (personService.personExists(currentUserName))
                {
                    person = personService.getPerson(currentUserName);
                }
            }
            return person;
        }
    };
    return retryingTransactionHelper.doInTransaction(callback, true);
}
 
Example #13
Source File: FeedNotifierJobTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@After
public void cleanUp()
{
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        @SuppressWarnings("synthetic-access")
        public Void execute() throws Throwable
        {
            personService.deletePerson(failingPersonNodeRef);
            personService.deletePerson(personNodeRef);
            return null;
        }
    }, false, true);
    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example #14
Source File: BaseCustomModelApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #15
Source File: RepoStore.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public Object findTemplateSource(final String name)
    throws IOException
{
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>()
            {
                public Object execute() throws Exception
                {
                    RepoTemplateSource source = null;
                    NodeRef nodeRef = findNodeRef(name);
                    if (nodeRef != null)
                    {
                        source = new RepoTemplateSource(nodeRef);
                    }
                    return source;
                }
            }, true);
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example #16
Source File: WebDAVMethodTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void checkLockedNodeTenantTest()
{
    setUpApplicationContext();

    // Create a tenant domain
    TenantUtil.runAsSystemTenant(new TenantUtil.TenantRunAsWork<Object>() {
        public Object doWork() throws Exception {
            if (!tenantAdminService.existsTenant(TEST_TENANT_DOMAIN))
            {
                tenantAdminService.createTenant(TEST_TENANT_DOMAIN, (DEFAULT_ADMIN_PW + " " + TEST_TENANT_DOMAIN).toCharArray(), null);
            }
            return null;
        }
    }, TenantService.DEFAULT_DOMAIN);
    
    TenantUtil.runAsUserTenant(new TenantUtil.TenantRunAsWork<Object>()
    {
        @Override
        public Object doWork() throws Exception
        {
            checkLockedNodeTestTenantWork();
            return null;
        }
    }, AuthenticationUtil.getAdminUserName(), TEST_TENANT_DOMAIN);
}
 
Example #17
Source File: HomeFolderProviderSynchronizer.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #18
Source File: ReplicationRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void tearDown() throws Exception
{
    super.tearDown();
    
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();
    
    personManager.clearPeople();
    
    // Zap any replication definitions we created
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    for(ReplicationDefinition rd : replicationService.loadReplicationDefinitions()) {
       replicationService.deleteReplicationDefinition(rd);
    }
    AuthenticationUtil.clearCurrentSecurityContext();
    
    txn.commit();
}
 
Example #19
Source File: SubscriptionServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext(CONTEXTS);
    // Get the required services
    transactionService = (TransactionService) ctx.getBean("TransactionService");
    subscriptionService = (SubscriptionService) ctx.getBean("SubscriptionService");
    personService = (PersonService) ctx.getBean("PersonService");
    nodeService = (NodeService) ctx.getBean("NodeService");
    searchService = (SearchService) ctx.getBean("SearchService");
    repositoryHelper = (Repository) ctx.getBean("repositoryHelper");

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());

    txn = transactionService.getNonPropagatingUserTransaction(false);
    txn.begin();

    createPerson(USER_BOB);
    createPerson(USER_TOM);
    createPerson(USER_LISA);
}
 
Example #20
Source File: MultiTDemoTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void test18AddCustomWebClient()
{
    // note: add as demo files - need to re-start Alfresco to see custom web client config / messages 
    logger.info("test add custom web client config");
    
    for (final String tenantDomain : tenants)
    {    
        final String tenantAdminName = tenantService.getDomainUser(AuthenticationUtil.getAdminUserName(), tenantDomain);
        
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Object>()
        {
            public Object doWork() throws Exception
            {
                NodeRef webClientExtFolder = getWebClientExtensionNodeRef(SPACES_STORE);
                
                InputStream is = getClass().getClassLoader().getResourceAsStream("tenant/webclient.properties");
                addContent(webClientExtFolder, "webclient.properties", is, MimetypeMap.MIMETYPE_TEXT_PLAIN);
                
                is = getClass().getClassLoader().getResourceAsStream("tenant/web-client-config-custom.xml");
                addContent(webClientExtFolder, "web-client-config-custom.xml", is, MimetypeMap.MIMETYPE_XML);
                
                return null;
            }
        }, tenantAdminName, tenantDomain);
    }
}
 
Example #21
Source File: MultiUserRenditionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@After public void tidyUpUnwantedNodeRefs()
{
    AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER);
    
    txnHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
            {
                public Void execute() throws Throwable
                {
                    for (NodeRef node : nodesToBeTidiedUp)
                    {
                        if (nodeService.exists(node))
                            nodeService.deleteNode(node);
                    }
                    return null;
                }
            });  
    nodesToBeTidiedUp.clear();
}
 
Example #22
Source File: AuditAppTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void testRetrieveAuditEntry(AuditApps auditAppsProxy, AuditApp auditApp) throws Exception
{
    int skipCount = 0;
    int maxItems = 4;
    Paging paging = getPaging(skipCount, maxItems);

    Map<String, String> otherParams = new HashMap<>();
    ListResponse<AuditEntry> resp = auditAppsProxy.getAuditAppEntries(auditApp.getId(),
            createParams(paging, otherParams), HttpServletResponse.SC_OK);
    String id = resp.getList().get(0).getId().toString();

    //Positive tests
    //200
    AuditEntry entryResp = auditAppsProxy.getAuditEntry(auditApp.getId(), id, null, HttpServletResponse.SC_OK);
    validateAuditEntryFields(entryResp, auditApp);
    assertNotNull(entryResp.getValues());

    // Negative tests
    // 400
    auditAppsProxy.getAuditEntry(auditApp.getId(), id+"invalidIdText", null, HttpServletResponse.SC_BAD_REQUEST);
    // 401
    setRequestContext(networkOne.getId(), networkAdmin, "wrongPassword");
    auditAppsProxy.getAuditEntry(auditApp.getId(), id, null, HttpServletResponse.SC_UNAUTHORIZED);
    // 403
    setRequestContext(networkOne.getId(), user1, null);
    auditAppsProxy.getAuditEntry(auditApp.getId(), id, null, HttpServletResponse.SC_FORBIDDEN);
    // 404
    setRequestContext(networkOne.getId(), networkAdmin, DEFAULT_ADMIN_PWD);
    auditAppsProxy.getAuditEntry(auditApp.getId(), "" + Math.abs(new Random().nextLong()), null, HttpServletResponse.SC_NOT_FOUND);
    // 501
    setRequestContext(networkOne.getId(), networkAdmin, DEFAULT_ADMIN_PWD);
    AuthenticationUtil.setFullyAuthenticatedUser(networkAdmin);
    disableSystemAudit();
    auditAppsProxy.getAuditEntry(auditApp.getId(), id, null, HttpServletResponse.SC_NOT_IMPLEMENTED);
    enableSystemAudit();
}
 
Example #23
Source File: CustomModelImportTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    authenticationService = getServer().getApplicationContext().getBean("AuthenticationService", MutableAuthenticationService.class);
    authorityService = getServer().getApplicationContext().getBean("AuthorityService", AuthorityService.class);
    personService = getServer().getApplicationContext().getBean("PersonService", PersonService.class);
    transactionHelper = getServer().getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    customModelService = getServer().getApplicationContext().getBean("customModelService", CustomModelService.class);

    AuthenticationUtil.clearCurrentSecurityContext();

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

            if (!authorityService.getContainingAuthorities(AuthorityType.GROUP, CUSTOM_MODEL_ADMIN, true).contains(
                        CustomModelServiceImpl.GROUP_ALFRESCO_MODEL_ADMINISTRATORS_AUTHORITY))
            {
                authorityService.addAuthority(CustomModelServiceImpl.GROUP_ALFRESCO_MODEL_ADMINISTRATORS_AUTHORITY, CUSTOM_MODEL_ADMIN);
            }
            return null;
        }
    });
    AuthenticationUtil.setFullyAuthenticatedUser(CUSTOM_MODEL_ADMIN);
}
 
Example #24
Source File: MessageServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void tearDown() throws Exception
{
    if (testTX != null)
    {
        try
        {
            testTX.rollback();
        }
        catch (Throwable e) {} // Ignore
    }
    AuthenticationUtil.clearCurrentSecurityContext();
    super.tearDown();
}
 
Example #25
Source File: MultiTDemoTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void test06LoginTenantUsers() throws Throwable
{
    // use common setup
    logger.info("Login tenant users");
    
    try
    {
        AuthenticationUtil.clearCurrentSecurityContext();
        
        for (final String tenantDomain : tenants)
        {
            loginLogoutUser(tenantService.getDomainUser(TEST_USER1, tenantDomain), TEST_USER1+" "+tenantDomain);
            
            loginLogoutUser(tenantService.getDomainUser(TEST_USER2, tenantDomain), TEST_USER2+" "+tenantDomain);
            
            if (tenantDomain.equals(TEST_TENANT_DOMAIN2))
            {
                loginLogoutUser(tenantService.getDomainUser(TEST_USER3, tenantDomain), TEST_USER3+" "+tenantDomain);
            }
        }
    }   
    catch (Throwable t)
    {
        StringWriter stackTrace = new StringWriter();
        t.printStackTrace(new PrintWriter(stackTrace));
        System.err.println(stackTrace.toString());
        throw t;
    }
}
 
Example #26
Source File: SiteServiceBootstrap.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void onBootstrap(ApplicationEvent event)
{
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            siteService.listSites("a");
            return null;
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example #27
Source File: VirtualRatingServiceExtensionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void applyRatingAs(final NodeRef targetNode, final float rating, final String ratingSchemeName,
            String asUser) throws RatingServiceException
{

    String fau = AuthenticationUtil.getFullyAuthenticatedUser();
    try
    {
        AuthenticationUtil.setFullyAuthenticatedUser(asUser);
        RunAsWork<Void> applyRatingsAsWork = new RunAsWork<Void>()
        {

            @Override
            public Void doWork() throws Exception
            {
                ratingService.applyRating(targetNode,
                                          rating,
                                          ratingSchemeName);
                return null;
            }

        };
        AuthenticationUtil.runAs(applyRatingsAsWork,
                                 asUser);
    }
    finally
    {
        AuthenticationUtil.setFullyAuthenticatedUser(fau);
    }
}
 
Example #28
Source File: FreemarkerRenderingEngine.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected Object buildModel(RenderingContext context)
{
    // The templateNode can be null.
    NodeRef companyHome = repository.getCompanyHome();
    NodeRef templateNode = getTemplateNode(context);
    Map<String, Serializable> paramMap = context.getCheckedParam(PARAM_MODEL, Map.class);
    TemplateImageResolver imgResolver = context.getCheckedParam(PARAM_IMAGE_RESOLVER, 
            TemplateImageResolver.class);
    
    // The fully authenticated user below is the username of the person who logged in and
    // who requested the execution of the current rendition. This will not be the
    // same person as the current user as renditions are executed by the system user.
    String fullyAuthenticatedUser = AuthenticationUtil.getFullyAuthenticatedUser();
    NodeRef person = serviceRegistry.getPersonService().getPerson(fullyAuthenticatedUser);
    
    NodeRef userHome = repository.getUserHome(person);
    Map<String, Object> model = getTemplateService().buildDefaultModel(person, companyHome, 
            userHome, templateNode, imgResolver);

    TemplateNode sourceTemplateNode = new TemplateNode(context.getSourceNode(), serviceRegistry, imgResolver);
    // TODO Add xml dom here.
    // model.put("xml", NodeModel.wrap(null));
    model.put(KEY_NODE, sourceTemplateNode);
    if (paramMap != null)
        model.putAll(paramMap);
    return model;
}
 
Example #29
Source File: AdminWebScriptTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    ctx = getServer().getApplicationContext();
    repoAdminService = (RepoAdminService) ctx.getBean("RepoAdminService");
    descriptorService = (DescriptorService) ctx.getBean("DescriptorService");
    admin = AuthenticationUtil.getAdminUserName();
    guest = AuthenticationUtil.getGuestUserName();

    AuthenticationUtil.setFullyAuthenticatedUser(admin);
}
 
Example #30
Source File: BatchImporterImpl.java    From alfresco-bulk-import with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.alfresco.extension.bulkimport.impl.BatchImporter#importBatch(String, NodeRef, Batch, boolean, boolean)
 */
@Override
public final void importBatch(final String  userId,
                              final NodeRef target,
                              final Batch   batch,
                              final boolean replaceExisting,
                              final boolean dryRun)
    throws InterruptedException,
           OutOfOrderBatchException
{
    long start = System.nanoTime();
    
    final String batchName = "Batch #" + batch.getNumber() + ", " + batch.size() + " items, " + batch.sizeInBytes() + " bytes.";
    if (debug(log)) debug(log, "Importing " + batchName);
    importStatus.setCurrentlyImporting(batchName);
    
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        @Override
        public Object doWork()
            throws Exception
        {
            importBatchInTxn(target, batch, replaceExisting, dryRun);
            return(null);
        }
    }, userId);
    
    if (debug(log))
    {
        long end = System.nanoTime();
        debug(log, "Batch #" + batch.getNumber() + " (containing " + batch.size() + " nodes) processed in " + getDurationInSeconds(end - start) + ".");
    }
}