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

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#getSystemUserName() . 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: ActivitiScriptBase.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 2
Source File: ADMRemoteStore.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Get the RunAs user need to execute a Write operation on the given path.
 * 
 * @param path  Document path
 * @return runas user - will be the Full Authenticated User or System as required
 */
protected String getPathRunAsUser(final String path)
{
    // check we actually are the user we are creating a user specific path for
    String runAsUser = AuthenticationUtil.getFullyAuthenticatedUser();
    String userId = null;
    Matcher matcher;
    if ((matcher = USER_PATTERN_1.matcher(path)).matches())
    {
        userId = matcher.group(1);
    }
    else if ((matcher = USER_PATTERN_2.matcher(path)).matches())
    {
        userId = matcher.group(1);
    }
    if (userId != null && userId.equals(runAsUser))
    {
        runAsUser = AuthenticationUtil.getSystemUserName();
    }
    return runAsUser;
}
 
Example 3
Source File: AuthenticatedAsyncJobHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
  public void execute(final JobEntity job, final String configuration, final ExecutionEntity execution,
              final CommandContext commandContext) 
  {
      // Get initiator
      String userName = AuthenticationUtil.runAsSystem(new RunAsWork<String>() {

	@Override
	public String doWork() throws Exception {
		ActivitiScriptNode ownerNode =  (ActivitiScriptNode) execution.getVariable(WorkflowConstants.PROP_INITIATOR);
		if(ownerNode != null && ownerNode.exists())
        {
          return (String) ownerNode.getProperties().get(ContentModel.PROP_USERNAME);            
        }
		return null;
	}
});
      
      
      // When no initiator is set, use system user to run job
      if (userName == null)
      {
          userName = AuthenticationUtil.getSystemUserName();
      }
      
      // Execute job
      AuthenticationUtil.runAs(new RunAsWork<Void>()
      {
          @SuppressWarnings("synthetic-access")
          public Void doWork() throws Exception
          {
              wrappedHandler.execute(job, configuration, execution, commandContext);
              return null;
          }
      }, userName);
  }
 
Example 4
Source File: RenditionEventProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get the executing user or the default, if none provided.
 */
private String getExecutingUserOrDefault(OnContentUpdatePolicyEvent event)
{
    if (event.getExecutingUser() != null && !event.getExecutingUser().isEmpty())
    {
        return event.getExecutingUser();
    }

    return AuthenticationUtil.getSystemUserName();
}
 
Example 5
Source File: LocalTestRunAsAuthenticatorFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Authenticator create(WebScriptServletRequest req, WebScriptServletResponse res)
{
    String runAsUser = AuthenticationUtil.getRunAsUser();
    if (runAsUser == null)
    {
        runAsUser = AuthenticationUtil.getSystemUserName();
    }
    return new LocalTestRunAsAuthenticator(runAsUser);
}
 
Example 6
Source File: NodeResourceHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public UserInfo getUserInfo(String userName)
{
    UserInfo userInfo = null;
    if (userName != null)
    {
        String sysUserName = AuthenticationUtil.getSystemUserName();
        if (userName.equals(sysUserName) || (AuthenticationUtil.isMtEnabled()
                    && userName.startsWith(sysUserName + "@")))
        {
            userInfo = new UserInfo(userName, userName, "");
        }
        else
        {
            PersonService.PersonInfo pInfo = null;
            try
            {
                NodeRef pNodeRef = personService.getPersonOrNull(userName);
                if (pNodeRef != null)
                {
                    pInfo = personService.getPerson(pNodeRef);
                }
            }
            catch (NoSuchPersonException | AccessDeniedException ex)
            {
                // ignore
            }

            if (pInfo != null)
            {
                userInfo = new UserInfo(userName, pInfo.getFirstName(), pInfo.getLastName());
            }
            else
            {
                if (LOGGER.isDebugEnabled())
                {
                    LOGGER.debug("Unknown person: " + userName);
                }
                userInfo = new UserInfo(userName, userName, "");
            }
        }
    }
    return userInfo;
}
 
Example 7
Source File: PersonServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public NodeRef createPerson(Map<QName, Serializable> properties, Set<String> zones)
{
    ParameterCheck.mandatory("properties", properties);
    String userName = DefaultTypeConverter.INSTANCE.convert(String.class, properties.get(ContentModel.PROP_USERNAME));
    if (userName == null)
    {
        throw new IllegalArgumentException("No username specified when creating the person.");
    }
    
    if (EqualsHelper.nullSafeEquals(userName, AuthenticationUtil.getSystemUserName()))
    {
        throw new AlfrescoRuntimeException("The built-in authority '" + AuthenticationUtil.getSystemUserName()  + "' is a user, but not a Person (i.e. it does not have a profile).");
    }

    AuthorityType authorityType = AuthorityType.getAuthorityType(userName);
    if (authorityType != AuthorityType.USER)
    {
        throw new AlfrescoRuntimeException("Attempt to create person for an authority which is not a user");
    }

    tenantService.checkDomainUser(userName);

    if (personExists(userName))
    {
        throw new AlfrescoRuntimeException("Person '" + userName + "' already exists.");
    }
    
    properties.put(ContentModel.PROP_USERNAME, userName);
    properties.put(ContentModel.PROP_SIZE_CURRENT, 0L);
    
    NodeRef personRef = null;
    try
    {
        beforeCreateNodeValidationBehaviour.disable();
        
        personRef = nodeService.createNode(
                getPeopleContainer(),
                ContentModel.ASSOC_CHILDREN,
                getChildNameLower(userName), // Lowercase:
                ContentModel.TYPE_PERSON, properties).getChildRef();         
    }
    finally
    {
        beforeCreateNodeValidationBehaviour.enable();
    }
    
    checkIfPersonShouldBeDisabledAndSetAspect(personRef, properties);
    
    if (zones != null)
    {
        for (String zone : zones)
        {
            // Add the person to an authentication zone (corresponding to an external user registry)
            // Let's preserve case on this child association
            nodeService.addChild(authorityService.getOrCreateZone(zone), personRef, ContentModel.ASSOC_IN_ZONE, QName.createQName(NamespaceService.CONTENT_MODEL_PREFIX, userName, namespacePrefixResolver));
        }
    }
    
    removeFromCache(userName, false);
    
    publishEvent("user.create", this.nodeService.getProperties(personRef));
    
    return personRef;
}
 
Example 8
Source File: AuthenticatedTimerJobHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void execute(final JobEntity job, final String configuration, final ExecutionEntity execution,
            final CommandContext commandContext) 
{
    String userName = null;
    String tenantToRunIn = (String) execution.getVariable(ActivitiConstants.VAR_TENANT_DOMAIN);
    if(tenantToRunIn != null && tenantToRunIn.trim().length() == 0)
    {
        tenantToRunIn = null;
    }
    
    final ActivitiScriptNode initiatorNode = (ActivitiScriptNode) execution.getVariable(WorkflowConstants.PROP_INITIATOR);
    
    // Extracting the properties from the initiatornode should be done in correct tennant or as administrator, since we don't 
    // know who started the workflow yet (We can't access node-properties when no valid authentication context is set up).
    if(tenantToRunIn != null)
    {
        userName = TenantUtil.runAsTenant(new TenantRunAsWork<String>()
        {
            @Override
            public String doWork() throws Exception
            {
                return getInitiator(initiatorNode);
            }
        }, tenantToRunIn);
    }
    else
    {
        // No tenant on worklfow, run as admin in default tenant
        userName = AuthenticationUtil.runAs(new RunAsWork<String>()
        {
            @SuppressWarnings("synthetic-access")
            public String doWork() throws Exception
            {
                return getInitiator(initiatorNode);
            }
        }, AuthenticationUtil.getSystemUserName());
    }
    
    // Fall back to task assignee, if no initiator is found
    if(userName == null)
    {
        PvmActivity targetActivity = execution.getActivity();
        if (targetActivity != null)
        {
            // Only try getting active task, if execution timer is waiting on is a userTask
            String activityType = (String) targetActivity.getProperty(ActivitiConstants.NODE_TYPE);
            if (ActivitiConstants.USER_TASK_NODE_TYPE.equals(activityType))
            {
                Task task = new TaskQueryImpl(commandContext)
                .executionId(execution.getId())
                .executeSingleResult(commandContext);
                
                if (task != null && task.getAssignee() != null)
                {
                    userName = task.getAssignee();
                }
            }
        }
    }
    
    // When no task assignee is set, nor the initiator, use system user to run job
    if (userName == null)
    {
        userName = AuthenticationUtil.getSystemUserName();
        tenantToRunIn = null;
    }
    
    if(tenantToRunIn != null)
    {
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
        {
            @Override
            public Void doWork() throws Exception
            {
                wrappedHandler.execute(job, configuration, execution, commandContext);
                return null;
            }
        }, userName, tenantToRunIn);
    }
    else
    {
        // Execute the timer without tenant
        AuthenticationUtil.runAs(new RunAsWork<Void>()
        {
            @SuppressWarnings("synthetic-access")
            public Void doWork() throws Exception
            {
                wrappedHandler.execute(job, configuration, execution, commandContext);
                return null;
            }
        }, userName);
    }
}
 
Example 9
Source File: Node.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static UserInfo lookupUserInfo(String userName, Map<String, UserInfo> mapUserInfo, PersonService personService, boolean displayNameOnly)
{
    UserInfo userInfo = mapUserInfo.get(userName);
    if ((userInfo == null) && (userName != null))
    {
        String sysUserName = AuthenticationUtil.getSystemUserName();
        if (userName.equals(sysUserName) || (AuthenticationUtil.isMtEnabled() && userName.startsWith(sysUserName + "@")))
        {
            userInfo = new UserInfo((displayNameOnly ? null : userName), userName, "");
        }
        else
        {
            PersonService.PersonInfo pInfo = null;
            try
            {
                NodeRef pNodeRef = personService.getPersonOrNull(userName);
                if (pNodeRef != null)
                {
                    pInfo = personService.getPerson(pNodeRef);
                }
            }
            catch (NoSuchPersonException nspe)
            {
                // drop-through
            }
            catch (AccessDeniedException ade)
            {
                // SFS-610
                // drop-through
            }

            if (pInfo != null)
            {
                userInfo = new UserInfo((displayNameOnly ? null : userName), pInfo.getFirstName(), pInfo.getLastName());
            }
            else
            {
                logger.warn("Unknown person: "+userName);
                userInfo = new UserInfo((displayNameOnly ? null : userName), userName, "");
            }
        }

        mapUserInfo.put(userName, userInfo);
    }
    return userInfo;
}