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

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationUtil#isRunAsUserTheSystemUser() . 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: TransactionServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean isReadOnly()
{
    if (shutdownListener.isVmShuttingDown())
    {
        return true;
    }
    vetoReadLock.lock();
    try
    {
        if (AuthenticationUtil.isRunAsUserTheSystemUser())
        {
            return false;
        }
        else
        {
            return !writeVeto.isEmpty();
        }
    }
    finally
    {
        vetoReadLock.unlock();
    }
}
 
Example 2
Source File: UsageQuotaProtector.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Called after a node's properties have been changed.
 * 
 * @param nodeRef reference to the updated node
 * @param before the node's properties before the change
 * @param after the node's properties after the change 
 */
public void onUpdateProperties(
        NodeRef nodeRef,
        Map<QName, Serializable> before,
        Map<QName, Serializable> after)
{    
    Long sizeCurrentBefore = (Long)before.get(ContentModel.PROP_SIZE_CURRENT);
    Long sizeCurrentAfter = (Long)after.get(ContentModel.PROP_SIZE_CURRENT); 
        
    Long sizeQuotaBefore = (Long)before.get(ContentModel.PROP_SIZE_QUOTA);
    Long sizeQuotaAfter = (Long)after.get(ContentModel.PROP_SIZE_QUOTA); 
    
    // Check for change in sizeCurrent
    if ((sizeCurrentBefore != null && !sizeCurrentBefore.equals(sizeCurrentAfter)) && (sizeCurrentBefore != null) &&
        (! (authorityService.hasAdminAuthority() || AuthenticationUtil.isRunAsUserTheSystemUser())))
    {
        throw new AlfrescoRuntimeException("Update failed: protected property 'sizeCurrent'");
    }
    
    // Check for change in sizeQuota
    if ((sizeQuotaBefore != null && !sizeQuotaBefore.equals(sizeQuotaAfter)) && (sizeQuotaBefore != null) &&
        (! (authorityService.hasAdminAuthority() || AuthenticationUtil.isRunAsUserTheSystemUser())))
    {
        throw new AlfrescoRuntimeException("Update failed: protected property 'sizeQuota'");
    }
}
 
Example 3
Source File: SubscriptionServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Checks if the current user is allowed to get change data.
 */
protected void checkWrite(String userId)
{
    if (userId == null)
    {
        throw new IllegalArgumentException("User Id may not be null!");
    }

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

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

    throw new AccessDeniedException("subscription_service.err.write-denied");
}
 
Example 4
Source File: InvitationServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Invitation cancelModeratedInvitation(WorkflowTask startTask)
{
    ModeratedInvitation invitation = getModeratedInvitation(startTask.getPath().getId());
    String currentUserName = this.authenticationService.getCurrentUserName();
    if (!AuthenticationUtil.isRunAsUserTheSystemUser())
    {
        if (false == currentUserName.equals(invitation.getInviteeUserName()))
        {
            checkManagerRole(currentUserName, invitation.getResourceType(), invitation.getResourceName());
        }
    }
    // Only proceed with the cancel if the site still exists (the site may have been deleted and invitations may be
    // getting cancelled in the background)
    if (this.siteService.getSite(invitation.getResourceName()) != null)
    {
        workflowService.cancelWorkflow(invitation.getInviteId());
    }
    return invitation;
}
 
Example 5
Source File: InvitationServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Invitation cancelNominatedInvitation(WorkflowTask startTask)
{
    NominatedInvitation invitation = getNominatedInvitation(startTask);
    String currentUserName = this.authenticationService.getCurrentUserName();
    if (!AuthenticationUtil.isRunAsUserTheSystemUser())
    {
        if (false == currentUserName.equals(invitation.getInviterUserName()))
        {
            checkManagerRole(currentUserName, invitation.getResourceType(), invitation.getResourceName());
        }
    }
    // Only proceed with the cancel if the site still exists (the site may have been deleted and invitations may be
    // getting cancelled in the background)
    if (this.siteService.getSite(invitation.getResourceName()) != null)
    {
        endInvitation(startTask, WorkflowModelNominatedInvitation.WF_TRANSITION_CANCEL, null,
                WorkflowModelNominatedInvitation.WF_TASK_ACTIVIT_INVITE_PENDING);
    }
    return invitation;
}
 
Example 6
Source File: InvitationServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void cancelInvitation(String siteName, String invitee, String inviteId, String currentInviteId)
{
    if (!AuthenticationUtil.isRunAsUserTheSystemUser())
    {
        String currentUserName = authenticationService.getCurrentUserName();
        String currentUserSiteRole = siteService.getMembersRole(siteName, currentUserName);
        if (SiteModel.SITE_MANAGER.equals(currentUserSiteRole)== false)
        {
            // The current user is not the site manager
            Object[] args = {currentUserName, inviteId, siteName};
            throw new InvitationExceptionForbidden(MSG_NOT_SITE_MANAGER, args);
        }
    }
    
    // Clean up invitee's user account and person node if they are not in use i.e.
    // account is still disabled and there are no pending invites outstanding for the
    // invitee
    deleteAuthenticationIfUnused(invitee, currentInviteId);
}
 
Example 7
Source File: DictionaryModelType.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean isUserNameAModelAdminAuthority(String userName)
{
    if (userName == null)
    {
        return false;
    }
    // this also allows the AuthenticationUtil.SYSTEM_USER_NAME ("System") user
    return this.authorityService.isAdminAuthority(userName)
           || this.authorityService.getAuthoritiesForUser(userName).contains(GROUP_ALFRESCO_MODEL_ADMINISTRATORS_AUTHORITY)
           || AuthenticationUtil.isRunAsUserTheSystemUser();
}
 
Example 8
Source File: AuthorityTypeBehaviour.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void onUpdateProperties(NodeRef nodeRef, Map<QName, Serializable> before, Map<QName, Serializable> after)
{
    if (modifyingOwnAccount(before, after))
    {
        return;
    }

    if (!(AuthenticationUtil.isRunAsUserTheSystemUser() || authorityService.hasAdminAuthority()))
    {
        throw new AccessDeniedException("Only users with ROLE_ADMINISTRATOR are allowed to manage users.");
    }
}
 
Example 9
Source File: RenameSiteAuthorityDisplayName.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected String applyInternal() throws Exception
{
 // NOTE: SiteService is not currently MT-enabled (eg. getSiteRoot) so skip if applied to tenant
    if (AuthenticationUtil.isRunAsUserTheSystemUser() || !AuthenticationUtil.isMtEnabled())
    {
        // Set all the sites in the repository
        List<SiteInfo> sites = this.siteService.listSites(null, null);
        renameDispayNames(sites);
    }
    // Report status
    return I18NUtil.getMessage(SUCCESS_MSG);
}
 
Example 10
Source File: SubscriptionServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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
Source File: MultiTServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void checkTenantEnabled(String tenantDomain)
{
    Tenant tenant = getTenant(tenantDomain);
    // note: System user can access disabled tenants
    if (tenant == null || !AuthenticationUtil.isRunAsUserTheSystemUser() && !tenant.isEnabled())
    {
        throw new TenantDisabledException(tenantDomain);
    }
}
 
Example 12
Source File: PermissionServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 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 13
Source File: HiddenAspect.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Gets the visibility constraint for the given client on the given node.
 * 
 * @param client Client
 * @param nodeRef NodeRef
 * 
 * @return the visibility constraint for the given client and node
 */
public Visibility getVisibility(Client client, NodeRef nodeRef)
{
    Visibility ret = Visibility.Visible;

    if (! AuthenticationUtil.isRunAsUserTheSystemUser())
    {
        if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_HIDDEN))
        {
            Integer visibilityMask = (Integer)nodeService.getProperty(nodeRef, ContentModel.PROP_VISIBILITY_MASK);
            if (visibilityMask != null)
            {
            	if(client != null && client.equals(Client.admin))
            	{
                    ret = Visibility.Visible;
            	}
            	else if(visibilityMask.intValue() == 0)
                {
                    ret = Visibility.NotVisible;
                }
                else if(client == null)
                {
                    ret = Visibility.NotVisible;
                }
                else
                {
                    ret = getVisibility(visibilityMask.intValue(), client);
                }
            }
            else
            {
                // no visibility mask property, so retain backwards compatibility with 3.4 hidden aspect behaviour
                if(client == Client.cifs)
                {
                    ret = Visibility.HiddenAttribute;
                }
                else if(client == Client.webdav || client == Client.nfs || client == Client.imap)
                {
                    ret = Visibility.Visible;
                }
                else
                {
                    ret = Visibility.NotVisible;
                }
            }
        }
    }
    return ret;
}
 
Example 14
Source File: RuleServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void addRulePendingExecution(NodeRef actionableNodeRef, NodeRef actionedUponNodeRef, Rule rule, boolean executeAtEnd) 
{
    ParameterCheck.mandatory("actionableNodeRef", actionableNodeRef);
    ParameterCheck.mandatory("actionedUponNodeRef", actionedUponNodeRef);
    
    // First check to see if the node has been disabled
    if (this.isEnabled() == true &&
        this.rulesEnabled(this.getOwningNodeRef(rule)) &&
        this.disabledRules.contains(rule) == false)
    {
        PendingRuleData pendingRuleData = new PendingRuleData(actionableNodeRef, actionedUponNodeRef, rule, executeAtEnd);
        pendingRuleData.setRunAsUser(AuthenticationUtil.getRunAsUser());

        List<PendingRuleData> pendingRules =
            (List<PendingRuleData>) AlfrescoTransactionSupport.getResource(KEY_RULES_PENDING);
        if (pendingRules == null)
        {
            // bind pending rules to the current transaction
            pendingRules = new ArrayList<PendingRuleData>();
            AlfrescoTransactionSupport.bindResource(KEY_RULES_PENDING, pendingRules);
            // bind the rule transaction listener
            AlfrescoTransactionSupport.bindListener(this.ruleTransactionListener);
            
            if (logger.isDebugEnabled() == true)
            {
                logger.debug("Rule '" + rule.getTitle() + "' has been added pending execution to action upon node '" + actionedUponNodeRef.getId() + "'");
            }
        }
        
        // Prevent the same rule being executed more than once in the same transaction    
        if (pendingRules.contains(pendingRuleData) == false)
        {
            if ((AuthenticationUtil.isRunAsUserTheSystemUser()) && (rule.getAction() instanceof ActionImpl))
            {
                ((ActionImpl)rule.getAction()).setRunAsUser(AuthenticationUtil.SYSTEM_USER_NAME);
            }
            pendingRules.add(pendingRuleData);
        }
    }
    else
    {
        if (logger.isDebugEnabled() == true)
        {
            logger.debug("The rule '" + rule.getTitle() + "' or the node '" + this.getOwningNodeRef(rule).getId() + "' has been disabled.");
        }
    }
}
 
Example 15
Source File: RuleServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void executePendingRuleImpl(PendingRuleData pendingRule) 
{
    Set<ExecutedRuleData> executedRules =
           (Set<ExecutedRuleData>) AlfrescoTransactionSupport.getResource(KEY_RULES_EXECUTED);

    NodeRef actionedUponNodeRef = pendingRule.getActionedUponNodeRef();
    Rule rule = pendingRule.getRule();
    
    boolean isSystemUser = false;
    if (!(AuthenticationUtil.isRunAsUserTheSystemUser()) && (rule.getAction()!=null) && (rule.getAction() instanceof ActionImpl))
    {
        isSystemUser = AuthenticationUtil.SYSTEM_USER_NAME.equals(((ActionImpl) rule.getAction()).getRunAsUser());
    }
		
    NodeRef ruleNodeRef = rule.getNodeRef();
    if (!ruleNodeRef.getStoreRef().equals(actionedUponNodeRef.getStoreRef()) && !nodeService.exists(ruleNodeRef))
    {
        NodeRef newRuleNodeRef = new NodeRef(actionedUponNodeRef.getStoreRef(), ruleNodeRef.getId());
        if (nodeService.exists(newRuleNodeRef))
        {
            ruleNodeRef = newRuleNodeRef;
        }
        
    }
    final NodeRef finalRuleNodeRef = ruleNodeRef;
    // update all associations and actions
    rule = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Rule>()
    {
        public Rule doWork() throws Exception
        {
            return getRule(finalRuleNodeRef);
        }
    }, AuthenticationUtil.getSystemUserName());

    if (executedRules == null || canExecuteRule(executedRules, actionedUponNodeRef, rule) == true)
    {
        if (isSystemUser)
        {
            final Rule fRule = rule;
            final NodeRef fActionedUponNodeRef = actionedUponNodeRef;
            final Set<ExecutedRuleData> fExecutedRules = executedRules;
            AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>()
            {
                public Void doWork() throws Exception
                {
                    executeRule(fRule, fActionedUponNodeRef, fExecutedRules);
                    return null;
                }
            }, AuthenticationUtil.getSystemUserName());
        }
        else
        {
            executeRule(rule, actionedUponNodeRef, executedRules);
        }
    }
}