Exemplo n.º 1
0
def restore_node(handle_id, node_name, node_type_name, node_meta_type,
                 fallback_user):
    """
    Tries to get a existing node handle from the SQL database before creating
    a new handle with an old handle id. If an existing node if found do not overwrite it.

    When we are setting the handle_id explicitly we need to run django-admin.py
    sqlsequencereset noclook and paste that SQL statements in to the dbhell.
    """
    node_type = utils.get_node_type(node_type_name)
    defaults = {
        'node_name': node_name,
        'node_type': node_type,
        'node_meta_type': node_meta_type,
        'creator': fallback_user,
        'modifier': fallback_user,
    }
    if NodeHandle.objects.filter(handle_id=handle_id).exists():
        # NodeHandle id already taken, create a new NodeHandle and map old id to new
        node_handle = NodeHandle.objects.create(**defaults)
        created = True
        NODE_HANDLE_ID_MAPPING[handle_id] = node_handle.handle_id
        logger.info('Remapping handle_id {} to {}'.format(
            handle_id, node_handle.handle_id))
    else:
        node_handle, created = NodeHandle.objects.get_or_create(
            handle_id=handle_id, defaults=defaults)
    if not created:
        if node_handle.node_meta_type != node_meta_type:
            node_handle.node_meta_type = node_meta_type
            node_handle.save()
    # rather than calling .save() which will do a db fetch of node_type
    node_handle._create_node(
        node_type.get_label())  # Make sure data is saved in neo4j as well.

    # Create NodeHandleContext
    net_ctx = sriutils.get_network_context()
    NodeHandleContext.objects.get_or_create(nodehandle=node_handle,
                                            context=net_ctx)

    return node_handle
Exemplo n.º 2
0
Arquivo: network.py Projeto: SUNET/ni
    def do_request(cls, request, **kwargs):
        form_class = kwargs.get('form_class')
        nimetaclass = getattr(cls, 'NIMetaClass')
        graphql_type = getattr(nimetaclass, 'graphql_type')
        relations_processors = getattr(nimetaclass, 'relations_processors')
        nimetatype = getattr(graphql_type, 'NIMetaType')
        node_type = getattr(nimetatype, 'ni_type').lower()
        has_error = False

        context = sriutils.get_network_context()

        # check it can write on this context
        authorized = sriutils.authorize_create_resource(request.user, context)

        if not authorized:
            raise GraphQLAuthException()

        # Get needed data from node
        if request.POST:
            # replace relay ids for handle_id in contacts if present
            post_data = request.POST.copy()

            relay_extra_ids = relations_processors.keys()
            for field in relay_extra_ids:
                handle_id = post_data.get(field)

                # check if it's already converted to int version
                try:
                    handle_id = int(handle_id)
                    continue
                except:
                    pass

                if handle_id:
                    try:
                        handle_id = relay.Node.from_global_id(handle_id)[1]
                        post_data.pop(field)
                        post_data.update({field: handle_id})
                    except BinasciiError:
                        pass # the id is already in handle_id format

            form = form_class(post_data)
            form.strict_validation = True

            if form.is_valid():
                data = form.cleaned_data
                if data['relationship_owner'] or data['relationship_location']:
                    meta_type = 'Physical'
                else:
                    meta_type = 'Logical'

                try:
                    nh = helpers.form_to_generic_node_handle(request, form,
                            node_type, meta_type, context)
                except UniqueNodeError:
                    has_error = True
                    return has_error, [ErrorType(field="_", messages=["A {} with that name already exists.".format(node_type)])]

                # Generic node update
                helpers.form_update_node(request.user, nh.handle_id, form)
                nh_reload, host_nh = helpers.get_nh_node(nh.handle_id)

                # add default context
                NodeHandleContext(nodehandle=nh, context=context).save()

                node = nh.get_node()

                # Set relations
                for relation_name, relation_f in relations_processors.items():
                    relation_f(request, form, node, relation_name)

                return has_error, { graphql_type.__name__.lower(): nh }
            else:
                # get the errors and return them
                has_error = True
                errordict = cls.format_error_array(form.errors)
                return has_error, errordict
        else:
            # get the errors and return them
            has_error = True
            errordict = cls.format_error_array(form.errors)
            return has_error, errordict
Exemplo n.º 3
0
    def test_grant_user_permissions(self):
        # only run mutations if we have set this value
        if not hasattr(self, 'test_type'):
            return

        another_user_id = self.another_user.id
        other_user_id = self.other_user.id

        for user in [self.another_user, self.other_user]:
            # first query another_user permissions
            user_id = user.id

            query = """
            {{
              getUserById(ID: {user_id}){{
                id
                username
                user_permissions{{
                  community{{
                    read
                    list
                    write
                    admin
                  }}
                  network{{
                    read
                    list
                    write
                    admin
                  }}
                  contracts{{
                    read
                    list
                    write
                    admin
                  }}
                }}
              }}
            }}
            """.format(user_id=user_id)
            result = schema.execute(query, context=self.context)
            assert not result.errors, pformat(result.errors, indent=1)

            expected = {
                'getUserById': {
                    'id': str(user_id),
                    'user_permissions': {
                        'community': {
                            'admin': False,
                            'list': False,
                            'read': False,
                            'write': False
                        },
                        'contracts': {
                            'admin': False,
                            'list': False,
                            'read': False,
                            'write': False
                        },
                        'network': {
                            'admin': False,
                            'list': False,
                            'read': False,
                            'write': False
                        }
                    },
                    'username': user.username
                }
            }

            # they must be blank as we didn't set anything yet
            self.assert_correct(result, expected)

        # add read, list and write permissions over our module
        query_t = """
        mutation{{
          grant_users_permissions(input:{{
            users_ids:[ {users_ids} ]
            context: "{context_name}"
            read: {read}
            list: {list}
            write: {write}
            {admin}
          }}){{
            results{{
              success
              errors{{
                field
                messages
              }}
    		  user{{
                id
                username
                user_permissions{{
                  network{{
                    read
                    list
                    write
                    admin
                  }}
                }}
              }}
            }}
          }}
        }}
        """

        # check the user permissions query
        net_ctxt = sriutils.get_network_context()
        context_name = net_ctxt.name
        read = str(True).lower()
        list = str(True).lower()
        write = str(True).lower()
        users_ids = ", ".join(['"{}"'.format(x) \
            for x in [other_user_id, another_user_id]])

        query = query_t.format(users_ids=users_ids,
                               context_name=context_name,
                               read=read,
                               list=list,
                               write=write,
                               admin="")

        # test vakt functions before
        for user in [self.other_user, self.another_user]:
            can_read = sriutils.authorize_read_module(user, net_ctxt)
            can_list = sriutils.authorize_list_module(user, net_ctxt)
            can_write = sriutils.authorize_create_resource(user, net_ctxt)

            self.assertFalse(can_read)
            self.assertFalse(can_list)
            self.assertFalse(can_write)

        # run mutation and check response
        result = schema.execute(query, context=self.context)
        assert not result.errors, pformat(result.errors, indent=1)

        expected = OrderedDict([('grant_users_permissions', {
            'results': [{
                'errors': None,
                'success': True,
                'user': {
                    'id': str(other_user_id),
                    'user_permissions': {
                        'network': {
                            'admin': False,
                            'list': True,
                            'read': True,
                            'write': True
                        }
                    },
                    'username': self.other_user.username
                }
            }, {
                'errors': None,
                'success': True,
                'user': {
                    'id': str(another_user_id),
                    'user_permissions': {
                        'network': {
                            'admin': False,
                            'list': True,
                            'read': True,
                            'write': True
                        }
                    },
                    'username': self.another_user.username
                }
            }]
        })])

        self.assert_correct(result, expected)

        # after
        for user in [self.other_user, self.another_user]:
            can_read = sriutils.authorize_read_module(user, net_ctxt)
            can_list = sriutils.authorize_list_module(user, net_ctxt)
            can_write = sriutils.authorize_create_resource(user, net_ctxt)

            self.assertTrue(can_read)
            self.assertTrue(can_list)
            self.assertTrue(can_write)

        # revoke write permission
        write = str(False).lower()

        query = query_t.format(users_ids=users_ids,
                               context_name=context_name,
                               read=read,
                               list=list,
                               write=write,
                               admin="")
        result = schema.execute(query, context=self.context)
        assert not result.errors, pformat(result.errors, indent=1)

        expected = OrderedDict([('grant_users_permissions', {
            'results': [{
                'errors': None,
                'success': True,
                'user': {
                    'id': str(other_user_id),
                    'user_permissions': {
                        'network': {
                            'admin': False,
                            'list': True,
                            'read': True,
                            'write': False
                        }
                    },
                    'username': self.other_user.username
                }
            }, {
                'errors': None,
                'success': True,
                'user': {
                    'id': str(another_user_id),
                    'user_permissions': {
                        'network': {
                            'admin': False,
                            'list': True,
                            'read': True,
                            'write': False
                        }
                    },
                    'username': self.another_user.username
                }
            }]
        })])

        # check the user permissions query
        self.assert_correct(result, expected)

        # test vakt functions
        for user in [self.other_user, self.another_user]:
            can_write = sriutils.authorize_create_resource(user, net_ctxt)
            self.assertFalse(can_write)

        # grand admin rights
        admin = "admin: true"
        query = query_t.format(users_ids=users_ids,
                               context_name=context_name,
                               read=read,
                               list=list,
                               write=write,
                               admin=admin)

        result = schema.execute(query, context=self.context)
        assert not result.errors, pformat(result.errors, indent=1)
        expected = None

        if self.test_type == "admin":
            # if it's not check the error
            expected = OrderedDict([('grant_users_permissions', {
                'results': [{
                    'errors': [{
                        'field':
                        '_',
                        'messages':
                        ['Only superadmins can '
                         'grant admin rights']
                    }],
                    'success':
                    False,
                    'user': {
                        'id': str(other_user_id),
                        'user_permissions': {
                            'network': {
                                'admin': False,
                                'list': True,
                                'read': True,
                                'write': False
                            }
                        },
                        'username': self.other_user.username
                    }
                }, {
                    'errors': [{
                        'field':
                        '_',
                        'messages':
                        ['Only superadmins can '
                         'grant admin rights']
                    }],
                    'success':
                    False,
                    'user': {
                        'id': str(another_user_id),
                        'user_permissions': {
                            'network': {
                                'admin': False,
                                'list': True,
                                'read': True,
                                'write': False
                            }
                        },
                        'username': self.another_user.username
                    }
                }]
            })])
        elif self.test_type == "superadmin":
            # if it's superadmin test it should be possible
            expected = OrderedDict([('grant_users_permissions', {
                'results': [{
                    'errors': None,
                    'success': True,
                    'user': {
                        'id': str(other_user_id),
                        'user_permissions': {
                            'network': {
                                'admin': True,
                                'list': True,
                                'read': True,
                                'write': False
                            }
                        },
                        'username': self.other_user.username
                    }
                }, {
                    'errors': None,
                    'success': True,
                    'user': {
                        'id': str(another_user_id),
                        'user_permissions': {
                            'network': {
                                'admin': True,
                                'list': True,
                                'read': True,
                                'write': False
                            }
                        },
                        'username': self.another_user.username
                    }
                }]
            })])

        self.assert_correct(result, expected)
Exemplo n.º 4
0
 def add_network_context(self, nh):
     net_ctx = sriutils.get_network_context()
     NodeHandleContext(nodehandle=nh, context=net_ctx).save()
Exemplo n.º 5
0
    def setUp(self, group_dict=None):
        super(Neo4jGraphQLGenericTest, self).setUp()

        self.context = TestContext(self.user)

        # get read aa
        self.get_read_authaction  = sriutils.get_read_authaction()
        self.get_write_authaction = sriutils.get_write_authaction()
        self.get_list_authaction  = sriutils.get_list_authaction()
        self.get_admin_authaction  = sriutils.get_admin_authaction()

        # get contexts
        self.network_ctxt = sriutils.get_network_context()
        self.community_ctxt = sriutils.get_community_context()
        self.contracts_ctxt = sriutils.get_contracts_context()

        # add contexts and profiles for network
        iter_contexts = (
            self.community_ctxt,
            self.network_ctxt,
            self.contracts_ctxt,
        )

        for acontext in iter_contexts:
            # create group for read in community context
            context_name = acontext.name.lower()
            group_read = sriutils.get_aaction_context_group(
                self.get_read_authaction, acontext)

            # create group for write in community context
            group_write = sriutils.get_aaction_context_group(
                self.get_write_authaction, acontext)

            # create group for list in community context
            group_list = sriutils.get_aaction_context_group(
                self.get_list_authaction, acontext)

            # create group for admin in community context
            group_admin = sriutils.get_aaction_context_group(
                self.get_admin_authaction, acontext)

            add_read  = False
            add_write = False
            add_list  = False
            add_admin = False

            if group_dict and context_name in group_dict:
                if group_dict[context_name].get('read', False):
                    add_read  = True

                if group_dict[context_name].get('write', False):
                    add_write = True

                if group_dict[context_name].get('list', False):
                    add_list  = True

                if group_dict[context_name].get('admin', False):
                    add_admin  = True

            if not group_dict:
                add_read  = True
                add_write = True
                add_list  = True
                add_admin  = True

            # save and add user to the group
            group_aaction = []

            if add_read:
                group_read.save()
                group_read.user_set.add(self.user)
                group_aaction.append((group_read, self.get_read_authaction))

            if add_write:
                group_write.save()
                group_write.user_set.add(self.user)
                group_aaction.append((group_write, self.get_write_authaction))

            if add_list:
                group_list.save()
                group_list.user_set.add(self.user)
                group_aaction.append((group_list, self.get_list_authaction))

            if add_admin:
                group_admin.save()
                group_admin.user_set.add(self.user)
                group_aaction.append((group_admin, self.get_admin_authaction))

            # add the correct actions fot each group
            for group, aaction in group_aaction:
                GroupContextAuthzAction(
                    group = group,
                    authzprofile = aaction,
                    context = acontext
                ).save()
Exemplo n.º 6
0
    def setUp(self):
        super(SRIVaktUtilsTest, self).setUp()

        # get contexts
        self.network_ctxt = sriutils.get_network_context()
        self.community_ctxt = sriutils.get_community_context()
        self.contracts_ctxt = sriutils.get_contracts_context()

        # get auth actions
        self.get_read_authaction = sriutils.get_read_authaction()
        self.get_write_authaction = sriutils.get_write_authaction()
        self.get_list_authaction = sriutils.get_list_authaction()
        self.get_admin_authaction = sriutils.get_admin_authaction()

        # create some nodes
        self.organization1 = self.create_node('organization1',
                                              'organization',
                                              meta='Logical')
        self.organization2 = self.create_node('organization2',
                                              'organization',
                                              meta='Logical')
        self.contact1 = self.create_node('contact1',
                                         'contact',
                                         meta='Relation')
        self.contact2 = self.create_node('contact2',
                                         'contact',
                                         meta='Relation')

        # add context to resources
        # organization1 belongs to the three modules
        NodeHandleContext(nodehandle=self.organization1,
                          context=self.network_ctxt).save()

        NodeHandleContext(nodehandle=self.organization1,
                          context=self.community_ctxt).save()

        NodeHandleContext(nodehandle=self.organization1,
                          context=self.contracts_ctxt).save()

        # organization2 belongs only to the network module
        NodeHandleContext(nodehandle=self.organization2,
                          context=self.network_ctxt).save()

        # the first contact belongs to the community module
        NodeHandleContext(nodehandle=self.contact1,
                          context=self.community_ctxt).save()

        # the second contact belongs to the contracts module
        NodeHandleContext(nodehandle=self.contact2,
                          context=self.contracts_ctxt).save()

        ### create users and groups and add permissions
        self.user1 = User(
            first_name="Kate",
            last_name="Svensson",
            email="*****@*****.**",
            is_staff=False,
            is_active=True,
            username="******",
        )
        self.user1.save()

        self.user2 = User(
            first_name="Jane",
            last_name="Atkins",
            email="*****@*****.**",
            is_staff=False,
            is_active=True,
            username="******",
        )
        self.user2.save()

        self.user3 = User(
            first_name="Sven",
            last_name="Svensson",
            email="*****@*****.**",
            is_staff=False,
            is_active=True,
            username="******",
        )
        self.user3.save()

        self.user4 = User(
            first_name="Pedro",
            last_name="Zutano",
            email="*****@*****.**",
            is_staff=False,
            is_active=True,
            username="******",
        )
        self.user4.save()

        # create groups
        self.group1 = Group(name="Group can read all contexts")
        self.group2 = Group(name="Group can write community and contracts")
        self.group3 = Group(name="Group can admin community module")
        self.group4 = Group(name="Group can list community and contracts")
        self.group5 = Group(name="Group can read community contracts")

        self.group1.save()
        self.group2.save()
        self.group3.save()
        self.group4.save()
        self.group5.save()

        # add contexts and actions
        # first group
        contexts = [
            self.network_ctxt, self.community_ctxt, self.contracts_ctxt
        ]

        for context in contexts:
            GroupContextAuthzAction(group=self.group1,
                                    authzprofile=self.get_read_authaction,
                                    context=context).save()

        # second and fifth group
        contexts = [self.community_ctxt, self.contracts_ctxt]

        for context in contexts:
            GroupContextAuthzAction(group=self.group2,
                                    authzprofile=self.get_write_authaction,
                                    context=context).save()

        for context in contexts:
            GroupContextAuthzAction(group=self.group5,
                                    authzprofile=self.get_read_authaction,
                                    context=context).save()

        # third group
        GroupContextAuthzAction(group=self.group3,
                                authzprofile=self.get_admin_authaction,
                                context=self.community_ctxt).save()

        for context in contexts:
            GroupContextAuthzAction(group=self.group4,
                                    authzprofile=self.get_list_authaction,
                                    context=context).save()

        # add users to groups
        self.group1.user_set.add(self.user1)
        self.group1.user_set.add(self.user2)
        self.group1.user_set.add(self.user3)

        self.group2.user_set.add(self.user1)
        self.group2.user_set.add(self.user2)

        self.group3.user_set.add(self.user1)

        self.group4.user_set.add(self.user1)
        self.group4.user_set.add(self.user2)
        self.group4.user_set.add(self.user3)

        self.group5.user_set.add(self.user4)