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
def test_create_resource(self): # check that only user1 and user2 (from the group2) can create resources in the community module result_auth_u1 = sriutils.authorize_create_resource( self.user1, self.community_ctxt) result_auth_u2 = sriutils.authorize_create_resource( self.user2, self.community_ctxt) result_auth_u3 = sriutils.authorize_create_resource( self.user3, self.community_ctxt) self.assertTrue(result_auth_u1) self.assertTrue(result_auth_u2) self.assertFalse(result_auth_u3) # check that only user1 and user2 (from the group2) can create resources in the contracts modules result_auth_u1 = sriutils.authorize_create_resource( self.user1, self.contracts_ctxt) result_auth_u2 = sriutils.authorize_create_resource( self.user2, self.contracts_ctxt) result_auth_u3 = sriutils.authorize_create_resource( self.user3, self.contracts_ctxt) self.assertTrue(result_auth_u1) self.assertTrue(result_auth_u2) self.assertFalse(result_auth_u3) # check that none of them can create resources in the network module result_auth_u1 = sriutils.authorize_create_resource( self.user1, self.network_ctxt) result_auth_u2 = sriutils.authorize_create_resource( self.user2, self.network_ctxt) result_auth_u3 = sriutils.authorize_create_resource( self.user3, self.network_ctxt) self.assertFalse(result_auth_u1) self.assertFalse(result_auth_u2) self.assertFalse(result_auth_u3)
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)
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)
def do_request(cls, request, **kwargs): form_class = kwargs.get('form_class') nimetaclass = getattr(cls, 'NIMetaClass') graphql_type = getattr(nimetaclass, 'graphql_type') nimetatype = getattr(graphql_type, 'NIMetaType') node_type = getattr(nimetatype, 'ni_type').lower() node_meta_type = getattr(nimetatype, 'ni_metatype').capitalize() context_method = getattr(nimetatype, 'context_method') has_error = False context = context_method() # 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() for field, roledict in DEFAULT_ROLES.items(): if field in post_data: handle_id = post_data.get(field) handle_id = relay.Node.from_global_id(handle_id)[1] post_data.pop(field) post_data.update({field: handle_id}) relay_extra_ids = ('relationship_parent_of', 'relationship_uses_a') for field in relay_extra_ids: handle_id = post_data.get(field) 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(): try: nh = helpers.form_to_generic_node_handle(request, form, node_type, node_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 # use property keys to avoid inserting contacts as a string property of the node property_keys = [ 'name', 'description', 'organization_id', 'type', 'incident_management_info', 'affiliation_customer', 'affiliation_end_customer', 'affiliation_provider', 'affiliation_partner', 'affiliation_host_user', 'affiliation_site_owner', 'website', 'organization_number' ] helpers.form_update_node(request.user, nh.handle_id, form, property_keys) nh_reload, organization = helpers.get_nh_node(nh.handle_id) # add default context NodeHandleContext(nodehandle=nh, context=context).save() # specific role setting for field, roledict in DEFAULT_ROLES.items(): if field in form.cleaned_data: contact_id = form.cleaned_data[field] role = RoleModel.objects.get(slug=field) set_contact = helpers.get_contact_for_orgrole(organization.handle_id, role) if contact_id: if set_contact: if set_contact.handle_id != contact_id: helpers.unlink_contact_with_role_from_org(request.user, organization, role) helpers.link_contact_role_for_organization(request.user, organization, contact_id, role) else: helpers.link_contact_role_for_organization(request.user, organization, contact_id, role) elif set_contact: helpers.unlink_contact_and_role_from_org(request.user, organization, set_contact.handle_id, role) # Set child organizations if form.cleaned_data['relationship_parent_of']: organization_nh = NodeHandle.objects.get(handle_id=form.cleaned_data['relationship_parent_of']) helpers.set_parent_of(request.user, organization, organization_nh.handle_id) if form.cleaned_data['relationship_uses_a']: procedure_nh = NodeHandle.objects.get(handle_id=form.cleaned_data['relationship_uses_a']) helpers.set_uses_a(request.user, organization, procedure_nh.handle_id) 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
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
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)