Exemple #1
0
    def test_simple_call_with_nested(self, mock_eng):
        document_cls = Mock(
            _public_fields=['name', 'desc'],
            _auth_fields=['id', 'creator'],
            _hidden_fields=[])
        mock_eng.get_document_cls.return_value = document_cls
        request = Mock(user=Mock())
        data = {
            'id': 1,
            '_type': 'foo1',
            'username': 'admin',
            'creator': {
                'id': 2,
                '_type': 'foo2',
                'creator': 'foo',
                'address': 'adsasd',
            }
        }
        filtered = wrappers.apply_privacy(request)(
            result=data, is_admin=False)
        assert filtered == {
            '_type': 'foo1',
            'id': 1,
            'creator': {
                '_type': 'foo2',
                'creator': 'foo',
                'id': 2
            }

        }
Exemple #2
0
 def test_apply_privacy_item_no_document_cls(self, mock_eng):
     mock_eng.get_document_cls.side_effect = ValueError
     request = Mock(user=Mock())
     filtered = wrappers.apply_privacy(request)(
         result=self.model_test_data, is_admin=True)
     assert list(sorted(filtered.keys())) == [
         '_type', 'desc', 'id', 'name', 'other_field', 'self']
Exemple #3
0
 def test_apply_privacy_item_no_request(self, mock_eng):
     document_cls = Mock(
         _public_fields=['name', 'desc'],
         _auth_fields=['id'])
     mock_eng.get_document_cls.return_value = document_cls
     filtered = wrappers.apply_privacy(None)(result=self.model_test_data)
     assert list(sorted(filtered.keys())) == [
         '_type', 'desc', 'id', 'name', 'other_field', 'self']
Exemple #4
0
    def setup_default_wrappers(self):
        """ Setup defaulf wrappers.

        Wrappers are applied when view method does not return instance
        of Response. In this case nefertari renderers call wrappers and
        handle response generation.

        Note: It's important for `add_etag` wrapper be applied before
        `apply_privacy` as later may remove response data that
        is used to generate etag
        """
        # Index
        self._after_calls['index'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
            wrappers.add_object_url(self.request),
            wrappers.add_etag(self.request),
        ]

        # Show
        self._after_calls['show'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
            wrappers.add_object_url(self.request),
        ]

        # Create
        self._after_calls['create'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
            wrappers.add_object_url(self.request),
        ]

        # Update
        self._after_calls['update'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
            wrappers.add_object_url(self.request),
        ]

        # Replace
        self._after_calls['replace'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
            wrappers.add_object_url(self.request),
        ]

        # Privacy wrappers
        if self._auth_enabled:
            for meth in ('index', 'show', 'create', 'update', 'replace'):
                self._after_calls[meth] += [
                    wrappers.apply_privacy(self.request),
                ]
            for meth in ('update', 'replace', 'update_many'):
                self._before_calls[meth] += [
                    wrappers.apply_request_privacy(
                        self.Model, self._json_params),
                ]
Exemple #5
0
 def test_apply_privacy_item_no_fields(self, mock_eng):
     document_cls = Mock(
         _public_fields=['name', 'desc'],
         _auth_fields=[])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=Mock())
     filtered = wrappers.apply_privacy(request)(
         result=self.model_test_data, is_admin=False)
     assert list(sorted(filtered.keys())) == ['_type', 'self']
Exemple #6
0
 def test_item_non_auth(self, mock_eng):
     document_cls = Mock(
         _public_fields=['name', 'desc'],
         _auth_fields=['id'],
         _hidden_fields=[])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=None)
     filtered = wrappers.apply_privacy(request)(result=self.model_test_data)
     assert list(sorted(filtered.keys())) == [
         '_pk', '_self', '_type', 'desc', 'name']
 def test_collection(self, mock_eng):
     document_cls = Mock(_public_fields=["name", "desc"], _auth_fields=["id"], _hidden_fields=[])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=Mock())
     result = {"total": 1, "count": 1, "data": [self.model_test_data]}
     filtered = wrappers.apply_privacy(request)(result=result, is_admin=False)
     assert list(sorted(filtered.keys())) == ["count", "data", "total"]
     assert len(filtered["data"]) == 1
     data = filtered["data"][0]
     assert list(sorted(data.keys())) == ["_pk", "_self", "_type", "id"]
 def test_no_type(self, mock_eng):
     data = self.model_test_data.copy()
     data.pop("_type")
     request = Mock(user=Mock())
     filtered = wrappers.apply_privacy(request)(result=data, is_admin=True)
     assert list(sorted(filtered.keys())) == ["_pk", "_self", "desc", "id", "name", "other_field"]
     filtered["desc"] == "User 1 data"
     filtered["id"] == 1
     filtered["name"] == "User1"
     filtered["other_field"] == 123
     filtered["_self"] == "http://example.com/1"
     assert not mock_eng.get_document_cls.called
    def test_item_auth_calculated(self, mock_eng):
        document_cls = Mock(_public_fields=["name", "desc"], _auth_fields=["id"], _hidden_fields=[])
        mock_eng.get_document_cls.return_value = document_cls

        class User(object):
            @classmethod
            def is_admin(self, obj):
                return False

        request = Mock(user=User())
        filtered = wrappers.apply_privacy(request)(result=self.model_test_data)
        assert list(sorted(filtered.keys())) == ["_pk", "_self", "_type", "id"]
Exemple #10
0
 def test_hidden_fields_not_drop(self, mock_eng):
     document_cls = Mock(
         _public_fields=['name', 'desc'],
         _auth_fields=['id'],
         _hidden_fields=['name'])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=Mock())
     filtered = wrappers.apply_privacy(request)(
         result=self.model_test_data, is_admin=False,
         drop_hidden=False)
     assert list(sorted(filtered.keys())) == [
         '_pk', '_self', '_type', 'id', 'name']
 def test_apply_nested_privacy_list(self, mock_eng):
     document_cls = Mock(_public_fields=["name", "desc"], _auth_fields=["id"], _hidden_fields=[])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=Mock())
     data = {"owner": [self.model_test_data]}
     wrapper = wrappers.apply_privacy(request)
     wrapper.is_admin = False
     wrapper.drop_hidden = False
     filtered = wrapper._apply_nested_privacy(data)
     assert list(filtered.keys()) == ["owner"]
     owner = filtered["owner"][0]
     assert sorted(owner.keys()) == ["_pk", "_self", "_type", "id"]
 def test_simple_call_with_nested(self, mock_eng):
     document_cls = Mock(_public_fields=["name", "desc"], _auth_fields=["id", "creator"], _hidden_fields=[])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=Mock())
     data = {
         "id": 1,
         "_type": "foo1",
         "username": "admin",
         "creator": {"id": 2, "_type": "foo2", "creator": "foo", "address": "adsasd"},
     }
     filtered = wrappers.apply_privacy(request)(result=data, is_admin=False)
     assert filtered == {"_type": "foo1", "id": 1, "creator": {"_type": "foo2", "creator": "foo", "id": 2}}
 def test_item_admin(self, mock_eng):
     document_cls = Mock(_public_fields=["name", "desc"], _auth_fields=["id"], _hidden_fields=[])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=Mock())
     filtered = wrappers.apply_privacy(request)(result=self.model_test_data, is_admin=True)
     assert list(sorted(filtered.keys())) == ["_pk", "_self", "_type", "desc", "id", "name", "other_field"]
     filtered["_type"] == "foo"
     filtered["desc"] == "User 1 data"
     filtered["id"] == 1
     filtered["name"] == "User1"
     filtered["other_field"] == 123
     filtered["_self"] == "http://example.com/1"
     mock_eng.get_document_cls.assert_called_once_with("foo")
Exemple #14
0
 def test_apply_privacy_no_type(self, mock_eng):
     data = self.model_test_data.copy()
     data.pop('_type')
     request = Mock(user=Mock())
     filtered = wrappers.apply_privacy(request)(
         result=data, is_admin=True)
     assert list(sorted(filtered.keys())) == [
         'desc', 'id', 'name', 'other_field', 'self']
     filtered['desc'] == 'User 1 data'
     filtered['id'] == 1
     filtered['name'] == 'User1'
     filtered['other_field'] == 123
     filtered['self'] == 'http://example.com/1'
     assert not mock_eng.get_document_cls.called
Exemple #15
0
    def test_apply_privacy_item_auth_calculated(self, mock_eng):
        document_cls = Mock(
            _public_fields=['name', 'desc'],
            _auth_fields=['id'])
        mock_eng.get_document_cls.return_value = document_cls

        class User(object):
            @classmethod
            def is_admin(self, obj):
                return False

        request = Mock(user=User())
        filtered = wrappers.apply_privacy(request)(result=self.model_test_data)
        assert list(sorted(filtered.keys())) == [
            '_type', 'id', 'self']
Exemple #16
0
    def setup_default_wrappers(self):
        root_resource = getattr(self, 'root_resource', None)
        auth_enabled = root_resource and root_resource.auth

        self._after_calls['index'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
        ]
        if auth_enabled:
            self._after_calls['index'] += [
                wrappers.apply_privacy(self.request),
            ]
        self._after_calls['index'] += [
            wrappers.add_etag(self.request),
        ]

        self._after_calls['show'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
        ]
        if auth_enabled:
            self._after_calls['show'] += [
                wrappers.apply_privacy(self.request),
            ]

        self._after_calls['delete'] = [
            wrappers.add_confirmation_url(self.request)
        ]

        self._after_calls['delete_many'] = [
            wrappers.add_confirmation_url(self.request)
        ]

        self._after_calls['update_many'] = [
            wrappers.add_confirmation_url(self.request)
        ]
Exemple #17
0
 def test_apply_nested_privacy_list(self, mock_eng):
     document_cls = Mock(
         _public_fields=['name', 'desc'],
         _auth_fields=['id'],
         _hidden_fields=[])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=Mock())
     data = {'owner': [self.model_test_data]}
     wrapper = wrappers.apply_privacy(request)
     wrapper.is_admin = False
     wrapper.drop_hidden = False
     filtered = wrapper._apply_nested_privacy(data)
     assert list(filtered.keys()) == ['owner']
     owner = filtered['owner'][0]
     assert sorted(owner.keys()) == [
         '_pk', '_self', '_type', 'id']
Exemple #18
0
 def test_apply_privacy_item_admin(self, mock_eng):
     document_cls = Mock(
         _public_fields=['name', 'desc'],
         _auth_fields=['id'])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=Mock())
     filtered = wrappers.apply_privacy(request)(
         result=self.model_test_data, is_admin=True)
     assert list(sorted(filtered.keys())) == [
         '_type', 'desc', 'id', 'name', 'other_field', 'self']
     filtered['_type'] == 'foo'
     filtered['desc'] == 'User 1 data'
     filtered['id'] == 1
     filtered['name'] == 'User1'
     filtered['other_field'] == 123
     filtered['self'] == 'http://example.com/1'
     mock_eng.get_document_cls.assert_called_once_with('foo')
    def __init__(self, *args, **kwargs):
        resource = kwargs.pop('resource', None)
        encoder = kwargs.pop('encoder', None)
        request = kwargs.pop('request', None)
        super(JHTTPCreated, self).__init__(*args, **kwargs)

        if resource and 'location' in kwargs:
            resource['self'] = kwargs['location']

        auth = request and request.registry._root_resources.values()[0].auth
        if resource and auth:
            wrapper = apply_privacy(request=request)
            resource = wrapper(result=resource)

        create_json_response(
            self, data=resource,
            encoder=encoder)
Exemple #20
0
 def test_apply_privacy_collection(self, mock_eng):
     document_cls = Mock(
         _public_fields=['name', 'desc'],
         _auth_fields=['id'])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=Mock())
     result = {
         'total': 1,
         'count': 1,
         'data': [self.model_test_data]
     }
     filtered = wrappers.apply_privacy(request)(
         result=result, is_admin=False)
     assert list(sorted(filtered.keys())) == ['count', 'data', 'total']
     assert len(filtered['data']) == 1
     data = filtered['data'][0]
     assert list(sorted(data.keys())) == ['_type', 'id', 'self']
Exemple #21
0
def validate_data_privacy(request, data, wrapper_kw=None):
    """ Validate :data: contains only data allowed by privacy settings.

    :param request: Pyramid Request instance
    :param data: Dict containing request/response data which should be
        validated
    """
    from nefertari import wrappers
    if wrapper_kw is None:
        wrapper_kw = {}

    wrapper = wrappers.apply_privacy(request)
    allowed_fields = wrapper(result=data, **wrapper_kw).keys()
    data = data.copy()
    data.pop('_type', None)
    not_allowed_fields = set(data.keys()) - set(allowed_fields)

    if not_allowed_fields:
        raise wrappers.ValidationError(', '.join(not_allowed_fields))
 def test_data_regular_attribute(self, mock_eng):
     document_cls = Mock(_public_fields=[], _auth_fields=["data"], _hidden_fields=[])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=Mock())
     filtered = wrappers.apply_privacy(request)(
         result={
             "_acl": [],
             "_type": "foo",
             "_self": "http://example.com/1",
             "_pk": "Subban",
             "data": {"stuff": 1, "other_stuff": True},
         },
         is_admin=False,
     )
     assert filtered == {
         "_type": "foo",
         "_self": "http://example.com/1",
         "_pk": "Subban",
         "data": {"stuff": 1, "other_stuff": True},
     }
Exemple #23
0
    def test_item_admin_calculated(self, mock_eng):
        document_cls = Mock(
            _public_fields=['name', 'desc'],
            _auth_fields=['id'],
            _hidden_fields=[])
        mock_eng.get_document_cls.return_value = document_cls

        class User(object):
            @classmethod
            def is_admin(self, obj):
                return True

        request = Mock(user=User())
        filtered = wrappers.apply_privacy(request)(result=self.model_test_data)
        assert list(sorted(filtered.keys())) == [
            '_pk', '_self', '_type', 'desc', 'id', 'name', 'other_field']
        filtered['_type'] == 'foo'
        filtered['desc'] == 'User 1 data'
        filtered['id'] == 1
        filtered['name'] == 'User1'
        filtered['other_field'] == 123
        filtered['_self'] == 'http://example.com/1'
        mock_eng.get_document_cls.assert_called_once_with('foo')
 def test_item_no_request(self, mock_eng):
     document_cls = Mock(_public_fields=["name", "desc"], _auth_fields=["id"], _hidden_fields=[])
     mock_eng.get_document_cls.return_value = document_cls
     filtered = wrappers.apply_privacy(None)(result=self.model_test_data)
     assert list(sorted(filtered.keys())) == ["_pk", "_self", "_type", "desc", "id", "name", "other_field"]
 def test_nested_data_not_dict(self, mock_eng):
     request = Mock(user=Mock())
     assert wrappers.apply_privacy(request)(result={"data": "foo"}, is_admin=True) == {"data": "foo"}
     assert wrappers.apply_privacy(request)(result={"data": 1}, is_admin=True) == {"data": 1}
 def test_hidden_fields_not_drop(self, mock_eng):
     document_cls = Mock(_public_fields=["name", "desc"], _auth_fields=["id"], _hidden_fields=["name"])
     mock_eng.get_document_cls.return_value = document_cls
     request = Mock(user=Mock())
     filtered = wrappers.apply_privacy(request)(result=self.model_test_data, is_admin=False, drop_hidden=False)
     assert list(sorted(filtered.keys())) == ["_pk", "_self", "_type", "id", "name"]
Exemple #27
0
 def test_apply_privacy_not_dict(self, mock_eng):
     request = Mock(user=Mock())
     filtered = wrappers.apply_privacy(request)(
         result='foo', is_admin=True)
     assert filtered == 'foo'
Exemple #28
0
 def test_apply_privacy_no_data(self):
     assert wrappers.apply_privacy(None)(result={}) == {}
 def test_item_no_document_cls(self, mock_eng):
     mock_eng.get_document_cls.side_effect = ValueError
     request = Mock(user=Mock())
     filtered = wrappers.apply_privacy(request)(result=self.model_test_data, is_admin=True)
     assert list(sorted(filtered.keys())) == ["_pk", "_self", "_type", "desc", "id", "name", "other_field"]