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

The following are Jave code examples for showing how to use runAs() 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: ModuleStarter.java   Source Code and License Vote up 8 votes
@Override
protected void onBootstrap(ApplicationEvent event)
{
    PropertyCheck.mandatory(this, "moduleService", moduleService);
    final RetryingTransactionCallback<Object> startModulesCallback = new RetryingTransactionCallback<Object>()
    {
        public Object execute() throws Throwable
        {
            moduleService.startModules();
            return null;
        }
    };
    
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        @Override
        public Object doWork() throws Exception 
        {
            transactionService.getRetryingTransactionHelper().doInTransaction(startModulesCallback, transactionService.isReadOnly());
            return null;
        }
    	
    }, AuthenticationUtil.getSystemUserName());       
}
 
Example 2
Project: alfresco-remote-api   File: RepoStore.java   Source Code and License Vote up 7 votes
public boolean hasDocument(final String documentPath)
{
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Boolean>()
    {
        public Boolean doWork() throws Exception
        {
            return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Boolean>()
            {
                public Boolean execute() throws Exception
                {
                    NodeRef nodeRef = findNodeRef(documentPath);
                    return (nodeRef != null);
                }
            }, true, false);
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example 3
Project: alfresco-repository   File: DescriptorServiceImpl.java   Source Code and License Vote up 6 votes
/**
 * On bootstrap load the special services for LicenseComponent
 * 
 * Also set installedRepoDescriptor and update current
 */
@Override
protected void onBootstrap(ApplicationEvent event)
{
    AuthenticationUtil.RunAsWork<Void> bootstrapWork = new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            bootstrap();
            return null;
        }
    };
    AuthenticationUtil.runAs(bootstrapWork, AuthenticationUtil.getSystemUserName());
    isBootstrapped = true;
    // Broadcast that the descriptor service is now available
    ((ApplicationContext) event.getSource()).publishEvent(new DescriptorServiceAvailableEvent(this));
}
 
Example 4
Project: alfresco-repository   File: TestPersonManager.java   Source Code and License Vote up 6 votes
public NodeRef createPerson(final String userName)
{
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<NodeRef>()
    {
        public NodeRef doWork() throws Exception
        {
            if (authenticationService.authenticationExists(userName) == false)
            {
                authenticationService.createAuthentication(userName, "password".toCharArray());
                return makePersonNode(userName);
            }
            else
            {
                return personService.getPerson(userName);
            }
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example 5
Project: alfresco-repository   File: AuditComponentTest.java   Source Code and License Vote up 5 votes
/**
 * Clear the audit log as 'admin'
 */
private Integer deleteAuditEntries(final String applicationName, final long fromId, final long toId)
{
    RunAsWork<Integer> work = new RunAsWork<Integer>()
    {
        @Override
        public Integer doWork() throws Exception
        {
            return new Integer(auditService.clearAuditByIdRange(applicationName, fromId, toId));
        }
    };
    return AuthenticationUtil.runAs(work, AuthenticationUtil.getAdminRoleName());
}
 
Example 6
Project: alfresco-data-model   File: DictionaryDAOImpl.java   Source Code and License Vote up 5 votes
/**
 * For cache use only.
 * 
 * @param tenantDomain String
 * @return constructed DictionaryRegistry
 */
public DictionaryRegistry initDictionaryRegistry(final String tenantDomain)
{
    return AuthenticationUtil.runAs(
            new RunAsWork<DictionaryRegistry>()
            {
                public DictionaryRegistry doWork()
                {
                    DictionaryRegistry dictionaryRegistry = null;
                    if (tenantDomain.equals(TenantService.DEFAULT_DOMAIN))
                    {
                        dictionaryRegistry = createCoreDictionaryRegistry();
                    }
                    else
                    {
                        dictionaryRegistry = createTenantDictionaryRegistry(tenantDomain);
                    }

                    getThreadLocal().put(tenantDomain, dictionaryRegistry);
                    dictionaryRegistry.init();
                    getThreadLocal().remove(tenantDomain);

                    return dictionaryRegistry;
                }
            },
            tenantService.getDomainUser(
                    AuthenticationUtil.getSystemUserName(), tenantDomain));
}
 
Example 7
Project: alfresco-repository   File: HomeFolderProviderSynchronizerTest.java   Source Code and License Vote up 5 votes
private void createTenant(final String tenantDomain)
{
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            if (!tenantAdminService.existsTenant(tenantDomain))
            {
                tenantAdminService.createTenant(tenantDomain,
                        ("admin "+tenantDomain).toCharArray(), null);
            }
            return null;
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example 8
Project: alfresco-remote-api   File: ADMRemoteStore.java   Source Code and License Vote up 5 votes
/**
 * Lists the document paths under a given path.
 * <p>
 * The output will be the list of relative document paths found under the path.
 * Separated by newline characters.
 * 
 * @param path      document path
 * @param recurse   true to peform a recursive list, false for direct children only.
 * 
 * @throws IOException if an error occurs listing the documents
 */
@Override
protected void listDocuments(final WebScriptResponse res, final String store, final String path, final boolean recurse)
    throws IOException
{
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @SuppressWarnings("synthetic-access")
        public Void doWork() throws Exception
        {
            res.setContentType("text/plain;charset=UTF-8");
            
            final String encpath = encodePath(path);
            final FileInfo fileInfo = resolveNodePath(encpath, false, true);
            if (fileInfo == null || !fileInfo.isFolder())
            {
                res.setStatus(Status.STATUS_NOT_FOUND);
                return null;
            }
            
            try
            {
                outputFileNodes(res.getWriter(), fileInfo, aquireSurfConfigRef(encpath, false), "*", recurse);
            }
            catch (AccessDeniedException ae)
            {
                res.setStatus(Status.STATUS_UNAUTHORIZED);
            }
            finally
            {
                res.getWriter().close();
            }
            return null;
        }
    }, AuthenticationUtil.getSystemUserName());
}
 
Example 9
Project: alfresco-repository   File: ActivitiScriptBase.java   Source Code and License Vote up 5 votes
protected Object executeScriptAsUser(final String theScript, final Map<String, Object> model, final String scriptProcessorName, final String runAsUser)
{
    // execute as specified runAsUser
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            return executeScript(theScript, model, scriptProcessorName);
        }
    }, runAsUser);
}
 
Example 10
Project: alfresco-repository   File: ImapFoldersPatch.java   Source Code and License Vote up 5 votes
@Override
protected String applyInternal() throws Exception
{
    checkCommonProperties();
    setUp();
    String msg = null;
    if (imapConfigFolderNodeRef == null)
    {
        // import the content
        final RunAsWork<Object> importRunAs = new RunAsWork<Object>()
        {
            public Object doWork() throws Exception
            {
                importImapConfig();
                importScripts();
                importEmailActions();
                return null;
            }
        };
        
        RetryingTransactionCallback<Object> cb = new RetryingTransactionCallback<Object>()
        {
            public Object execute() throws Throwable 
            {
                AuthenticationUtil.runAs(importRunAs, authenticationContext.getSystemUserName());
                return null;
            }
     
        };
        
        transactionHelper.doInTransaction(cb, false, true);
        msg = I18NUtil.getMessage(MSG_CREATED);
    }
    else
    {
        msg = I18NUtil.getMessage(MSG_EXISTS, imapConfigFolderNodeRef);
    }
    return msg;

}
 
Example 11
Project: alfresco-repository   File: AuthenticatedAsyncJobHandler.java   Source Code and License Vote up 5 votes
@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 12
Project: alfresco-repository   File: MessageServiceImpl.java   Source Code and License Vote up 5 votes
public ResourceBundle getRepoResourceBundle(
        final StoreRef storeRef,
        final String path,
        final Locale locale) throws IOException
{   
    // TODO - need to replace basic strategy with a more complete
    // search & instantiation strategy similar to ResourceBundle.getBundle()
    // Consider search query with basename* and then apply strategy ...
    
    // Avoid permission exceptions
    RunAsWork<ResourceBundle> getBundleWork = new RunAsWork<ResourceBundle>()
    {
        @Override
        public ResourceBundle doWork() throws Exception
        {
            NodeRef rootNode = nodeService.getRootNode(storeRef);

            // first attempt - with locale        
            NodeRef nodeRef = getNode(rootNode, path+"_"+locale+PROPERTIES_FILE_SUFFIX);
            
            if (nodeRef == null)
            {
                // second attempt - basename 
                nodeRef = getNode(rootNode, path+PROPERTIES_FILE_SUFFIX);
            }
            
            if (nodeRef == null)
            {
                logger.debug("Could not find message resource bundle " + storeRef + "/" + path);
                return null;
            }
            
            ContentReader cr = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
            ResourceBundle resBundle = new MessagePropertyResourceBundle(
                    new InputStreamReader(cr.getContentInputStream(), cr.getEncoding()));
            return resBundle;
        }
    };
    return AuthenticationUtil.runAs(getBundleWork, AuthenticationUtil.getSystemUserName());
}
 
Example 13
Project: alfresco-repository   File: QuickShareServiceIntegrationTest.java   Source Code and License Vote up 4 votes
private QuickShareDTO share(final NodeRef nodeRef, final String username, final Date expiryDate)
{
    return AuthenticationUtil.runAs(() -> quickShareService.shareContent(nodeRef, expiryDate), username);
}
 
Example 14
Project: alfresco-repository   File: Site.java   Source Code and License Vote up 4 votes
/**
 * Apply a set of permissions to the node.
 * 
 * @param node   node
 * @param permissions   permissions
 */
public void setPermissions(final ScriptNode node, final Object permissions)
{
    final NodeRef nodeRef = node.getNodeRef();
    
    if (permissions != null && permissions instanceof ScriptableObject)
    {
        final PermissionService permissionService = this.serviceRegistry.getPermissionService();
        // ensure the user has permission to Change Permissions
        if (permissionService.hasPermission(nodeRef, PermissionService.CHANGE_PERMISSIONS).equals(AccessStatus.ALLOWED))
        {
            AuthenticationUtil.runAs(new RunAsWork<Void>()
            {
                public Void doWork() throws Exception
                {
                    if (!permissionService.getInheritParentPermissions(nodeRef))
                    {
                        // remove existing permissions
                        permissionService.deletePermissions(nodeRef);
                    }
                    
                    // Assign the correct permissions
                    ScriptableObject scriptable = (ScriptableObject)permissions;
                    Object[] propIds = scriptable.getIds();
                    for (int i = 0; i < propIds.length; i++)
                    {
                        // Work on each key in turn
                        Object propId = propIds[i];
                        
                        // Only interested in keys that are formed of Strings
                        if (propId instanceof String)
                        {
                            // Get the value out for the specified key - it must be String
                            final String key = (String)propId;
                            final Object value = scriptable.get(key, scriptable);
                            if (value instanceof String)
                            {                                   
                                // Set the permission on the node
                                permissionService.setPermission(nodeRef, key, (String)value, true);
                            }
                        }
                    }
                    
                    // always add the site managers group with SiteManager permission
                    String managers = siteService.getSiteRoleGroup(getShortName(), SiteModel.SITE_MANAGER);
                    permissionService.setPermission(nodeRef, managers, SiteModel.SITE_MANAGER, true);
                    
                    // now turn off inherit to finalize our permission changes
                    permissionService.setInheritParentPermissions(nodeRef, false);
                    return null;
                }
            }, AuthenticationUtil.SYSTEM_USER_NAME);
        }
    }
    else
    {
    	// No permissions passed-in
    	this.resetAllPermissions(node);
    }
}
 
Example 15
Project: alfresco-repository   File: UpdateTagScopesQuartzJob.java   Source Code and License Vote up 4 votes
protected void execute(final ActionService actionService, final UpdateTagScopesActionExecuter updateTagsAction)
{
    // Process
    final ArrayList<NodeRef> tagNodes = new ArrayList<NodeRef>();
    final HashSet<NodeRef> handledTagNodes = new HashSet<NodeRef>();
    
    while(true)
    {
       // Fetch a batch of the pending changes
       AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>() 
          {
             public Void doWork() throws Exception
             {
                tagNodes.clear();
                tagNodes.addAll(
                      updateTagsAction.searchForTagScopesPendingUpdates()
                );
                return null;
             }
          }, AuthenticationUtil.getSystemUserName()
       );
       
       // If we're on our 2nd loop round for any of them, then skip them from now on
       // (This can happen if another thread is already processing one of them)
       Iterator<NodeRef> it = tagNodes.iterator();
       while(it.hasNext())
       {
          NodeRef nodeRef = it.next();
          if(handledTagNodes.contains(nodeRef))
          {
             it.remove();
             if(logger.isDebugEnabled())
                logger.debug("Tag scope " + nodeRef + " must be being processed by another Thread, not updating it");
          }
       }
       
       // Log what we found to process
       if(logger.isDebugEnabled())
       {
          logger.debug("Checked for tag scopes with pending tag updates, found " + tagNodes);
       }
       
       // If we're out of tag scopes, stop!
       if(tagNodes.size() == 0)
          break;
       
       // Have the action run for these tag scope nodes
       // Needs to run synchronously
       Action action = actionService.createAction(UpdateTagScopesActionExecuter.NAME);
       action.setParameterValue(UpdateTagScopesActionExecuter.PARAM_TAG_SCOPES, (Serializable)tagNodes); 
       actionService.executeAction(action, null, false, false);
       
       // Record the scopes we've just done
       handledTagNodes.addAll(tagNodes);
    }
}
 
Example 16
Project: alfresco-repository   File: Site.java   Source Code and License Vote up 4 votes
private NodeRef createContainerImpl(final String componentId, final String folderType, final Object permissions)
{
    return AuthenticationUtil.runAs(new RunAsWork<NodeRef>()
    {
        public NodeRef doWork() throws Exception
        {
            // Get the container type
            QName folderQName = (folderType == null) ? null : QName.createQName(folderType, serviceRegistry.getNamespaceService());
            
            // Create the container node
            NodeRef containerNode = Site.this.siteService.createContainer(getShortName(), componentId, folderQName, null);
            
            // Set any permissions that might have been provided for the container
            if (permissions != null && permissions instanceof ScriptableObject)
            {
                ScriptableObject scriptable = (ScriptableObject)permissions;
                Object[] propIds = scriptable.getIds();
                for (int i = 0; i < propIds.length; i++)
                {
                    // work on each key in turn
                    Object propId = propIds[i];
                    
                    // we are only interested in keys that are formed of Strings
                    if (propId instanceof String)
                    {
                        // get the value out for the specified key - it must be String
                        final String key = (String)propId;
                        final Object value = scriptable.get(key, scriptable);
                        if (value instanceof String)
                        {                                   
                            // Set the permission on the container
                            Site.this.serviceRegistry.getPermissionService().setPermission(containerNode, key, (String)value, true);
                        }
                    }
                }
            }
            
            // Make the "admin" the owner of the node
            serviceRegistry.getOwnableService().setOwner(containerNode, AuthenticationUtil.getAdminUserName());
    
            return containerNode;
        }
    }, AuthenticationUtil.SYSTEM_USER_NAME);
}
 
Example 17
Project: alfresco-repository   File: IncompleteNodeTaggerTest.java   Source Code and License Vote up 4 votes
/**
 * Test for MNT-17239: Unexpected changes of cm:modified and cm:modifier
 */
public void testUnexpectedAuditUpdate() throws Exception
{
    NodeRef nodeRef = createNode("abc", IntegrityTest.TEST_TYPE_WITH_PROPERTIES, null);

    checkTagging(nodeRef, true);

    // Now remove the aspect.
    nodeService.removeAspect(nodeRef, ContentModel.ASPECT_INCOMPLETE);

    // Assert the node is not auditable.
    Set<QName> aspects = nodeService.getAspects(nodeRef);
    assertFalse(aspects.contains(ContentModel.ASPECT_AUDITABLE));

    // Add auditable capability.
    nodeService.addAspect(nodeRef, ContentModel.ASPECT_AUDITABLE, null);

    // Assert the node is now auditable.
    aspects = nodeService.getAspects(nodeRef);
    assertTrue(aspects.contains(ContentModel.ASPECT_AUDITABLE));

    final Map<QName, Serializable> props = nodeService.getProperties(nodeRef);
    assertNotNull(props.get(ContentModel.PROP_CREATED));
    assertNotNull(props.get(ContentModel.PROP_MODIFIED));
    assertNotNull(props.get(ContentModel.PROP_CREATOR));
    assertNotNull(props.get(ContentModel.PROP_MODIFIER));

    // Authenticate as someone else - someone not able to do anything
    final String user = "user-" + UUID.randomUUID();
    RunAsWork<Void> createUserWork = new RunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            if (!authenticationService.authenticationExists(user))
            {
                authenticationService.createAuthentication(user, user.toCharArray());
            }
            return null;
        }
    };
    AuthenticationUtil.runAs(createUserWork, AuthenticationUtil.getSystemUserName());
    authenticationComponent.setCurrentUser(user);

    // Tag
    checkTagging(nodeRef, true);

    // Check that audit behavior wasn't triggered.
    checkAuditableProperties(nodeRef, props);
}
 
Example 18
Project: alfresco-remote-api   File: FacetRestApiTest.java   Source Code and License Vote up 4 votes
public void testNonSearchAdminUserCannotCreateUpdateSolrFacets() throws Exception
{
    // Create a filter
    final JSONObject filter = new JSONObject();
    final String filterName = "filter" + System.currentTimeMillis();
    filters.add(filterName);
    filter.put("filterID", filterName);
    filter.put("facetQName", "cm:test1");
    filter.put("displayName", "facet-menu.facet.test1");
    filter.put("displayControl", "alfresco/search/FacetFilters/test1");
    filter.put("maxFilters", 5);
    filter.put("hitThreshold", 1);
    filter.put("minFilterValueLength", 4);
    filter.put("sortBy", "ALPHABETICALLY");

    // Non-Search-Admin tries to create a filter
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            // Post the filter
            sendRequest(new PostRequest(POST_FACETS_URL, filter.toString(), "application/json"), 403);
            return null;
        }
    }, NON_SEARCH_ADMIN_USER);

    // Search-Admin creates a filter
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            // Post the filter
            sendRequest(new PostRequest(POST_FACETS_URL, filter.toString(), "application/json"), 200);
            return null;
        }
    }, SEARCH_ADMIN_USER);

    // Non-Search-Admin tries to modify the filter
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            Response response = sendRequest(new GetRequest(GET_FACETS_URL + "/" + filterName), 200);
            JSONObject jsonRsp = new JSONObject(new JSONTokener(response.getContentAsString()));
            assertEquals(filterName, jsonRsp.getString("filterID"));
            assertEquals(5, jsonRsp.getInt("maxFilters"));
            // Now change the maxFilters value and try to update
            jsonRsp.put("maxFilters", 10);
            sendRequest(new PutRequest(PUT_FACETS_URL, jsonRsp.toString(), "application/json"), 403);

            return null;
        }
    }, NON_SEARCH_ADMIN_USER);
}
 
Example 19
Project: alfresco-remote-api   File: RepoStore.java   Source Code and License Vote up 4 votes
public String[] getAllDocumentPaths()
    {
        return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<String[]>()
        {
            public String[] doWork() throws Exception
            {
                return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<String[]>()
                {
                    public String[] execute() throws Exception
                    {
                        int baseDirLength = getBaseDir().length() +1;
                        
                        List<String> documentPaths;
                        
                        NodeRef repoStoreRootNodeRef = nodeService.getRootNode(repoStore);
                        List<NodeRef> nodeRefs = searchService.selectNodes(
                                repoStoreRootNodeRef,
                                repoPath +
                                "//*[subtypeOf('{http://www.alfresco.org/model/content/1.0}content')]\"",
                                new QueryParameterDefinition[] {},
                                namespaceService,
                                false,
                                SearchService.LANGUAGE_XPATH);
                        documentPaths = new ArrayList<String>(nodeRefs.size());
                      for (NodeRef nodeRef : nodeRefs)
                      {
                          if (isContentPresent(nodeRef))
                          {
                                String nodeDir = getPath(nodeRef);
                                documentPaths.add(nodeDir.substring(baseDirLength));
                          }
                      }
                        
//                        String query = "+PATH:\"" + repoPath +
//                                       "//*\" +TYPE:\"{http://www.alfresco.org/model/content/1.0}content\"";
//                        ResultSet resultSet = searchService.query(repoStore, SearchService.LANGUAGE_LUCENE, query);
//                        try
//                        {
//                            documentPaths = new ArrayList<String>(resultSet.length());
//                            List<NodeRef> nodes = resultSet.getNodeRefs();
//                            for (NodeRef nodeRef : nodes)
//                            {
//                                String nodeDir = getPath(nodeRef);
//                                documentPaths.add(nodeDir.substring(baseDirLength));
//                            }
//                        }
//                        finally
//                        {
//                            resultSet.close();
//                        }
                        
                        return documentPaths.toArray(new String[documentPaths.size()]);
                    }
                }, true, false);
            }
        }, AuthenticationUtil.getSystemUserName());
    }
 
Example 20
Project: alfresco-repository   File: SiteServiceImpl.java   Source Code and License Vote up 4 votes
/**
 * @see org.alfresco.service.cmr.site.SiteService#removeMembership(java.lang.String, java.lang.String)
 */
public void removeMembership(final String shortName, final String authorityName)
{
    final NodeRef siteNodeRef = getSiteNodeRef(shortName);
    if (siteNodeRef == null)
    {
       throw new SiteDoesNotExistException(shortName);
    }

    // TODO what do we do about the user if they are in a group that has
    // rights to the site?

    // Get the current user
    String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();

    // Get the user current role
    final String role = getMembersRole(shortName, authorityName);
    if (role != null)
    {
        // Check that we are not about to remove the last site manager
        checkLastManagerRemoval(shortName, authorityName, role);
        
        // If ...
        // -- the current user has change permissions rights on the site
        // or
        // -- the user is ourselves
        if ((currentUserName.equals(authorityName) == true) || isSiteAdmin(currentUserName) ||
            (permissionService.hasPermission(siteNodeRef, PermissionService.CHANGE_PERMISSIONS) == AccessStatus.ALLOWED))
        {
            // Run as system user
            AuthenticationUtil.runAs(
                new AuthenticationUtil.RunAsWork<Object>()
                {
                    public Object doWork() throws Exception
                    {
                        // Remove the user from the current permission
                        // group
                        String currentGroup = getSiteRoleGroup(shortName, role, true);
                        authorityService.removeAuthority(currentGroup, authorityName);
                        
                        return null;
                    }
                }, AuthenticationUtil.SYSTEM_USER_NAME);

            // Raise events
            AuthorityType authorityType = AuthorityType.getAuthorityType(authorityName);
            if (authorityType == AuthorityType.USER)
            {
                activityService.postActivity(
                        ActivityType.SITE_USER_REMOVED, shortName,
                        ACTIVITY_TOOL, getActivityUserData(authorityName, ""), authorityName);
            }
            else if (authorityType == AuthorityType.GROUP)
            {
                String authorityDisplayName = authorityService.getAuthorityDisplayName(authorityName);
                activityService.postActivity(
                        ActivityType.SITE_GROUP_REMOVED, shortName,
                        ACTIVITY_TOOL, getActivityGroupData(authorityDisplayName, ""));
            }
        }
        else
        {
            // Throw an exception
            throw new SiteServiceException(MSG_CAN_NOT_REMOVE_MSHIP, new Object[]{shortName});
        }
    } 
    else
    {
        // Throw an exception
        throw new SiteServiceException(MSG_CAN_NOT_REMOVE_MSHIP, new Object[]{shortName});
    }
}