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

The following are Jave code examples for showing how to use getFullyAuthenticatedUser() 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.
Example 1
Project: alfresco-repository   File: AlfrescoScriptVirtualContext.java   Source Code and License Vote up 6 votes
private Map<String, String> createPlaceHolders()
{
    Map<String, String> newPlaceholders = new HashMap<>();
    String user = AuthenticationUtil.getFullyAuthenticatedUser();

    newPlaceholders.put(CURRENT_USER_PH,
                        user);

    String[] paths = createQNamePaths();

    // the actual path will contain the ISO9075 encoded qname path
    // this was reverted from a dual placeholder implementation (see CM-523)
    newPlaceholders.put(ACTUAL_PATH_PH,
                        paths[1]);

    // newPlaceholders.put(ACTUAL_ISO9075_PATH_PH,
    // paths[1]);

    return newPlaceholders;
}
 
Example 2
Project: alfresco-repository   File: ActivitiScriptBase.java   Source Code and License Vote up 6 votes
protected Object executeScript(String theScript, Map<String, Object> model, String scriptProcessorName, String runAsUser)
{
    String user = AuthenticationUtil.getFullyAuthenticatedUser();
    
    Object scriptResult = null;
    if (runAsUser == null && user != null)
    {
        // Just execute the script using the current user
        scriptResult = executeScript(theScript, model, scriptProcessorName);
    }
    else 
    {
        if (runAsUser != null)
        {
            // Check if the user used for running exists
            validateRunAsUser(runAsUser);
        }
        else
        {
            // No current user is authenticated, use the system-user to execute the script
            runAsUser = AuthenticationUtil.getSystemUserName();
        }
        executeScriptAsUser(theScript, model, scriptProcessorName, runAsUser);
    }
    return scriptResult;
}
 
Example 3
Project: alfresco-repository   File: AuthenticatedPersonDataGenerator.java   Source Code and License Vote up 6 votes
/**
 * @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 4
Project: alfresco-repository   File: CMISConnector.java   Source Code and License Vote up 5 votes
/**
 * Sets the given ACL.
 */
public void applyACL(NodeRef nodeRef, TypeDefinitionWrapper type, Acl aces)
{
    boolean hasAces = (aces != null) && (aces.getAces() != null) && !aces.getAces().isEmpty();

    if (!hasAces && !permissionService.getInheritParentPermissions(nodeRef))
    {
        return;
    }

    if (!type.getTypeDefinition(false).isControllableAcl())
    {
        throw new CmisConstraintException("Object is not ACL controllable!");
    }

    // remove all permissions
    permissionService.deletePermissions(nodeRef);

    // set new permissions
    for (Ace ace : aces.getAces())
    {
        String principalId = ace.getPrincipalId();
        if (CMIS_USER.equals(principalId))
        {
            principalId = AuthenticationUtil.getFullyAuthenticatedUser();
        }

        List<String> permissions = translatePermissionsFromCMIS(ace.getPermissions());
        for (String permission : permissions)
        {
            permissionService.setPermission(nodeRef, principalId, permission, true);
        }
    }
}
 
Example 5
Project: alfresco-repository   File: SiteServiceImpl.java   Source Code and License Vote up 5 votes
/**
 * @see org.alfresco.service.cmr.site.SiteService#canAddMember(java.lang.String,
 *      java.lang.String, java.lang.String)
 */
public boolean canAddMember(final String shortName, final String authorityName, final String role)
{
    final NodeRef siteNodeRef = getSiteNodeRef(shortName);
    if (siteNodeRef == null)
    {
        throw new SiteDoesNotExistException(shortName);
    }

    // Get the user's current role
    final String currentRole = getMembersRole(shortName, authorityName);

    // Get the visibility of the site
    SiteVisibility visibility = getSiteVisibility(siteNodeRef);

    // If we are ...
    // -- the current user has change permissions rights on the site
    // or we are ...
    // -- referring to a public site and
    // -- the role being set is consumer and
    // -- the user being added is ourselves and
    // -- the member does not already have permissions
    // ... then we can set the permissions as system user
    final String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
    return ((permissionService.hasPermission(siteNodeRef, PermissionService.CHANGE_PERMISSIONS) == AccessStatus.ALLOWED)
                || isSiteAdmin(currentUserName) || (SiteVisibility.PUBLIC.equals(visibility)
                && role.equals(SiteModel.SITE_CONSUMER) && authorityName.equals(currentUserName) && currentRole == null));
}
 
Example 6
Project: alfresco-repository   File: VirtualRatingServiceExtensionTest.java   Source Code and License Vote up 5 votes
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 7
Project: alfresco-remote-api   File: SiteAdminSitesGet.java   Source Code and License Vote up 5 votes
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
{
    String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
    // check the current user access rights
    if (!siteService.isSiteAdmin(currentUser))
    {
        // Note: security, no message to indicate why
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Resource not found.");
    }

    // Create paging
    final ScriptPagingDetails paging = new ScriptPagingDetails(getIntParameter(req, MAX_ITEMS,
                DEFAULT_MAX_ITEMS_PER_PAGE), getIntParameter(req, SKIP_COUNT, 0));

    // request a total count of found items
    paging.setRequestTotalCountMax(Integer.MAX_VALUE);

    final List<FilterProp> filterProp = getFilterProperties(req.getParameter(NAME_FILTER));

    final List<Pair<QName, Boolean>> sortProps = new ArrayList<Pair<QName, Boolean>>();
    sortProps.add(new Pair<QName, Boolean>(ContentModel.PROP_NAME, true));

    PagingResults<SiteInfo> pagingResults = AuthenticationUtil.runAs(
                new AuthenticationUtil.RunAsWork<PagingResults<SiteInfo>>()
                {
                    public PagingResults<SiteInfo> doWork() throws Exception
                    {
                        return siteService.listSites(filterProp, sortProps, paging);
                    }
                }, AuthenticationUtil.getAdminUserName());

    List<SiteInfo> result = pagingResults.getPage();
    List<SiteState> sites = new ArrayList<SiteState>(result.size());
    for (SiteInfo info : result)
    {
        sites.add(SiteState.create(info,
                    siteService.listMembers(info.getShortName(), null, SiteModel.SITE_MANAGER, 0), currentUser,
                    nodeService, personService));
    }

    Map<String, Object> sitesData = new HashMap<String, Object>(6);

    // Site data
    sitesData.put("items", sites);
    // Paging data
    sitesData.put("count", result.size());
    sitesData.put("hasMoreItems", pagingResults.hasMoreItems());
    sitesData.put("totalItems", (pagingResults.getTotalResultCount() == null ? -1 : pagingResults.getTotalResultCount().getFirst()));
    sitesData.put("skipCount", paging.getSkipCount());
    sitesData.put("maxItems", paging.getMaxItems());
    
    // Create the model from the site and pagination data
    Map<String, Object> model = new HashMap<String, Object>(1);
    model.put("data", sitesData);

    return model;
}
 
Example 8
Project: alfresco-remote-api   File: PeopleImpl.java   Source Code and License Vote up 5 votes
private boolean checkCurrentUserOrAdmin(String personId)
{
    boolean isAdmin = isAdminAuthority();

    String currentUserId = AuthenticationUtil.getFullyAuthenticatedUser();
    if (!isAdmin && !currentUserId.equalsIgnoreCase(personId))
    {
        throw new PermissionDeniedException();
    }

    return isAdmin;
}
 
Example 9
Project: alfresco-repository   File: NodeArchiveServiceImpl.java   Source Code and License Vote up 5 votes
/**
 * Uses batch processing and job locking to purge all archived nodes
 */
public void purgeAllArchivedNodes(StoreRef originalStoreRef)
{
    final String user = AuthenticationUtil.getFullyAuthenticatedUser();
    if (user == null)
    {
        throw new IllegalStateException("Cannot purge as there is no authenticated user.");
    }
    
    /**
     * Worker that purges each node
     */
    BatchProcessWorker<NodeRef> worker = new BatchProcessor.BatchProcessWorkerAdaptor<NodeRef>()
    {
        @Override
        public void beforeProcess() throws Throwable
        {
            AuthenticationUtil.pushAuthentication();
        }
        public void process(NodeRef nodeRef) throws Throwable
        {
            AuthenticationUtil.setFullyAuthenticatedUser(user);
            if (nodeService.exists(nodeRef))
            {
                invokeBeforePurgeNode(nodeRef);
                nodeService.deleteNode(nodeRef);
            }
        }
        @Override
        public void afterProcess() throws Throwable
        {
            AuthenticationUtil.popAuthentication();
        }
    };
    doBulkOperation(user, originalStoreRef, worker);
}
 
Example 10
Project: alfresco-repository   File: RatingServiceImpl.java   Source Code and License Vote up 5 votes
/**
 * This method checks if the current fully authenticated user is the cm:creator of the specified node.
 */
private boolean isCurrentUserNodeCreator(NodeRef targetNode)
{
    final String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
    Serializable creator = nodeService.getProperty(targetNode, ContentModel.PROP_CREATOR);
    return currentUser.equals(creator);
}
 
Example 11
Project: alfresco-remote-api   File: BlogPostsMyDraftsGet.java   Source Code and License Vote up 5 votes
@Override
protected PagingResults<BlogPostInfo> getBlogResultsImpl(SiteInfo site, NodeRef node, Date fromDate, Date toDate, PagingRequest pagingReq)
{
    String user = AuthenticationUtil.getFullyAuthenticatedUser();
    if(site != null)
    {
       return blogService.getDrafts(site.getShortName(), user, pagingReq);
    }
    else
    {
       return blogService.getDrafts(node, user, pagingReq);
    }
}
 
Example 12
Project: alfresco-repository   File: RatingServiceImpl.java   Source Code and License Vote up 5 votes
@Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class)
public Rating removeRatingByCurrentUser(NodeRef targetNode,
        String ratingScheme)
{
    String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
    return removeRating(targetNode, ratingScheme, currentUser);
}
 
Example 13
Project: alfresco-repository   File: ActivitiWorkflowEngine.java   Source Code and License Vote up 5 votes
private WorkflowTask endNormalTask(String taskId, String localTaskId, String transition)
{
    // Retrieve task
    Task task = taskService.createTaskQuery().taskId(localTaskId).singleResult();
    
    if(task == null)
    {
        String msg = messageService.getMessage(ERR_END_UNEXISTING_TASK, taskId);
        throw new WorkflowException(msg);
    }
    
    // Check if the assignee is equal to the current logged-in user. If not, assign task before ending
    String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
    if(task.getAssignee() == null || !task.getAssignee().equals(currentUserName)) {
        taskService.setAssignee(localTaskId, currentUserName);
        // Also update pojo used to set the outcome, this will read assignee as wel
        task.setAssignee(currentUserName);
        
        // Re-fetch the task-entity since it's revision has been updated by the setAssignee() call
        task = taskService.createTaskQuery().taskId(localTaskId).singleResult();
    }
    
    setOutcome(task, transition);
    taskService.complete(localTaskId);
    // The task should have a historicTaskInstance
    HistoricTaskInstance historicTask = historyService.createHistoricTaskInstanceQuery().taskId(task.getId()).singleResult();
    return typeConverter.convert(historicTask);
}
 
Example 14
Project: alfresco-repository   File: FreemarkerRenderingEngine.java   Source Code and License Vote up 5 votes
@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 15
Project: alfresco-repository   File: BlogServiceImpl.java   Source Code and License Vote up 5 votes
/**
 * @deprecated
 */
@Override
public PagingResults<BlogPostInfo> getMyDraftsAndAllPublished(NodeRef blogContainerNode, Date createdFrom, Date createdTo, PagingRequest pagingReq)
{
    ParameterCheck.mandatory("blogContainerNode", blogContainerNode);
    ParameterCheck.mandatory("pagingReq", pagingReq);
    
    // get canned query
    String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
    DraftsAndPublishedBlogPostsCannedQuery cq = (DraftsAndPublishedBlogPostsCannedQuery)draftsAndPublishedBlogPostsCannedQueryFactory.getCannedQuery(blogContainerNode, createdFrom, createdTo, currentUser, pagingReq);
        
    // execute canned query
    CannedQueryResults<BlogEntity> results = cq.execute();
    return wrap(results, blogContainerNode);
}
 
Example 16
Project: alfresco-repository   File: RatingServiceImpl.java   Source Code and License Vote up 4 votes
@Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class)
public Rating getRatingByCurrentUser(NodeRef targetNode, String ratingSchemeName)
{
    String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
    return this.getRating(targetNode, ratingSchemeName, currentUser);
}
 
Example 17
Project: alfresco-remote-api   File: QuickShareLinksImpl.java   Source Code and License Vote up 4 votes
public CollectionWithPagingInfo<QuickShareLink> findLinks(Parameters parameters)
{
    checkEnabled();

    String queryString =
            "ASPECT:\"" + QuickShareModel.ASPECT_QSHARE.toString() + "\"";

    SearchParameters sp = new SearchParameters();

    // note: REST API query parameter (ie. where clause filter) - not to be confused with search query ;-)
    Query q = parameters.getQuery();
    if (q != null)
    {
        // filtering via "where" clause
        MapBasedQueryWalker propertyWalker = new MapBasedQueryWalker(FIND_SHARED_LINKS_QUERY_PROPERTIES, null);
        QueryHelper.walk(q, propertyWalker);

        String sharedByUserId = propertyWalker.getProperty(PARAM_SHAREDBY, WhereClauseParser.EQUALS, String.class);

        if (sharedByUserId != null)
        {
            if (People.DEFAULT_USER.equalsIgnoreCase(sharedByUserId))
            {
                sharedByUserId =  AuthenticationUtil.getFullyAuthenticatedUser();
            }

            QueryParameterDefinition qpd = new QueryParameterDefImpl(QuickShareModel.PROP_QSHARE_SHAREDBY, dictionaryService.getDataType(DataTypeDefinition.TEXT),
                    true, sharedByUserId);
            sp.addQueryParameterDefinition(qpd);

            String qsharedBy = QuickShareModel.PROP_QSHARE_SHAREDBY.toPrefixString(namespaceService);
            queryString += " [email protected]"+SearchLanguageConversion.escapeLuceneQuery(qsharedBy)+":\"${"+qsharedBy+"}\"";
        }
    }

    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery(queryString);
    sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);

    Paging paging = parameters.getPaging();
    PagingRequest pagingRequest = Util.getPagingRequest(paging);

    sp.setSkipCount(pagingRequest.getSkipCount());
    sp.setMaxItems(pagingRequest.getMaxItems());

    sp.addSort("@" + ContentModel.PROP_MODIFIED, false);

    ResultSet results = searchService.query(sp);

    List<QuickShareLink> qsLinks = new ArrayList<>(results.length());

    List<String> includeParam = parameters.getInclude();

    for (ResultSetRow row : results)
    {
        NodeRef nodeRef = row.getNodeRef();
        qsLinks.add(getQuickShareInfo(nodeRef, false, includeParam));
    }

    results.close();

    return CollectionWithPagingInfo.asPaged(paging, qsLinks, results.hasMore(), new Long(results.getNumberFound()).intValue());
}
 
Example 18
Project: alfresco-repository   File: AuthenticatedUserDataGenerator.java   Source Code and License Vote up 4 votes
/**
 * @return              Returns the currently-authenticated user
 */
public Serializable getData() throws Throwable
{
    return AuthenticationUtil.getFullyAuthenticatedUser();
}
 
Example 19
Project: alfresco-repository   File: ImapServiceImpl.java   Source Code and License Vote up 4 votes
private String getCurrentUser()
{
    return AuthenticationUtil.getFullyAuthenticatedUser();
}
 
Example 20
Project: alfresco-remote-api   File: SitesImpl.java   Source Code and License Vote up 4 votes
/**
 * Create default/fixed preset (Share) site - with DocLib container/component
 *
 * @param site
 * @return
 */
public Site createSite(Site site, Parameters parameters)
{
    // note: if site id is null then will be generated from the site title
    site = validateSite(site);

    SiteInfo siteInfo = null;
    try
    {
        siteInfo = createSite(site);
    }
    catch (SiteServiceException sse)
    {
        if (sse.getMsgId().equals("site_service.unable_to_create"))
        {
            throw new ConstraintViolatedException(sse.getMessage());
        }
        else
        {
            throw sse;
        }
    }

    String siteId = siteInfo.getShortName();
    NodeRef siteNodeRef = siteInfo.getNodeRef();

    // default false (if not provided)
    boolean skipShareSurfConfig = Boolean.valueOf(parameters.getParameter(PARAM_SKIP_SURF_CONFIGURATION));
    if (skipShareSurfConfig == false)
    {
        // import default/fixed preset Share surf config
        importSite(siteId, siteNodeRef);
    }

    // pre-create doclib
    siteService.createContainer(siteId, SiteService.DOCUMENT_LIBRARY, ContentModel.TYPE_FOLDER, null);

    // default false (if not provided)
    boolean skipAddToFavorites = Boolean.valueOf(parameters.getParameter(PARAM_SKIP_ADDTOFAVORITES));
    if (skipAddToFavorites == false)
    {
        String personId = AuthenticationUtil.getFullyAuthenticatedUser();
        favouritesService.addFavourite(personId, siteNodeRef); // ignore result
    }

    return getSite(siteInfo, true);
}