Search in sources :

Example 81 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class AccessControlTest method test06GrantReadPermission.

@Test
public void test06GrantReadPermission() {
    // remove auto-generated resource access objects
    clearResourceAccess();
    try {
        List<Principal> users = createTestNodes(Principal.class, 2);
        Principal user1 = (Principal) users.get(0);
        Principal user2 = (Principal) users.get(1);
        Result result = null;
        // Let user 1 create a node
        Class type = TestOne.class;
        final TestOne t1 = createTestNode(TestOne.class, user1);
        try (final Tx tx = app.tx()) {
            // Grant read permission to user 2
            t1.grant(Permission.read, user2);
            tx.success();
        }
        // Let user 2 search
        SecurityContext user2Context = SecurityContext.getInstance(user2, AccessMode.Backend);
        try (final Tx tx = app.tx()) {
            result = StructrApp.getInstance(user2Context).nodeQuery(type).getResult();
            assertEquals(1, result.size());
            assertEquals(t1.getUuid(), result.get(0).getUuid());
        }
        try (final Tx tx = app.tx()) {
            // Revoke permission again
            t1.revoke(Permission.read, user2);
            tx.success();
        }
        try (final Tx tx = app.tx()) {
            result = StructrApp.getInstance(user2Context).nodeQuery(type).getResult();
            assertTrue(result.isEmpty());
        }
    } catch (FrameworkException ex) {
        logger.warn("", ex);
        fail("Unexpected exception");
    }
}
Also used : Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) TestOne(org.structr.core.entity.TestOne) Principal(org.structr.core.entity.Principal) Result(org.structr.core.Result) Test(org.junit.Test)

Example 82 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class BasicTest method testRelationshipsOnNodeCreation.

@Test
public void testRelationshipsOnNodeCreation() {
    Principal user = null;
    TestOne test = null;
    // create user
    try (final Tx tx = app.tx()) {
        user = app.create(Principal.class, "tester");
        tx.success();
    } catch (FrameworkException fex) {
        logger.warn("", fex);
        fail("Unexpected exception.");
    }
    final SecurityContext ctx = SecurityContext.getInstance(user, AccessMode.Backend);
    final App app = StructrApp.getInstance(ctx);
    // create object with user context
    try (final Tx tx = app.tx()) {
        test = app.create(TestOne.class);
        tx.success();
    } catch (FrameworkException fex) {
        logger.warn("", fex);
        fail("Unexpected exception.");
    }
    // query for relationships
    try (final Tx tx = app.tx()) {
        final List<? extends RelationshipInterface> rels1 = app.relationshipQuery().and(AbstractRelationship.sourceId, user.getUuid()).getAsList();
        final List<Class> classes1 = rels1.stream().map(r -> r.getClass()).collect(Collectors.toList());
        assertEquals("Invalid number of relationships after object creation", 2, rels1.size());
        assertTrue("Invalid relationship type after object creation", classes1.contains(Security.class));
        assertTrue("Invalid relationship type after object creation", classes1.contains(PrincipalOwnsNode.class));
        final List<? extends RelationshipInterface> rels2 = app.relationshipQuery().and(AbstractRelationship.targetId, test.getUuid()).getAsList();
        final List<Class> classes2 = rels2.stream().map(r -> r.getClass()).collect(Collectors.toList());
        assertEquals("Invalid number of relationships after object creation", 2, rels2.size());
        assertTrue("Invalid relationship type after object creation", classes2.contains(Security.class));
        assertTrue("Invalid relationship type after object creation", classes2.contains(PrincipalOwnsNode.class));
        final List<? extends RelationshipInterface> rels3 = Iterables.toList(test.getIncomingRelationships());
        final List<Class> classes3 = rels3.stream().map(r -> r.getClass()).collect(Collectors.toList());
        assertEquals("Invalid number of relationships after object creation", 2, rels3.size());
        assertTrue("Invalid relationship type after object creation", classes3.contains(Security.class));
        assertTrue("Invalid relationship type after object creation", classes3.contains(PrincipalOwnsNode.class));
        final Security sec = app.relationshipQuery(Security.class).getFirst();
        assertNotNull("Relationship caching on node creation is broken", sec);
        final PrincipalOwnsNode owns = app.relationshipQuery(PrincipalOwnsNode.class).getFirst();
        assertNotNull("Relationship caching on node creation is broken", owns);
        tx.success();
    } catch (FrameworkException fex) {
        logger.warn("", fex);
        fail("Unexpected exception.");
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) LoggerFactory(org.slf4j.LoggerFactory) RelationshipType(org.structr.api.graph.RelationshipType) TestTen(org.structr.core.entity.TestTen) StringUtils(org.apache.commons.lang3.StringUtils) GenericNode(org.structr.core.entity.GenericNode) FrameworkException(org.structr.common.error.FrameworkException) App(org.structr.core.app.App) StringProperty(org.structr.core.property.StringProperty) Assert.fail(org.junit.Assert.fail) Location(org.structr.core.entity.Location) ResourceAccess(org.structr.core.entity.ResourceAccess) OneThreeOneToOne(org.structr.core.entity.OneThreeOneToOne) NodeHasLocation(org.structr.core.entity.relationship.NodeHasLocation) AbstractRelationship(org.structr.core.entity.AbstractRelationship) SixOneOneToOne(org.structr.core.entity.SixOneOneToOne) NotInTransactionException(org.structr.api.NotInTransactionException) GraphObject(org.structr.core.GraphObject) OneTwoOneToOne(org.structr.core.entity.OneTwoOneToOne) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) SixOneManyToMany(org.structr.core.entity.SixOneManyToMany) List(java.util.List) DynamicResourceAccess(org.structr.core.entity.DynamicResourceAccess) StructrApp(org.structr.core.app.StructrApp) TestOne(org.structr.core.entity.TestOne) Security(org.structr.core.entity.Security) TestSix(org.structr.core.entity.TestSix) PropertyMap(org.structr.core.property.PropertyMap) NotFoundException(org.structr.api.NotFoundException) NodeAttribute(org.structr.core.graph.NodeAttribute) PropertyKey(org.structr.core.property.PropertyKey) TestNine(org.structr.core.entity.TestNine) Result(org.structr.core.Result) LinkedList(java.util.LinkedList) AbstractNode(org.structr.core.entity.AbstractNode) TestTwo(org.structr.core.entity.TestTwo) NodeInterface(org.structr.core.graph.NodeInterface) SixThreeOneToMany(org.structr.core.entity.SixThreeOneToMany) Logger(org.slf4j.Logger) Iterables(org.structr.api.util.Iterables) GenericRelationship(org.structr.core.entity.GenericRelationship) Assert.assertNotNull(org.junit.Assert.assertNotNull) Group(org.structr.core.entity.Group) Tx(org.structr.core.graph.Tx) Principal(org.structr.core.entity.Principal) Relation(org.structr.core.entity.Relation) PrincipalOwnsNode(org.structr.core.entity.relationship.PrincipalOwnsNode) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) TestSeven(org.structr.core.entity.TestSeven) TestThree(org.structr.core.entity.TestThree) TestFour(org.structr.core.entity.TestFour) NodeServiceCommand(org.structr.core.graph.NodeServiceCommand) Localization(org.structr.core.entity.Localization) SchemaRelationshipNode(org.structr.core.entity.SchemaRelationshipNode) RelationshipInterface(org.structr.core.graph.RelationshipInterface) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) SchemaNode(org.structr.core.entity.SchemaNode) PrincipalOwnsNode(org.structr.core.entity.relationship.PrincipalOwnsNode) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) TestOne(org.structr.core.entity.TestOne) Security(org.structr.core.entity.Security) Principal(org.structr.core.entity.Principal) Test(org.junit.Test)

Example 83 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class CustomPermissionQueriesTest method test02SimplePermissionResolutionWrite.

@Test
public void test02SimplePermissionResolutionWrite() {
    final Class<Principal> principalType = StructrApp.getConfiguration().getNodeEntityClass("Principal");
    Principal user1 = null;
    Class type1 = null;
    try (final Tx tx = app.tx()) {
        // create a test user
        user1 = app.create(principalType, "user1");
        final SchemaNode t1 = app.create(SchemaNode.class, "Type1");
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
        fail("Unexpected exception");
    }
    Assert.assertNotNull("User should have been created", user1);
    try (final Tx tx = app.tx()) {
        type1 = StructrApp.getConfiguration().getNodeEntityClass("Type1");
        Assert.assertNotNull("Node type Type1 should exist.", type1);
        final NodeInterface instance1 = app.create(type1, "instance1OfType1");
        Assert.assertNotNull("Instance of type Type1 should exist", instance1);
        // make instance1 visible to user1
        instance1.grant(Permission.read, user1);
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
        fail("Unexpected exception");
    }
    // check access for user1 on instance1
    final App userApp = StructrApp.getInstance(SecurityContext.getInstance(user1, AccessMode.Backend));
    try (final Tx tx = userApp.tx()) {
        userApp.nodeQuery(type1).getFirst().setProperty(GraphObject.visibleToPublicUsers, true);
        tx.success();
    } catch (FrameworkException fex) {
        Assert.assertEquals("User1 should NOT be able to modify instance of type Type1", 403, fex.getStatus());
    }
    // set custom permission query on user
    try (final Tx tx = userApp.tx()) {
        // query returns always true if user exists
        user1.setProperty(StructrApp.key(Principal.class, "customPermissionQueryWrite"), "MATCH (p:Principal {id: {principalUuid}}) RETURN p IS NOT NULL");
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
        fail("Unexpected exception");
    }
    // check access for user1 on instance1
    try (final Tx tx = userApp.tx()) {
        userApp.nodeQuery(type1).getFirst().setProperty(GraphObject.visibleToPublicUsers, true);
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
        fail("Unexpected exception");
    }
    // set custom permission query on user
    try (final Tx tx = userApp.tx()) {
        // query returns always false if user exists
        user1.setProperty(StructrApp.key(Principal.class, "customPermissionQueryRead"), "MATCH (p:Principal {id: {principalUuid}}) RETURN p IS NULL");
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
        fail("Unexpected exception");
    }
    // check access for user1 on instance1
    try (final Tx tx = userApp.tx()) {
        userApp.nodeQuery(type1).getFirst().setProperty(GraphObject.visibleToPublicUsers, true);
        tx.success();
    } catch (FrameworkException fex) {
        Assert.assertEquals("User1 should NOT be able to modify instance of type Type1", 403, fex.getStatus());
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) SchemaNode(org.structr.core.entity.SchemaNode) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Principal(org.structr.core.entity.Principal) NodeInterface(org.structr.core.graph.NodeInterface) Test(org.junit.Test)

Example 84 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class RestAuthenticator method doLogout.

@Override
public void doLogout(final HttpServletRequest request) {
    try {
        final Principal user = getUser(request, false);
        if (user != null) {
            AuthHelper.doLogout(request, user);
        }
        final HttpSession session = request.getSession(false);
        if (session != null) {
            SessionHelper.invalidateSession(session);
        }
    } catch (IllegalStateException | FrameworkException ex) {
        logger.warn("Error while logging out user", ex);
    }
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) HttpSession(javax.servlet.http.HttpSession) Principal(org.structr.core.entity.Principal)

Example 85 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class RestAuthenticator method checkResourceAccess.

@Override
public void checkResourceAccess(final SecurityContext securityContext, final HttpServletRequest request, final String rawResourceSignature, final String propertyView) throws FrameworkException {
    final ResourceAccess resourceAccess = ResourceAccess.findGrant(securityContext, rawResourceSignature);
    final Method method = methods.get(request.getMethod());
    final Principal user = getUser(request, true);
    final boolean validUser = (user != null);
    // super user is always authenticated
    if (validUser && (user instanceof SuperUser || user.isAdmin())) {
        return;
    }
    // no grants => no access rights
    if (resourceAccess == null) {
        logger.info("No resource access grant found for signature {}.", rawResourceSignature);
        throw new UnauthorizedException("Forbidden");
    } else {
        switch(method) {
            case GET:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_GET)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_GET)) {
                    return;
                }
                break;
            case PUT:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_PUT)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_PUT)) {
                    return;
                }
                break;
            case POST:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_POST)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_POST)) {
                    return;
                }
                break;
            case DELETE:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_DELETE)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_DELETE)) {
                    return;
                }
                break;
            case OPTIONS:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_OPTIONS)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_OPTIONS)) {
                    return;
                }
                break;
            case HEAD:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_HEAD)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_HEAD)) {
                    return;
                }
                break;
        }
    }
    logger.info("Resource access grant found for signature {}, but method {} not allowed for {}.", new Object[] { rawResourceSignature, method, validUser ? "authenticated users" : "public users" });
    throw new UnauthorizedException("Forbidden");
}
Also used : ResourceAccess(org.structr.core.entity.ResourceAccess) UnauthorizedException(org.structr.core.auth.exception.UnauthorizedException) SuperUser(org.structr.core.entity.SuperUser) Principal(org.structr.core.entity.Principal)

Aggregations

Principal (org.structr.core.entity.Principal)112 FrameworkException (org.structr.common.error.FrameworkException)68 Tx (org.structr.core.graph.Tx)65 Test (org.junit.Test)41 App (org.structr.core.app.App)31 StructrApp (org.structr.core.app.StructrApp)31 TestOne (org.structr.core.entity.TestOne)16 Group (org.structr.core.entity.Group)14 NodeAttribute (org.structr.core.graph.NodeAttribute)13 PropertyMap (org.structr.core.property.PropertyMap)13 SecurityContext (org.structr.common.SecurityContext)10 LinkedList (java.util.LinkedList)9 Result (org.structr.core.Result)8 User (org.structr.web.entity.User)8 AbstractNode (org.structr.core.entity.AbstractNode)7 SuperUser (org.structr.core.entity.SuperUser)7 StructrUiTest (org.structr.web.StructrUiTest)7 Page (org.structr.web.entity.dom.Page)7 IOException (java.io.IOException)6 List (java.util.List)6