コード例 #1
0
ファイル: query.py プロジェクト: SUNET/ni
    def resolve_checkExistentOrganizationId(self, info, **kwargs):
        ret = False

        if info.context and info.context.user.is_authenticated:
            # well use the community context to check if the user
            # can read the rolegroup list
            community_context = sriutils.get_community_context()
            authorized = sriutils.authorize_list_module(
                info.context.user, community_context)

            if authorized:
                id = kwargs.get('id', None)
                handle_id = None

                if id:
                    _type, handle_id = relay.Node.from_global_id(id)

                organization_id = kwargs.get('organization_id')

                ret = nc.models.OrganizationModel \
                        .check_existent_organization_id(
                            organization_id, handle_id, nc.graphdb.manager)
        else:
            raise GraphQLAuthException()

        return ret
コード例 #2
0
ファイル: query.py プロジェクト: SUNET/ni
    def resolve_getAvailableRoleGroups(self, info, **kwargs):
        ret = []

        if info.context and info.context.user.is_authenticated:
            # well use the community context to check if the user
            # can read the rolegroup list
            community_context = sriutils.get_community_context()
            authorized = sriutils.authorize_list_module(
                info.context.user, community_context)

            if authorized:
                ret = RoleGroupModel.objects.all()
        else:
            #401
            raise GraphQLAuthException()

        return ret
コード例 #3
0
ファイル: community.py プロジェクト: SUNET/ni
    def get_form_kwargs(cls, root, info, **input):
        context = sriutils.get_community_context()

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

        if not authorized:
            raise GraphQLAuthException()

        kwargs = {"data": input}

        id = input.pop("id", None)
        handle_id = relay.Node.from_global_id(id)[1]
        if handle_id:
            instance = cls._meta.model._default_manager.get(pk=handle_id)
            kwargs["instance"] = instance

        return kwargs
コード例 #4
0
ファイル: query.py プロジェクト: SUNET/ni
    def resolve_getRolesFromRoleGroup(self, info, **kwargs):
        ret = []
        name = kwargs.get('name', DEFAULT_ROLEGROUP_NAME)

        if info.context and info.context.user.is_authenticated:
            # well use the community context to check if the user
            # can read the rolegroup list
            community_context = sriutils.get_community_context()
            authorized = sriutils.authorize_list_module(
                info.context.user, community_context)

            if authorized:
                role_group = RoleGroupModel.objects.get(name=name)
                ret = RoleModel.objects.filter(role_group=role_group)
        else:
            #401
            raise GraphQLAuthException()

        return ret
コード例 #5
0
ファイル: community.py プロジェクト: SUNET/ni
    def mutate_and_get_payload(cls, root, info, **input):
        context = sriutils.get_community_context()

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

        if not authorized:
            raise GraphQLAuthException()

        form = cls.get_form(root, info, **input)

        if form.is_valid():
            return cls.perform_mutate(form, info)
        else:
            errors = [
                ErrorType(field=key, messages=value)
                for key, value in form.errors.items()
            ]

            return cls(errors=errors)
コード例 #6
0
ファイル: community.py プロジェクト: SUNET/ni
    def mutate_and_get_payload(cls, root, info, **input):
        id = input.get("id", None)
        handle_id = relay.Node.from_global_id(id)[1]
        success = False

        context = sriutils.get_community_context()

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

        if not authorized:
            raise GraphQLAuthException()

        try:
            role = RoleModel.objects.get(handle_id=handle_id)
            role.delete()
            success = True
        except ObjectDoesNotExist:
            success = False

        return DeleteRole(success=success, id=id)
コード例 #7
0
ファイル: csvimport.py プロジェクト: SUNET/ni
    def fix_community_context(self):
        com_ctx = sriutils.get_community_context()

        organization_type = self.get_nodetype(type='Organization',
                                              slug='organization')
        contact_type = self.get_nodetype(type='Contact', slug='contact')
        email_type = self.get_nodetype(type='Email', slug='email', hidden=True)
        phone_type = self.get_nodetype(type='Phone', slug='phone', hidden=True)
        address_type = self.get_nodetype(type='Address',
                                         slug='address',
                                         hidden=True)

        all_contacts = NodeHandle.objects.filter(node_type=contact_type)
        community_contacts = NodeHandleContext.objects.filter(
            context=com_ctx, nodehandle__in=all_contacts)

        # add ctx to contacts' phones and emails
        for com_contact in community_contacts:
            contact = com_contact.nodehandle
            contact_node = contact.get_node()

            relations = contact_node.get_outgoing_relations()
            relation_keys = list(relations.keys())

            self.add_subentity_to_community(relations, 'Has_phone')
            self.add_subentity_to_community(relations, 'Has_email')

        all_organizations = NodeHandle.objects.filter(
            node_type=organization_type)
        community_organizations = NodeHandleContext.objects.filter(
            context=com_ctx, nodehandle__in=all_organizations)

        for com_organization in community_organizations:
            organization = com_organization.nodehandle
            organizationt_node = organization.get_node()

            relations = organizationt_node.get_outgoing_relations()
            relation_keys = list(relations.keys())

            self.add_subentity_to_community(relations, 'Has_address')
コード例 #8
0
ファイル: query.py プロジェクト: SUNET/ni
    def resolve_roles(self, info, **kwargs):
        qs = RoleModel.objects.none()

        if info.context and info.context.user.is_authenticated:
            context = sriutils.get_community_context()
            authorized = sriutils.authorize_list_module(
                info.context.user, context)

            if authorized:
                filter = kwargs.get('filter')
                order_by = kwargs.get('orderBy')

                qs = RoleModel.objects.all()

                if order_by:
                    if order_by == RoleOrderBy.handle_id_ASC:
                        qs = qs.order_by('handle_id')
                    elif order_by == RoleOrderBy.handle_id_DESC:
                        qs = qs.order_by('-handle_id')
                    elif order_by == RoleOrderBy.name_ASC:
                        qs = qs.order_by('name')
                    elif order_by == RoleOrderBy.name_DESC:
                        qs = qs.order_by('-name')

                if filter:
                    if filter.id:
                        handle_id = relay.Node.from_global_id(filter.id)[1]
                        qs = qs.filter(handle_id=handle_id)

                    if filter.name:
                        qs = qs.filter(name=filter.name)

                return qs
            else:
                #403
                return qs
        else:
            # 401
            raise GraphQLAuthException()
コード例 #9
0
ファイル: csvimport.py プロジェクト: SUNET/ni
 def add_community_context(self, nh):
     com_ctx = sriutils.get_community_context()
     NodeHandleContext.objects.get_or_create(nodehandle=nh,
                                             context=com_ctx)[0]
コード例 #10
0
    def test_fix_community_context(self):
        # call csvimport command (verbose 0) to import test organizations
        call_command(
            self.cmd_name,
            organizations=self.organizations_file,
            verbosity=0,
        )

        # and contacts
        call_command(
            self.cmd_name,
            contacts=self.contacts_file,
            verbosity=0,
        )

        # get types and contexts
        com_ctx = sriutils.get_community_context()

        csvcommand = CSVCommand()
        email_type = csvcommand.get_nodetype(type='Email',
                                             slug='email',
                                             hidden=True)
        phone_type = csvcommand.get_nodetype(type='Phone',
                                             slug='phone',
                                             hidden=True)
        address_type = csvcommand.get_nodetype(type='Address',
                                               slug='address',
                                               hidden=True)

        all_emails = NodeHandle.objects.filter(node_type=email_type)
        all_phones = NodeHandle.objects.filter(node_type=phone_type)
        all_address = NodeHandle.objects.filter(node_type=address_type)

        # delete context from all these nodes
        NodeHandleContext.objects.filter(context=com_ctx,
                                         nodehandle__in=all_emails).delete()
        NodeHandleContext.objects.filter(context=com_ctx,
                                         nodehandle__in=all_phones).delete()
        NodeHandleContext.objects.filter(context=com_ctx,
                                         nodehandle__in=all_emails).delete()

        # fix it
        call_command(
            self.cmd_name,
            contextfix=True,
            verbosity=0,
        )

        # check that every node have a context
        comm_emails_num = NodeHandleContext.objects.filter(
            context=com_ctx, nodehandle__in=all_emails).count()
        emails_num = all_emails.count()

        self.assertEqual(comm_emails_num, emails_num)

        comm_phones_num = NodeHandleContext.objects.filter(
            context=com_ctx, nodehandle__in=all_phones).count()
        phones_num = all_phones.count()

        self.assertEqual(comm_phones_num, phones_num)

        comm_address_num = NodeHandleContext.objects.filter(
            context=com_ctx, nodehandle__in=all_address).count()
        address_num = all_address.count()

        self.assertEqual(comm_address_num, address_num)
コード例 #11
0
    def test_fix_emails_phones(self):
        # call csvimport command (verbose 0) to import test contacts
        call_command(
            self.cmd_name,
            contacts=self.contacts_file,
            verbosity=0,
        )

        # check one of the contacts is present
        full_name = '{} {}'.format('Caesar', 'Newby')
        qs = NodeHandle.objects.filter(node_name=full_name)
        self.assertIsNotNone(qs)
        contact1 = qs.first()
        self.assertIsNotNone(contact1)
        self.assertIsInstance(contact1.get_node(), ncmodels.ContactModel)
        contact_node = contact1.get_node()

        # check user emails in old fields
        email1_test = '*****@*****.**'
        has_email1 = 'email' in contact_node.data
        self.assertTrue(has_email1)
        self.assertEquals(contact_node.data['email'], email1_test)

        email2_test = '*****@*****.**'
        has_email2 = 'other_email' in contact_node.data
        self.assertTrue(has_email2)
        self.assertEquals(contact_node.data['other_email'], email2_test)

        # check user phones in old fields
        phone1_test = '897-979-7799'
        has_phone1 = 'phone' in contact_node.data
        self.assertTrue(has_phone1)
        self.assertEquals(contact_node.data['phone'], phone1_test)

        phone2_test = '501-503-1550'
        has_phone2 = 'mobile' in contact_node.data
        self.assertTrue(has_phone2)
        self.assertEquals(contact_node.data['mobile'], phone2_test)

        call_command(
            self.cmd_name,
            emailphones=True,
            verbosity=0,
        )

        # check the old fields are not present anymore
        qs = NodeHandle.objects.filter(node_name=full_name)
        self.assertIsNotNone(qs)
        contact1 = qs.first()
        self.assertIsNotNone(contact1)
        self.assertIsInstance(contact1.get_node(), ncmodels.ContactModel)
        contact_node = contact1.get_node()

        has_phone1 = 'phone' in contact_node.data
        self.assertTrue(not has_phone1)
        has_phone2 = 'mobile' in contact_node.data
        self.assertTrue(not has_phone2)
        has_email1 = 'email' in contact_node.data
        self.assertTrue(not has_email1)
        has_email2 = 'other_email' in contact_node.data
        self.assertTrue(not has_email2)

        relations = contact_node.get_outgoing_relations()
        relation_keys = list(relations.keys())
        has_phone = 'Has_phone' in relation_keys
        has_emails = 'Has_email' in relation_keys

        test_dict = {
            'email': {
                'work': email1_test,
                'personal': email2_test,
            },
            'phone': {
                'work': phone1_test,
                'personal': phone2_test,
            }
        }

        self.assertTrue(has_phone)
        self.assertTrue(has_emails)

        for phone_rel in relations['Has_phone']:
            phone_node = phone_rel['node']
            phone_type = phone_node.data['type']
            check_phone = test_dict['phone'][phone_type]
            self.assertEquals(check_phone, phone_node.data['name'])

            # check phone has the community context
            phone_nh = NodeHandle.objects.get(handle_id=phone_node.handle_id)
            com_ctx = sriutils.get_community_context()
            rule = srirules.BelongsContext(com_ctx)
            self.assertTrue(rule.satisfied(phone_nh))

        for email_rel in relations['Has_email']:
            email_node = email_rel['node']
            email_type = email_node.data['type']
            check_email = test_dict['email'][email_type]
            self.assertEquals(check_email, email_node.data['name'])

            # check phone has the community context
            email_nh = NodeHandle.objects.get(handle_id=email_node.handle_id)
            com_ctx = sriutils.get_community_context()
            rule = srirules.BelongsContext(com_ctx)
            self.assertTrue(rule.satisfied(email_nh))
コード例 #12
0
    def test_fix_addresss(self):
        # call csvimport command (verbose 0) to import test contacts
        call_command(
            self.cmd_name,
            organizations=self.organizations_file,
            verbosity=0,
        )

        # check one of the contacts is present
        org_name = "Tazz"
        qs = NodeHandle.objects.filter(node_name=org_name)
        self.assertIsNotNone(qs)
        organization1 = qs.first()
        self.assertIsNotNone(organization1)
        self.assertIsInstance(organization1.get_node(),
                              ncmodels.OrganizationModel)
        organization1_node = organization1.get_node()

        # check organization's website and phone
        phone1_test = '453-896-3068'
        has_phone1 = 'phone' in organization1_node.data
        self.assertTrue(has_phone1)
        self.assertEquals(organization1_node.data['phone'], phone1_test)

        website1_test = 'https://studiopress.com'
        has_website1 = 'website' in organization1_node.data
        self.assertTrue(has_website1)
        self.assertEquals(organization1_node.data['website'], website1_test)

        call_command(
            self.cmd_name,
            addressfix=True,
            verbosity=0,
        )

        # check the old fields are not present anymore
        qs = NodeHandle.objects.filter(node_name=org_name)
        self.assertIsNotNone(qs)
        organization1 = qs.first()
        self.assertIsNotNone(organization1)
        self.assertIsInstance(organization1.get_node(),
                              ncmodels.OrganizationModel)
        organization1_node = organization1.get_node()

        has_phone = 'phone' in organization1_node.data
        self.assertFalse(has_phone)

        relations = organization1_node.get_outgoing_relations()
        relation_keys = list(relations.keys())
        has_address = 'Has_address' in relation_keys
        self.assertTrue(has_address)

        address_node = relations['Has_address'][0]['node']
        self.assertIsInstance(address_node, ncmodels.AddressModel)

        has_phone = 'phone' in address_node.data
        self.assertTrue(has_phone)

        # check address has the community context
        address_nh = NodeHandle.objects.get(handle_id=address_node.handle_id)
        com_ctx = sriutils.get_community_context()
        rule = srirules.BelongsContext(com_ctx)
        self.assertTrue(rule.satisfied(address_nh))
コード例 #13
0
ファイル: data_generator.py プロジェクト: SUNET/ni
 def add_community_context(self, nh):
     com_ctx = sriutils.get_community_context()
     NodeHandleContext(nodehandle=nh, context=com_ctx).save()
コード例 #14
0
def forwards_func(apps, schema_editor):
    NodeType = apps.get_model('noclook', 'NodeType')
    NodeHandle = apps.get_model('noclook', 'NodeHandle')
    Context = apps.get_model('noclook', 'Context')
    NodeHandleContext = apps.get_model('noclook', 'NodeHandleContext')
    Dropdown = apps.get_model('noclook', 'Dropdown')
    Choice = apps.get_model('noclook', 'Choice')
    User = apps.get_model('auth', 'User')

    # wait for neo4j to be available
    neo4j_inited = False
    failure_count = 3
    while not neo4j_inited and failure_count != 0:
        if nc.graphdb.manager:
            neo4j_inited = True
        else:
            failure_count = failure_count - 1
            time.sleep(2)

    if neo4j_inited:
        username = '******'
        passwd = User.objects.make_random_password(length=30)
        user = None

        try:
            user = User.objects.get(username=username)
        except:
            user = User(username=username, password=passwd).save()

        # get the values from the old group dropdown
        groups_dropname = 'responsible_groups'

        groupdropdown, created = \
            Dropdown.objects.get_or_create(name=groups_dropname)
        choices = Choice.objects.filter(dropdown=groupdropdown)

        group_type, created = NodeType.objects.get_or_create(type='Group',
                                                             slug='group')
        groups_dict = {}

        community_context = sriutils.get_community_context(Context)

        host_type_objs = []
        for host_type_str in host_types:
            host_type, created = NodeType.objects.get_or_create(
                type=host_type_str, slug=slugify(host_type_str))
            host_type_objs.append(host_type)

        if NodeHandle.objects.filter(node_type__in=host_type_objs).exists():
            for choice in choices:
                node_name = choice.name

                group_nh, created = NodeHandle.objects.get_or_create(
                    node_name=node_name,
                    node_type=group_type,
                    node_meta_type=nc.META_TYPES[1],  # Logical
                    creator=user,
                    modifier=user,
                )

                if created:
                    try:
                        nc.create_node(nc.graphdb.manager, node_name,
                                       group_nh.node_meta_type,
                                       group_type.type, group_nh.handle_id)
                    except CypherError:
                        pass

                    NodeHandleContext(nodehandle=group_nh,
                                      context=community_context).save()

                groups_dict[node_name] = group_nh

            # if there's nodes on the db, create groups with these values
            prop_methods = {
                'responsible_group': 'set_takes_responsibility',
                'support_group': 'set_supports',
            }

            # loop over entity types
            for host_type in host_type_objs:
                nhs = NodeHandle.objects.filter(node_type=host_type)

                # loop over entities of this type
                for nh in nhs:
                    host_node = nc.get_node_model(nc.graphdb.manager,
                                                  nh.handle_id)

                    for prop, method_name in prop_methods.items():
                        # get old data
                        prop_value = host_node.data.get(prop, None)

                        # link matched group
                        if prop_value and prop_value in groups_dict:
                            group_nh = groups_dict[prop_value]
                            group_node = nc.get_node_model(nc.graphdb.manager,\
                                group_nh.handle_id)

                            method = getattr(group_node, method_name, None)

                            if method:
                                method(nh.handle_id)

                            # remove old property
                            host_node.remove_property(prop)
コード例 #15
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()
コード例 #16
0
ファイル: test_utils.py プロジェクト: SUNET/ni
    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)