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

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#getRunAsUser() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * 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 2
@Override
protected Object determineCurrentLookupKey() 
{
    //return tenantService.getCurrentUserDomain(); // note: this is re-entrant if it checks whether tenant is enabled !
    String runAsUser = AuthenticationUtil.getRunAsUser();
    String tenantDomain = TenantService.DEFAULT_DOMAIN;
    if (runAsUser != null)
    {
        String[] parts = runAsUser.split(TenantService.SEPARATOR);
        if (parts.length == 2)
        {
            tenantDomain = parts[1];
        }
    }
    return tenantDomain;
}
 
Example 3
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 4
/**
 * {@inheritDoc}
 */
public boolean hasAdminAuthority()
{
    String currentUserName = AuthenticationUtil.getRunAsUser();
    
    // Determine whether the administrator role is mapped to this user or one of their groups
    return ((currentUserName != null) && getAuthoritiesForUser(currentUserName).contains(PermissionService.ADMINISTRATOR_AUTHORITY));
}
 
Example 5
/**
 * {@inheritDoc}
 */
public boolean hasGuestAuthority()
{
    String currentUserName = AuthenticationUtil.getRunAsUser();
    
    // Determine whether the guest role is mapped to this user or one of their groups
    return ((currentUserName != null) && getAuthoritiesForUser(currentUserName).contains(PermissionService.GUEST_AUTHORITY));
}
 
Example 6
/**
 * {@inheritDoc}
 */
// note: could be renamed (via deprecation) to getAuthoritiesForUser()
public Set<String> getAuthorities()
{
    String currentUserName = AuthenticationUtil.getRunAsUser();
    return getAuthoritiesForUser(currentUserName);
}
 
Example 7
private String getAuthInRun(String userName)
{
    RunAsWork<String> getWork = new RunAsWork<String>()
    {
        @Override
        public String doWork() throws Exception
        {
            return AuthenticationUtil.getRunAsUser();
        }
    };
    return AuthenticationUtil.runAs(getWork, userName);
}
 
Example 8
private String getCurrentUser()
{
    String userId = AuthenticationUtil.getRunAsUser();
    if ((userId != null) && (! userId.equals(AuthenticationUtil.SYSTEM_USER_NAME)) && (! userNamesAreCaseSensitive))
    {
        // user names are not case-sensitive
        userId = userId.toLowerCase();
    }
    
    return userId;
}
 
Example 9
@Override
public void onContentRead(NodeRef nodeRef)
{
    appendSubAction(new NodeChange(nodeInfoFactory, namespaceService, nodeRef).
            setAction(READ_CONTENT));
    // MNT-8810 fix, remember runAsUser for read operation
    runAsUser = AuthenticationUtil.getRunAsUser();
}
 
Example 10
/**
 * Checks if the current user is allowed to get subscription data.
 */
protected void checkRead(String userId, boolean checkPrivate)
{
    if (userId == null)
    {
        throw new IllegalArgumentException("User Id may not be null!");
    }

    if (!checkPrivate)
    {
        return;
    }

    String currentUser = AuthenticationUtil.getRunAsUser();
    if (currentUser == null)
    {
        throw new IllegalArgumentException("No current user!");
    }

    if (currentUser.equalsIgnoreCase(userId) || authorityService.isAdminAuthority(currentUser)
            || AuthenticationUtil.isRunAsUserTheSystemUser() || !isSubscriptionListPrivate(userId))
    {
        return;
    }

    throw new PrivateSubscriptionListException("subscription_service.err.private-list");
}
 
Example 11
@Override
public boolean canVirtualize(NodeRef nodeRef) throws VirtualizationException
{
    String runAsUser = AuthenticationUtil.getRunAsUser();
    if (runAsUser == null)
    {
        if (logger.isTraceEnabled())
        {

            RuntimeException stackTracingException = new RuntimeException("Stack trace.");
            logger.trace("Virtualization check call in unauthenticated-context - stack trace follows:",
                         stackTracingException);
        }

        return false;
    }

    Reference reference = Reference.fromNodeRef(nodeRef);
    if (reference != null)
    {
        return true;
    }
    else
    {
        for (VirtualizationMethod vMethod : virtualizationMethods)
        {
            if (vMethod.canVirtualize(environment,
                                      nodeRef))
            {
                return true;
            }
        }

        return false;
    }
}
 
Example 12
@Override
public Authenticator create(WebScriptServletRequest req, WebScriptServletResponse res)
{
    String runAsUser = AuthenticationUtil.getRunAsUser();
    if (runAsUser == null)
    {
        runAsUser = AuthenticationUtil.getSystemUserName();
    }
    return new LocalTestRunAsAuthenticator(runAsUser);
}
 
Example 13
/**
 * @see org.alfresco.extension.bulkimport.BulkImporter#start(org.alfresco.extension.bulkimport.source.BulkImportSource, java.util.Map, org.alfresco.service.cmr.repository.NodeRef)
 */
@Override
public void start(final BulkImportSource          source,
                  final Map<String, List<String>> parameters,
                  final NodeRef                   target)
{
    // PRECONDITIONS
    if (source == null)
    {
        throw new IllegalArgumentException("Bulk import source bean must not be null.");
    }
    
    if (parameters == null)
    {
        throw new IllegalArgumentException("Bulk import parameters must not be null.");
    }
    
    if (target == null)
    {
        throw new IllegalArgumentException("Bulk import target nodeRef must not be null.");
    }
    
    if (!nodeService.exists(target))
    {
        throw new IllegalArgumentException("Bulk import target nodeRef " + String.valueOf(target) + " does not exist.");
    }
    
    if (!AccessStatus.ALLOWED.equals(permissionService.hasPermission(target, PermissionService.ADD_CHILDREN)))
    {
        throw new IllegalArgumentException("User " + authenticationService.getCurrentUserName() +
                                           " does not have permission to add children to target nodeRef " + String.valueOf(target) + ".");
    }

    if (!dictionaryService.isSubClass(nodeService.getType(target), ContentModel.TYPE_FOLDER))
    {
        throw new IllegalArgumentException("Target '" + String.valueOf(target) + "' is not a space.");
    }
    
    if (importStatus.inProgress())
    {
        throw new IllegalStateException("An import is already in progress.");
    }
        
    // Body
    if (debug(log)) debug(log, source.getName() + " bulk import started with parameters " + Arrays.toString(parameters.entrySet().toArray()) + ".");

    // Create the threads used by the bulk import tool
    scannerThread = new Thread(new Scanner(serviceRegistry,
                                           AuthenticationUtil.getRunAsUser(),
                                           batchWeight,
                                           importStatus,
                                           pauser,
                                           source,
                                           parameters,
                                           target,
                                           createThreadPool(),
                                           batchImporter,
                                           completionHandlers));
    
    scannerThread.setName(SCANNER_THREAD_NAME);
    scannerThread.setDaemon(true);
    scannerThread.start();
}
 
Example 14
/**
 * Optimised read permission evaluation
 * caveats:
 * doesn't take into account dynamic authorities/groups
 * doesn't take into account node types/aspects for permissions
 *  
 */
@Override
@Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class)
public AccessStatus hasReadPermission(NodeRef nodeRef)
{
    AccessStatus status = AccessStatus.DENIED;

    // If the node ref is null there is no sensible test to do - and there
    // must be no permissions
    // - so we allow it
    if (nodeRef == null)
    {
        return AccessStatus.ALLOWED;
    }

    // Allow permissions for nodes that do not exist
    if (!nodeService.exists(nodeRef))
    {
        return AccessStatus.ALLOWED;
    }

    String runAsUser = AuthenticationUtil.getRunAsUser();
    if (runAsUser == null)
    {
        return AccessStatus.DENIED;
    }

    if (AuthenticationUtil.isRunAsUserTheSystemUser())
    {
        return AccessStatus.ALLOWED;
    }

    // any dynamic authorities other than those defined in the default permissions model with full
    // control or read permission force hasPermission check
    Boolean forceHasPermission = (Boolean)AlfrescoTransactionSupport.getResource("forceHasPermission");
    if(forceHasPermission == null)
    {
        for(DynamicAuthority dynamicAuthority : dynamicAuthorities)
        {
            String authority = dynamicAuthority.getAuthority();
            Set<PermissionReference> requiredFor = dynamicAuthority.requiredFor();
            if(authority != PermissionService.OWNER_AUTHORITY &&
                    authority != PermissionService.ADMINISTRATOR_AUTHORITY &&
                    authority != PermissionService.LOCK_OWNER_AUTHORITY &&
                    (requiredFor == null ||
                            requiredFor.contains(modelDAO.getPermissionReference(null, PermissionService.FULL_CONTROL)) ||
                            requiredFor.contains(modelDAO.getPermissionReference(null, PermissionService.READ))))
            {
                forceHasPermission = Boolean.TRUE;
                break;
            }
        }
        AlfrescoTransactionSupport.bindResource("forceHasPermission", forceHasPermission);            
    }

    if(forceHasPermission == Boolean.TRUE)
    {
        return hasPermission(nodeRef, PermissionService.READ);
    }

    Long aclID = nodeService.getNodeAclId(nodeRef);
    if(aclID == null)
    {
        // ACLID is null - need to call default permissions evaluation
        // This will end up calling the old-style ACL code that walks up the ACL tree
        status = hasPermission(nodeRef, getPermissionReference(null, PermissionService.READ));
    }
    else
    {
        status = (canRead(aclID) == AccessStatus.ALLOWED ||
                adminRead() == AccessStatus.ALLOWED ||
                ownerRead(runAsUser, nodeRef) == AccessStatus.ALLOWED) ? AccessStatus.ALLOWED : AccessStatus.DENIED;
    }

    return status;
}
 
Example 15
/**
 * Creates a "signature" object and associates it with the signed doc
 * @param node
 * @param location
 * @param reason
 */
protected NodeRef addSignatureNodeAssociation(NodeRef node, String location, String reason, 
		String signatureField, java.util.Date sigDate, String geolocation, int page, String position)
{
	NodeService nodeService = serviceRegistry.getNodeService();
	
	String userId = AuthenticationUtil.getRunAsUser();
	NodeRef person = serviceRegistry.getPersonService().getPerson(userId);
	
	// if page is -1, then this was a signature field, set position to "none"
	if(page == -1) position = "none";
	
	HashMap<QName, Serializable> props = new HashMap<QName, Serializable>();
	props.put(CounterSignSignatureModel.PROP_REASON, reason);
	props.put(CounterSignSignatureModel.PROP_LOCATION, location);
	props.put(CounterSignSignatureModel.PROP_SIGNATUREDATE, sigDate);
	props.put(CounterSignSignatureModel.PROP_SIGNATUREFIELD, signatureField);
	props.put(CounterSignSignatureModel.PROP_SIGNATUREPAGE, page);
	props.put(CounterSignSignatureModel.PROP_SIGNATUREPOSITION, position);
	props.put(CounterSignSignatureModel.PROP_EXTERNALSIGNER, userId);
	
	// check the geolocation data, if it is valid, split it out and add
	if(geolocation.indexOf(",") != -1)
	{
		String[] latLong = geolocation.split(",");
		props.put(ContentModel.PROP_LATITUDE, latLong[0]);
		props.put(ContentModel.PROP_LONGITUDE, latLong[1]);
	}
	else
	{
		props.put(ContentModel.PROP_LATITUDE, -1);
		props.put(ContentModel.PROP_LONGITUDE, -1);
	}
	
	QName assocQName = QName.createQName(
			CounterSignSignatureModel.COUNTERSIGN_SIGNATURE_MODEL_1_0_URI,
			QName.createValidLocalName(userId + "-" + sigDate.getTime()));
		
	ChildAssociationRef sigChildRef = nodeService.createNode(
			node, 
			CounterSignSignatureModel.ASSOC_SIGNATURES, 
			assocQName, 
			CounterSignSignatureModel.TYPE_SIGNATURE, 
			props);
	
	NodeRef signature = sigChildRef.getChildRef();
	
	// add hidden aspect to signature nodes, these should not be 
	// shown in any document lists or other Share views
	HashMap<QName, Serializable> aspectProps = new HashMap<QName, Serializable>();
	aspectProps.put(ContentModel.PROP_VISIBILITY_MASK, HiddenAspect.Visibility.NotVisible.getMask());
	nodeService.addAspect(signature, ContentModel.ASPECT_HIDDEN, aspectProps);

	nodeService.createAssociation(signature, person, CounterSignSignatureModel.ASSOC_SIGNEDBY);
	
	return signature;
}
 
Example 16
/**
 * List the open invitations.
 * props specifies optional properties to constrain the search.
 * 
 * By default, if no "resultsLimit" property is specified in the props argument,
 * this method will return a maximum of DEFAULT_MAX_LIST_INVITATIONS_RETURN_SIZE (200) results
 * 
 * @param props inviteeUserName
 * @param props resourceName
 * @param props resourceType
 * @param props invitationType
 *
 * @return the invitations
 */

public ScriptInvitation<?>[] listInvitations(Scriptable props)
{
    InvitationSearchCriteriaImpl crit = new InvitationSearchCriteriaImpl();
    
    int resultsLimit = DEFAULT_MAX_LIST_INVITATIONS_RETURN_SIZE;
    
    if (props.has("resourceName", props))
    {
        crit.setResourceName((String)props.get("resourceName", props));
    }
    if (props.has("resourceType", props))
    {
        crit.setResourceType(ResourceType.valueOf((String)props.get("resourceType", props)));
    }
    if (props.has("inviteeUserName", props))
    {
        crit.setInvitee((String)props.get("inviteeUserName", props));
    }
    if (props.has("invitationType", props))
    {
        String invitationType = (String)props.get("invitationType", props);
        crit.setInvitationType(InvitationType.valueOf(invitationType));
    }
    if (props.has("resultsLimit", props))
    {
        String resultsLimitStr = (String) props.get("resultsLimit", props);
        try
        {
            if (resultsLimitStr != null && !resultsLimitStr.isEmpty())
            {
                resultsLimit = Integer.parseInt(resultsLimitStr);
            }
        }
        catch (Exception e)
        {
            // ignore any parse exceptions; no need to log them
        }
    }

    //MNT-9905 Pending Invites created by one site manager aren't visible to other site managers
    String currentUser = AuthenticationUtil.getRunAsUser();
    String siteShortName = crit.getResourceName();
    List<Invitation> invitations;

    if (siteShortName != null && (SiteModel.SITE_MANAGER).equals(siteService.getMembersRole(siteShortName, currentUser)))
    {
        final InvitationSearchCriteriaImpl criteria = crit;
        final int resultsLimitFinal = resultsLimit;
        RunAsWork<List<Invitation>> runAsSystem = new RunAsWork<List<Invitation>>()
        {
            public List<Invitation> doWork() throws Exception
            {
                return invitationService.searchInvitation(criteria, resultsLimitFinal);
            }
        };

        invitations = AuthenticationUtil.runAs(runAsSystem, AuthenticationUtil.getSystemUserName());
    }
    else
    {
        invitations = invitationService.searchInvitation(crit, resultsLimit);
    }
    
    ScriptInvitation<?>[] ret = new ScriptInvitation[invitations.size()];
    int i = 0;
    for(Invitation item : invitations)
    {
        ret[i++] = scriptInvitationFactory.toScriptInvitation(item);
    }
    return ret;
}
 
Example 17
/**
 * {@inheritDoc}
 */
@Extend(traitAPI=LockServiceTrait.class,extensionAPI=LockServiceExtension.class)
public void checkForLock(NodeRef nodeRef) throws NodeLockedException
{
    String userName = getUserName();
    
    nodeRef = tenantService.getName(nodeRef);
 
    // Ensure we have found a node reference
    if (nodeRef != null && userName != null)
    {
        String effectiveUserName = AuthenticationUtil.getRunAsUser();
        // Check to see if should just ignore this node - note: special MT System due to AuditableAspect
        if (! (ignore(nodeRef) || tenantService.getBaseNameUser(effectiveUserName).equals(AuthenticationUtil.getSystemUserName())))
        {
            try
            {
                // Get the current lock status on the node ref
                LockStatus currentLockStatus = getLockStatus(nodeRef, userName);

                LockType lockType = getLockType(nodeRef);
                if (LockType.WRITE_LOCK.equals(lockType) == true && 
                    LockStatus.LOCKED.equals(currentLockStatus) == true)
                {
                    // Lock is of type Write Lock and the node is locked by another owner.
                    throw new NodeLockedException(nodeRef);
                }
                else if (LockType.READ_ONLY_LOCK.equals(lockType) == true &&
                         (LockStatus.LOCKED.equals(currentLockStatus) == true || LockStatus.LOCK_OWNER.equals(currentLockStatus) == true))
                {
                    // Error since there is a read only lock on this object and all
                    // modifications are prevented
                    throw new NodeLockedException(nodeRef);
                }
                else if (LockType.NODE_LOCK.equals(lockType) == true &&
                        (LockStatus.LOCKED.equals(currentLockStatus) == true || LockStatus.LOCK_OWNER.equals(currentLockStatus) == true))
                {
                    // Error since there is a read only lock on this object and all
                    // modifications are prevented
                    throw new NodeLockedException(nodeRef);
                }

            }
            catch (AspectMissingException exception)
            {
                // Ignore since this indicates that the node does not have the lock aspect applied
            }
        }
    }
}
 
Example 18
public NoCredentialsFoundException(String remoteSystemId) 
{
    super("No Credentials Found for " + AuthenticationUtil.getRunAsUser() + " for Remote System '" + remoteSystemId + "'");
}
 
Example 19
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
{

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

    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    final String siteShortName = templateVars.get("shortname");
    final String invitationId = templateVars.get("invitationId");
    validateParameters(siteShortName, invitationId);

    try
    {
        // MNT-9905 Pending Invites created by one site manager aren't visible to other site managers
        String currentUser = AuthenticationUtil.getRunAsUser();

        if (siteShortName != null && (SiteModel.SITE_MANAGER).equals(siteService.getMembersRole(siteShortName, currentUser)))
        {

            RunAsWork<Void> runAsSystem = new RunAsWork<Void>()
            {
                @Override
                public Void doWork() throws Exception
                {
                    checkAndCancelTheInvitation(invitationId, siteShortName);
                    return null;
                }
            };

            AuthenticationUtil.runAs(runAsSystem, AuthenticationUtil.getSystemUserName());
        }
        else
        {
            checkAndCancelTheInvitation(invitationId, siteShortName);
        }
    }
    catch (InvitationExceptionForbidden fe)
    {
        throw new WebScriptException(Status.STATUS_FORBIDDEN, "Unable to cancel workflow", fe);
    }
    catch (AccessDeniedException ade)
    {
        throw new WebScriptException(Status.STATUS_FORBIDDEN, "Unable to cancel workflow", ade);
    }

    return model;
}
 
Example 20
@Override
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) 
{
	NodeService nodeService = serviceRegistry.getNodeService();
	ContentService contentService = serviceRegistry.getContentService();
	byte[] sigBytes;

	if (nodeService.exists(actionedUponNodeRef) == false)
       {
           return;
       }
   	 
       String location = (String)ruleAction.getParameterValue(PARAM_LOCATION);
       String geolocation = (String)ruleAction.getParameterValue(PARAM_GEOLOCATION);
       String reason = (String)ruleAction.getParameterValue(PARAM_REASON);
       String keyPassword = (String)ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
       
	// get a hash of the document
       InputStream contentStream = contentService.
       		getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT).getContentInputStream();
	
       try
       {
           // get the user's private key
        String user = AuthenticationUtil.getRunAsUser();
    	SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user);
        KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword);
        PrivateKey key = (PrivateKey)keystore.getKey(alias, keyPassword.toCharArray());
        
        // compute the document hash
        byte[] hash = signatureProvider.computeHash(contentStream);
        
		// sign the hash
		sigBytes = signatureProvider.signHash(hash, keyPassword);
		
		// create a "signature" node and associate it with the signed doc
        NodeRef sig = addSignatureNodeAssociation(actionedUponNodeRef, location, reason, 
        		"none", new java.util.Date(), geolocation, -1, "none");
        
		// save the signature
		ContentWriter writer = contentService.getWriter(sig, ContentModel.PROP_CONTENT, true);
		writer.putContent(new ByteArrayInputStream(sigBytes));
		
		// also save the expected hash in the signature
		nodeService.setProperty(sig, CounterSignSignatureModel.PROP_DOCHASH, new String(hash));
       }
       catch(UnrecoverableKeyException uke)
       {
       	throw new AlfrescoRuntimeException(uke.getMessage());
       } 
       catch (KeyStoreException kse) 
       {
		throw new AlfrescoRuntimeException(kse.getMessage());
	} 
       catch (NoSuchAlgorithmException nsae) 
	{
		throw new AlfrescoRuntimeException(nsae.getMessage());
	} 
       catch (Exception e) 
       {
		throw new AlfrescoRuntimeException(e.getMessage());
	}
}