org.alfresco.service.cmr.security.PermissionService Java Examples

The following examples show how to use org.alfresco.service.cmr.security.PermissionService. 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: HasPermissionMethod.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public AccessStatus execute(VirtualProtocol virtualProtocol, Reference reference) throws ProtocolMethodException
{
    VirtualFolderDefinition definition = resolver.resolveVirtualFolderDefinition(reference);
    FilingRule filingRule = definition.getFilingRule();

    boolean readonly = filingRule.isNullFilingRule()
                || filingRule.filingNodeRefFor(new FilingParameters(reference)) == null;
    if (readonly)
    {
        Set<String> deniedPermissions = userPermissions.getDenyReadonlySmartNodes();
        if (deniedPermissions.contains(permissionToCheck))
        {
            return AccessStatus.DENIED;
        }
        
        if (PermissionService.READ.equals(permissionToCheck))
        {
            return AccessStatus.ALLOWED;
        }
    }

    return userPermissions.hasVirtualNodePermission(permissionToCheck,
                                                    readonly);
}
 
Example #2
Source File: GroupsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void deleteGroupMembership(String groupId, String groupMemberId)
{
    validateGroupId(groupId, false);

    // Not allowed to modify a GROUP_EVERYONE member.
    if (PermissionService.ALL_AUTHORITIES.equals(groupId))
    {
        throw new ConstraintViolatedException(ERR_MSG_MODIFY_FIXED_AUTHORITY);
    }

    validateGroupMemberId(groupMemberId);

    // Verify if groupMemberId is member of groupId
    AuthorityType authorityType = AuthorityType.getAuthorityType(groupMemberId);
    Set<String> parents = authorityService.getContainingAuthorities(AuthorityType.GROUP, groupMemberId, true);
    if (!parents.contains(groupId))
    {
        throw new NotFoundException(groupMemberId + " is not member of " + groupId);
    }

    authorityService.removeAuthority(groupId, groupMemberId);
}
 
Example #3
Source File: LinksServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@BeforeClass public static void initTestsContext() throws Exception
{
    AUTHENTICATION_SERVICE = (MutableAuthenticationService)testContext.getBean("authenticationService");
    BEHAVIOUR_FILTER       = (BehaviourFilter)testContext.getBean("policyBehaviourFilter");
    LINKS_SERVICE          = (LinksService)testContext.getBean("LinksService");
    NODE_SERVICE           = (NodeService)testContext.getBean("nodeService");
    PUBLIC_NODE_SERVICE    = (NodeService)testContext.getBean("NodeService");
    PERSON_SERVICE         = (PersonService)testContext.getBean("personService");
    TRANSACTION_HELPER     = (RetryingTransactionHelper)testContext.getBean("retryingTransactionHelper");
    PERMISSION_SERVICE     = (PermissionService)testContext.getBean("permissionService");
    SITE_SERVICE           = (SiteService)testContext.getBean("siteService");
    CONTENT_SERVICE        = (ContentService)testContext.getBean("ContentService");

    // Do the setup as admin
    AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER);
    createUser(TEST_USER);
    
    // We need to create the test site as the test user so that they can contribute content to it in tests below.
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER);
    createTestSites();
}
 
Example #4
Source File: QuickShareServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean canRead(String sharedId)
{
    Pair<String, NodeRef> pair = getTenantNodeRefFromSharedId(sharedId);
    final String tenantDomain = pair.getFirst();
    final NodeRef nodeRef = pair.getSecond();
    
    return TenantUtil.runAsTenant(new TenantRunAsWork<Boolean>()
    {
        public Boolean doWork() throws Exception
        {
            try
            {
                checkQuickShareNode(nodeRef);
                return permissionService.hasPermission(nodeRef, PermissionService.READ) == AccessStatus.ALLOWED;
            }
            catch (AccessDeniedException ex)
            {
                return false;
            }
        }
    }, tenantDomain);
    
}
 
Example #5
Source File: AddGroupAuthorityPatch.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected String applyInternal() throws Exception
{
    StringBuilder result = new StringBuilder(I18NUtil.getMessage(MSG_START));

    String groupAuthorityName = PermissionService.GROUP_PREFIX + this.groupAuthorityDetails.groupName;
    if (!authorityService.authorityExists(groupAuthorityName))
    {
        groupAuthorityName = authorityService.createAuthority(AuthorityType.GROUP,
                    this.groupAuthorityDetails.groupName,
                    this.groupAuthorityDetails.groupDisplayName,
                    this.groupAuthorityDetails.authorityZones);

        authorityService.addAuthority(groupAuthorityName, AuthenticationUtil.getAdminUserName());

        result.append(I18NUtil.getMessage(MSG_RESULT, groupAuthorityName));
    }
    else
    {
        result.append(I18NUtil.getMessage(MSG_EXIST, groupAuthorityName));
    }
    return result.toString();
}
 
Example #6
Source File: GetAllSetPermissionsMethod.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Set<AccessPermission> execute(VirtualProtocol virtualProtocol, Reference reference)
            throws ProtocolMethodException
{
    Set<String> toAllow = userPermissions.getAllowSmartNodes();
    Set<String> toDeny = userPermissions.getDenySmartNodes();

    VirtualFolderDefinition definition = resolver.resolveVirtualFolderDefinition(reference);
    FilingRule filingRule = definition.getFilingRule();
    boolean readonly = filingRule.isNullFilingRule()
                || filingRule.filingNodeRefFor(new FilingParameters(reference)) == null;
    if (readonly)
    {
        Set<String> deniedPermissions = userPermissions.getDenyReadonlySmartNodes();
        toDeny = new HashSet<>(toDeny);
        toDeny.addAll(deniedPermissions);
        toAllow.add(PermissionService.READ);
    }
    

    return execute(reference,
                   toAllow,
                   toDeny);
}
 
Example #7
Source File: ACLEntryAfterInvocationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testBasicAllowChildAssociationRef2() throws Exception
{
    runAs("andy");

    Object o = new ClassWithMethods();
    Method method = o.getClass().getMethod("echoChildAssocRef", new Class[] { ChildAssociationRef.class });

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("AFTER_ACL_PARENT.sys:base.Read")));
    proxyFactory.setTargetSource(new SingletonTargetSource(o));
    Object proxy = proxyFactory.getProxy();

    permissionService.setPermission(new SimplePermissionEntry(rootNodeRef, getPermission(PermissionService.READ), "andy", AccessStatus.ALLOWED));

    Object answer = method.invoke(proxy, new Object[] { nodeService.getPrimaryParent(rootNodeRef) });
    assertEquals(answer, nodeService.getPrimaryParent(rootNodeRef));

    answer = method.invoke(proxy, new Object[] { nodeService.getPrimaryParent(systemNodeRef) });
    assertEquals(answer, nodeService.getPrimaryParent(systemNodeRef));
}
 
Example #8
Source File: CommentsApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * REPO-828 (MNT-16401)
 * @throws Exception
 */
public void testDeleteCommentPostActivity() throws Exception
{
    permissionService.setPermission(sitePage, USER_TWO, PermissionService.ALL_PERMISSIONS, true);
    postLookup.execute();
    feedGenerator.execute();
    int activityNumStart = activityService.getSiteFeedEntries(SITE_SHORT_NAME).size();
    Response response = addComment(sitePage, USER_TWO, 200);
    postLookup.execute();
    feedGenerator.execute();
    int activityNumNext = activityService.getSiteFeedEntries(SITE_SHORT_NAME).size();
    assertEquals("The activity feeds were not generated after adding a comment", activityNumStart + 1, activityNumNext);
    JSONObject jsonResponse = parseResponseJSON(response);
    String nodeRefComment = getOrNull(jsonResponse, JSON_KEY_NODEREF);
    NodeRef commentNodeRef = new NodeRef(nodeRefComment);
    deleteComment(commentNodeRef, sitePage, USER_TWO, 200);
    activityNumStart = activityNumNext;
    postLookup.execute();
    feedGenerator.execute();
    activityNumNext = activityService.getSiteFeedEntries(SITE_SHORT_NAME).size();
    assertEquals("The activity feeds were not generated after deleting a comment", activityNumStart + 1, activityNumNext);
}
 
Example #9
Source File: RenditionService2IntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testAccessWithNoPermissions() 
{
    String ownerUserName = createRandomUser();
    NodeRef sourceNodeRef = createSource(ownerUserName, "quick.jpg");
    render(ownerUserName, sourceNodeRef, DOC_LIB);
    String noPermissionsUser = createRandomUser();
    transactionService.getRetryingTransactionHelper().doInTransaction(() ->
    {
        permissionService.setPermission(sourceNodeRef, noPermissionsUser, PermissionService.ALL_PERMISSIONS, false);
        return null;
    });
    try
    {
        waitForRendition(noPermissionsUser, sourceNodeRef, DOC_LIB, true);
        fail("The rendition should not be visible for user with no permissions");
    }
    catch (AccessDeniedException ade)
    {
        // expected
    }
}
 
Example #10
Source File: NodeBrowserPost.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Gets the current node permissions
 * 
 * @return the permissions
 */
public List<Permission> getPermissions(NodeRef nodeRef)
{
    List<Permission> permissions = null;
    AccessStatus readPermissions = this.getPermissionService().hasPermission(nodeRef, PermissionService.READ_PERMISSIONS);
    if (readPermissions.equals(AccessStatus.ALLOWED))
    {
        List<Permission> nodePermissions = new ArrayList<Permission>();
        for (Iterator<AccessPermission> iterator = getPermissionService().getAllSetPermissions(nodeRef).iterator(); iterator
                .hasNext();)
        {
            AccessPermission ap = iterator.next();
            nodePermissions.add(new Permission(ap.getPermission(), ap.getAuthority(), ap.getAccessStatus().toString()));
        }
        permissions = nodePermissions;
    }
    else
    {
        List<Permission> noReadPermissions = new ArrayList<Permission>(1);
        noReadPermissions.add(new NoReadPermissionGranted());
        permissions = noReadPermissions;
    }
    return permissions;
}
 
Example #11
Source File: RenditionService2IntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testRenderByReader() 
{
    String ownerUserName = createRandomUser();
    NodeRef sourceNodeRef = createSource(ownerUserName, "quick.jpg");
    String otherUserName = createRandomUser();
    transactionService.getRetryingTransactionHelper().doInTransaction(() ->
    {
        permissionService.setPermission(sourceNodeRef, otherUserName, PermissionService.READ, true);
        return null;
    });
    render(otherUserName, sourceNodeRef, DOC_LIB);
    NodeRef renditionNodeRef = waitForRendition(ownerUserName, sourceNodeRef, DOC_LIB, true);
    assertNotNull("The rendition is not visible for owner of source node", renditionNodeRef);
    renditionNodeRef = waitForRendition(otherUserName, sourceNodeRef, DOC_LIB, true);
    assertNotNull("The rendition is not visible for owner of rendition node", renditionNodeRef);
    assertEquals("The creator of the rendition is not correct",
            ownerUserName, nodeService.getProperty(sourceNodeRef, ContentModel.PROP_CREATOR));
}
 
Example #12
Source File: AbstractReadPermissionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void build1000NodesReadDenied(final String authority)
{
	runAs("admin");

	RetryingTransactionCallback<Void> cb = new RetryingTransactionCallback<Void>()
	{
		public Void execute() throws Throwable
		{
			String name = "simple" + System.currentTimeMillis();

			NodeRef folder = fileFolderService.create(rootNodeRef, name, ContentModel.TYPE_FOLDER).getNodeRef();

			NodeRef folder_1001 = fileFolderService.create(folder, name + "-1001", ContentModel.TYPE_FOLDER).getNodeRef();
			permissionService.setPermission(folder_1001, authority, PermissionService.READ, true);
			permissionService.setInheritParentPermissions(folder_1001, false);
			for(int j = 0; j < 1000; j++)
			{
				NodeRef file = fileFolderService.create(folder_1001, name + "-1001-"+j, ContentModel.TYPE_CONTENT).getNodeRef();
				permissionService.setInheritParentPermissions(file, false);
				permissionService.setPermission(file, authority, PermissionService.READ, false);
			}

			return null;
		}
	};
	retryingTransactionHelper.doInTransaction(cb, false, false);
}
 
Example #13
Source File: ImapServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testSetFlags() throws Exception
{
    NavigableMap<Long, FileInfo> fis = imapService.getFolderStatus(authenticationService.getCurrentUserName(), testImapFolderNodeRef, ImapViewMode.ARCHIVE).search;
    if (fis != null && fis.size() > 0)
    {
        FileInfo messageFileInfo = fis.firstEntry().getValue();
        try
        {
            setFlags(messageFileInfo);
            fail("Can't set flags");
        }
        catch (Exception e)
        {
            if (e instanceof AccessDeniedException)
            {
                // expected
            }
            else
            {
                throw e;
            }
        }
        
        reauthenticate(USER_NAME, USER_PASSWORD);
        
        permissionService.setPermission(testImapFolderNodeRef, anotherUserName, PermissionService.WRITE, true);
        
        reauthenticate(anotherUserName, anotherUserName);
        
        setFlags(messageFileInfo);
    }
}
 
Example #14
Source File: CommentsApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * MNT-9771
 */
public void testCommentDoesNotChangeModifier() throws Exception
{
    permissionService.setPermission(nodeRef, USER2, PermissionService.ALL_PERMISSIONS, true);
    String modifierBefore = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIER);
    addComment(nodeRef, USER2, 200);
    String modifierAfter = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIER);
    assertEquals(modifierBefore, modifierAfter);
}
 
Example #15
Source File: AuthorityServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * {@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 #16
Source File: PermissionServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
AclTest(PermissionReference required, QName typeQName, Set<QName> aspectQNames)
{
    this.required = required;
    this.typeQName = typeQName;
    this.aspectQNames = aspectQNames;

    // Set the required node permissions
    if (required.equals(getPermissionReference(ALL_PERMISSIONS)))
    {
        nodeRequirements = modelDAO.getRequiredPermissions(getPermissionReference(PermissionService.FULL_CONTROL), typeQName, aspectQNames, RequiredPermission.On.NODE);
    }
    else
    {
        nodeRequirements = modelDAO.getRequiredPermissions(required, typeQName, aspectQNames, RequiredPermission.On.NODE);
    }

    if (modelDAO.getRequiredPermissions(required, typeQName, aspectQNames, RequiredPermission.On.PARENT).size() > 0)
    {
        throw new IllegalStateException("Parent permissions can not be checked for an acl");
    }

    if (modelDAO.getRequiredPermissions(required, typeQName, aspectQNames, RequiredPermission.On.CHILDREN).size() > 0)
    {
        throw new IllegalStateException("Child permissions can not be checked for an acl");
    }

    // Find all the permissions that grant the allowed permission
    // All permissions are treated specially.
    granters = new LinkedHashSet<PermissionReference>(128, 1.0f);
    granters.addAll(modelDAO.getGrantingPermissions(required));
    granters.add(getAllPermissionReference());
    granters.add(OLD_ALL_PERMISSIONS_REFERENCE);
}
 
Example #17
Source File: PermissionServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
UnconditionalAclTest(PermissionReference required)
{
    this.required = required;

    // Set the required node permissions
    if (required.equals(getPermissionReference(ALL_PERMISSIONS)))
    {
        nodeRequirements = modelDAO.getUnconditionalRequiredPermissions(getPermissionReference(PermissionService.FULL_CONTROL), RequiredPermission.On.NODE);
    }
    else
    {
        nodeRequirements = modelDAO.getUnconditionalRequiredPermissions(required, RequiredPermission.On.NODE);
    }

    if (modelDAO.getUnconditionalRequiredPermissions(required, RequiredPermission.On.PARENT).size() > 0)
    {
        throw new IllegalStateException("Parent permissions can not be checked for an acl");
    }

    if (modelDAO.getUnconditionalRequiredPermissions(required,  RequiredPermission.On.CHILDREN).size() > 0)
    {
        throw new IllegalStateException("Child permissions can not be checked for an acl");
    }

    // Find all the permissions that grant the allowed permission
    // All permissions are treated specially.
    granters = new LinkedHashSet<PermissionReference>(128, 1.0f);
    granters.addAll(modelDAO.getGrantingPermissions(required));
    granters.add(getAllPermissionReference());
    granters.add(OLD_ALL_PERMISSIONS_REFERENCE);
}
 
Example #18
Source File: ACLEntryVoterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testMultiNodeMethodsArg0() throws Exception
{
    runAs("andy");

    Object o = new ClassWithMethods();
    Method method = o.getClass().getMethod("testManyNodeRef",
            new Class[] { NodeRef.class, NodeRef.class, NodeRef.class, NodeRef.class });

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("ACL_NODE.0.sys:base.Read")));
    proxyFactory.setTargetSource(new SingletonTargetSource(o));
    Object proxy = proxyFactory.getProxy();

    method.invoke(proxy, new Object[] { null, null, null, null });

    try
    {
        method.invoke(proxy, new Object[] { rootNodeRef, null, null, null });
        assertNotNull(null);
    }
    catch (InvocationTargetException e)
    {

    }

    permissionService.setPermission(new SimplePermissionEntry(rootNodeRef, getPermission(PermissionService.READ),
            "andy", AccessStatus.ALLOWED));
    method.invoke(proxy, new Object[] { rootNodeRef, null, null, null });
}
 
Example #19
Source File: ACLEntryAfterInvocationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testBasicAllowNodeParent() throws Exception
{
    runAs("andy");

    Object o = new ClassWithMethods();
    Method method = o.getClass().getMethod("echoNodeRef", new Class[] { NodeRef.class });

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("AFTER_ACL_PARENT.sys:base.Read")));
    proxyFactory.setTargetSource(new SingletonTargetSource(o));
    Object proxy = proxyFactory.getProxy();

    Object answer = method.invoke(proxy, new Object[] { rootNodeRef });
    assertEquals(answer, rootNodeRef);

    try
    {
        answer = method.invoke(proxy, new Object[] { systemNodeRef });
        assertNotNull(answer);
    }
    catch (InvocationTargetException e)
    {

    }

    permissionService.setPermission(new SimplePermissionEntry(rootNodeRef, getPermission(PermissionService.READ), "andy", AccessStatus.ALLOWED));

    answer = method.invoke(proxy, new Object[] { systemNodeRef });
    assertEquals(answer, systemNodeRef);
}
 
Example #20
Source File: CanCheckOutActionEvaluator.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Construct
 */
protected CanCheckOutActionEvaluator(ServiceRegistry serviceRegistry)
{
    super(serviceRegistry, Action.CAN_CHECK_OUT);
    permissionEvaluator = new PermissionActionEvaluator(
            serviceRegistry,
            Action.CAN_CHECK_OUT,
            PermissionService.CHECK_OUT);
    lockService = serviceRegistry.getLockService();
}
 
Example #21
Source File: RuleServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testRuleServicePermissionsCoordinator()
{
    this.authenticationService.createAuthentication("coordUser", "password".toCharArray());
    this.permissionService.setPermission(this.nodeRef, "coordUser", PermissionService.COORDINATOR, true);
    this.permissionService.setInheritParentPermissions(this.nodeRef, true);
    
	this.authenticationService.authenticate(AuthenticationUtil.getAdminUserName(), "admin".toCharArray());    	
    Rule rule2 = createTestRule();
    this.ruleService.saveRule(this.nodeRef, rule2);        
    this.authenticationService.clearCurrentSecurityContext();
}
 
Example #22
Source File: LockOwnerDynamicAuthorityTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * MNT-9502
 */
public void testPermissionOfLockedNodeWithWorkingcopyAspect()
{
    permissionService.setPermission(rootNodeRef, "andy", PermissionService.ALL_PERMISSIONS, true);
    permissionService.setPermission(rootNodeRef, "lemur", PermissionService.CHECK_OUT, true);
    permissionService.setPermission(rootNodeRef, "lemur", PermissionService.WRITE, true);
    permissionService.setPermission(rootNodeRef, "lemur", PermissionService.READ, true);
    permissionService.setPermission(rootNodeRef, "frog", PermissionService.CHECK_OUT, true);
    permissionService.setPermission(rootNodeRef, "frog", PermissionService.WRITE, true);
    permissionService.setPermission(rootNodeRef, "frog", PermissionService.READ, true);
    authenticationService.authenticate("andy", "andy".toCharArray());
    NodeRef testNode = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_PERSON,
            ContentModel.TYPE_CMOBJECT, null).getChildRef();
    nodeService.addAspect(testNode, ContentModel.ASPECT_WORKING_COPY, null);
    lockService.lock(testNode, LockType.READ_ONLY_LOCK);
   
    assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(testNode, PermissionService.CHECK_IN));
    assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(testNode, PermissionService.CANCEL_CHECK_OUT));
    
    authenticationService.authenticate("lemur", "lemur".toCharArray());
    
    assertEquals(AccessStatus.DENIED, permissionService.hasPermission(testNode, PermissionService.CHECK_IN));
    assertEquals(AccessStatus.DENIED, permissionService.hasPermission(testNode, PermissionService.CANCEL_CHECK_OUT));
    
    authenticationService.authenticate("andy", "andy".toCharArray());
    lockService.unlock(testNode);
    authenticationService.authenticate("lemur", "lemur".toCharArray());
    lockService.lock(testNode, LockType.READ_ONLY_LOCK);
    
    assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(testNode, PermissionService.CHECK_IN));
    assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(testNode, PermissionService.CANCEL_CHECK_OUT));
    
    
    authenticationService.authenticate("frog", "frog".toCharArray());
    
    assertEquals(AccessStatus.DENIED, permissionService.hasPermission(testNode, PermissionService.CHECK_IN));
    assertEquals(AccessStatus.DENIED, permissionService.hasPermission(testNode, PermissionService.CANCEL_CHECK_OUT));
    
}
 
Example #23
Source File: AbstractReadPermissionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void buildNodes(final String user, final String permission, final int n, final boolean inherit)
{
    RetryingTransactionCallback<Void> cb = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            String namePrefix = "simple" + System.currentTimeMillis();

            NodeRef folder = fileFolderService.create(rootNodeRef, namePrefix, ContentModel.TYPE_FOLDER).getNodeRef();

            NodeRef folder_n = fileFolderService.create(folder, namePrefix + "-n", ContentModel.TYPE_FOLDER).getNodeRef();
            permissionService.setInheritParentPermissions(folder_n, false);
            permissionService.setPermission(folder_n, user, PermissionService.READ, true);
            for(int j = 0; j < n; j++)
            {
                NodeRef file = fileFolderService.create(folder_n, namePrefix + "-n-"+j, ContentModel.TYPE_CONTENT).getNodeRef();
                if(!inherit)
                {
                    permissionService.setInheritParentPermissions(file, false);
                    if(permission != null)
                    {
                        permissionService.setPermission(file, user, permission, true);
                    }
                }
            }

            return null;
        }
    };
    retryingTransactionHelper.doInTransaction(cb, false, false);
}
 
Example #24
Source File: SiteServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @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 #25
Source File: VirtualPermissionServiceExtensionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testReadonlyNodeHasPermission() throws Exception
{

    // virtual permission should override actual permissions
    NodeRef aVFTestTemplate2 = createVirtualizedFolder(testRootFolder.getNodeRef(),
                                                       "aVFTestTemplate2",
                                                       TEST_TEMPLATE_2_JSON_SYS_PATH);
    NodeRef vf2Node2 = nodeService.getChildByName(aVFTestTemplate2,
                                                  ContentModel.ASSOC_CONTAINS,
                                                  "Node2");

    final String[] deniedReadOnly = new String[] { PermissionService.UNLOCK, PermissionService.CANCEL_CHECK_OUT,
                PermissionService.CHANGE_PERMISSIONS, PermissionService.CREATE_CHILDREN, PermissionService.DELETE,
                PermissionService.WRITE, PermissionService.DELETE_NODE, PermissionService.WRITE_PROPERTIES,
                PermissionService.WRITE_CONTENT, PermissionService.CREATE_ASSOCIATIONS };

    StringBuilder nonDeniedTrace = new StringBuilder();
    for (int i = 0; i < deniedReadOnly.length; i++)
    {
        AccessStatus accessStatus = hasPermissionAs(vf2Node2,
                                                    deniedReadOnly[i],
                                                    user1);
        if (!AccessStatus.DENIED.equals(accessStatus))
        {
            if (nonDeniedTrace.length() > 0)
            {
                nonDeniedTrace.append(",");
            }
            nonDeniedTrace.append(deniedReadOnly[i]);
        }
    }

    assertTrue("Non-denied permissions on RO virtual nodes : " + nonDeniedTrace,
               nonDeniedTrace.length() == 0);
}
 
Example #26
Source File: FixedAclUpdaterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext();
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    txnHelper = serviceRegistry.getTransactionService().getRetryingTransactionHelper();
    fileFolderService = serviceRegistry.getFileFolderService();
    repository = (Repository) ctx.getBean("repositoryHelper");
    fixedAclUpdater = (FixedAclUpdater) ctx.getBean("fixedAclUpdater");
    permissionsDaoComponent = (PermissionsDaoComponent) ctx.getBean("admPermissionsDaoComponent");
    permissionService = (PermissionService) ctx.getBean("permissionService");
    nodeDAO = (NodeDAO) ctx.getBean("nodeDAO");

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());

    NodeRef home = repository.getCompanyHome();
    // create a folder hierarchy for which will change permission inheritance
    int[] filesPerLevel = { 5, 5, 10 };
    RetryingTransactionCallback<NodeRef> cb1 = createFolderHierchyCallback(home, fileFolderService, "rootFolderAsyncCall",
            filesPerLevel);
    folderAsyncCallNodeRef = txnHelper.doInTransaction(cb1);

    RetryingTransactionCallback<NodeRef> cb2 = createFolderHierchyCallback(home, fileFolderService, "rootFolderSyncCall",
            filesPerLevel);
    folderSyncCallNodeRef = txnHelper.doInTransaction(cb2);

    // change setFixedAclMaxTransactionTime to lower value so setInheritParentPermissions on created folder
    // hierarchy require async call
    setFixedAclMaxTransactionTime(permissionsDaoComponent, home, 50);

}
 
Example #27
Source File: ArchiveAndRestoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * <a href="https://issues.alfresco.com/jira/browse/MNT-2777">MNT-2777</a>
 */
public void testALF17554ArchiveAndRestoreCheckPermission() throws Exception
{
    permissionService.setInheritParentPermissions(a, false);
    // Set the permission for the node for user USER_C
    AuthenticationUtil.setFullyAuthenticatedUser(USER_C);
    assertTrue(
            "The user should not have the permission set on the node yet.",
            permissionService.hasPermission(a, PermissionService.COORDINATOR) == AccessStatus.DENIED);
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    permissionService.setPermission(a, USER_C, PermissionService.COORDINATOR, true);
    assertTrue(
            "The user should have the permission set on the node.",
            permissionService.hasPermission(a, PermissionService.COORDINATOR) == AccessStatus.ALLOWED);
    commitAndBeginNewTransaction();
    nodeService.deleteNode(a);
    verifyNodeExistence(a, false);
    nodeService.restoreNode(a_, null, null, null);
    // Check the permission
    AuthenticationUtil.setFullyAuthenticatedUser(USER_C);
    assertTrue(
            "The user should have the same permission after restoring the node.",
            permissionService.hasPermission(a, PermissionService.COORDINATOR) == AccessStatus.ALLOWED);
    assertFalse(
            "The node should have InheritParentPermissions set to false.",
            permissionService.getInheritParentPermissions(a));
}
 
Example #28
Source File: RuleServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
  public void before() throws Exception
  {
      super.before();
      this.permissionService = (PermissionService)this.applicationContext.getBean("permissionService");
this.authenticationService = (MutableAuthenticationService)this.applicationContext.getBean("authenticationService");
      this.searchService = (SearchService) applicationContext.getBean("SearchService");
      this.namespaceService = (NamespaceService) applicationContext.getBean("NamespaceService");
      this.fileFolderService = (FileFolderService) applicationContext.getBean("FileFolderService");
  }
 
Example #29
Source File: VirtualStoreImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Set<AccessPermission> getAllSetPermissions(Reference reference)
{
    return reference.execute(new GetAllSetPermissionsMethod(this,
                                                            userPermissions,
                                                            PermissionService.ALL_AUTHORITIES));
}
 
Example #30
Source File: CommentServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean canEditPermission(NodeRef commentNodeRef)
{
    String creator = (String)nodeService.getProperty(commentNodeRef, ContentModel.PROP_CREATOR);
    Serializable owner = nodeService.getProperty(commentNodeRef, ContentModel.PROP_OWNER);
    String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();

    boolean isSiteManager = permissionService.hasPermission(commentNodeRef, SiteModel.SITE_MANAGER) == (AccessStatus.ALLOWED);
    boolean isCoordinator = permissionService.hasPermission(commentNodeRef, PermissionService.COORDINATOR) == (AccessStatus.ALLOWED);
    return (isSiteManager || isCoordinator || currentUser.equals(creator) || currentUser.equals(owner));
}