Beispiel #1
0
    def test_document_content_validator(self):
        with test_context(self.app):
            model.Output(
                title="FakeOutput",
                content="Content of the fake output",
                html='',
                _owner=self._get_user('*****@*****.**')._id,
                _category=self._get_category('Area 1')._id,
                _precondition=None,
            )
            DBSession.flush()
            output = model.Output.query.get(title="FakeOutput")

            validator = DocumentContentValidator()
            try:
                res = validator._validate_python([
                    {
                        'type': "output",
                        'content': str(output._id),
                        'title': output.title
                    },
                ])
            except ValidationError:
                assert False
            else:
                assert True
Beispiel #2
0
 def test_document_content_validator_without_output(self):
     with test_context(self.app):
         validator = DocumentContentValidator()
         try:
             res = validator._validate_python("Buongiorno")
         except ValidationError:
             assert False
         else:
             assert True
Beispiel #3
0
 def test_document_content_validator_invalid_output(self):
     with test_context(self.app):
         validator = DocumentContentValidator()
         try:
             res = validator._validate_python(
                 "Buongiorno #{5757ce79c42d752bde919318}")
         except ValidationError:
             assert True
         else:
             assert False
Beispiel #4
0
 def test_document_content_validator_invalid_type_output(self):
     with test_context(self.app):
         validator = DocumentContentValidator()
         try:
             res = validator._validate_python([{
                 'type': "fake_type",
                 'content': "Buongiorno",
                 'title': ""
             }])
         except ValidationError:
             assert True
         else:
             assert False
Beispiel #5
0
    def test_document_content_validator(self):
        with test_context(self.app):
            model.Output(
                title="FakeOutput",
                html='',
                _owner=self._get_user('*****@*****.**')._id,
                _workspace=self._get_workspace('Area 1')._id,
                _precondition=None,
            )
            DBSession.flush()
            output = model.Output.query.get(title="FakeOutput")

            validator = DocumentContentValidator()
            try:
                res = validator._validate_python('#{%s}' % str(output.hash))
            except ValidationError:
                assert False
            else:
                assert True
Beispiel #6
0
 def test_document_content_validator_invalid_output(self):
     with test_context(self.app):
         validator = DocumentContentValidator()
         try:
             res = validator._validate_python([
                 {
                     'type': "text",
                     'content': "Buongiorno",
                     'title': ""
                 },
                 {
                     'type': "output",
                     'content': "5757ce79c42d752bde919318",
                     'title': "fake title"
                 },
             ])
         except ValidationError:
             assert True
         else:
             assert False
Beispiel #7
0
class DocumentController(RestController):
    def _before(self, *args, **kw):
        tmpl_context.sidebar_section = "documents"

    allow_only = predicates.has_any_permission(
        'manage', 'lawyer', msg=l_('Only for admin or lawyer'))

    @expose('ksweb.templates.document.index')
    @paginate('entities',
              items_per_page=int(tg.config.get('pagination.items_per_page')))
    @validate({'workspace': WorkspaceExistValidator(required=True)})
    def get_all(self, workspace, **kw):
        return dict(
            page='document-index',
            fields={
                'columns_name':
                [_('Title'),
                 _('Description'),
                 _('Version'),
                 _('License')],
                'fields_name': ['title', 'description', 'version', 'license']
            },
            entities=model.Document.document_available_for_user(
                request.identity['user']._id, workspace=workspace),
            actions_content=[_('Export'), _('Create Form')],
            workspace=workspace,
            download=True)

    @expose('ksweb.templates.document.new')
    @validate({'workspace': WorkspaceExistValidator(required=True)})
    def new(self, workspace, **kw):
        tmpl_context.sidebar_document = "document-new"
        return dict(document={}, workspace=workspace, errors=None)

    @decode_params('json')
    @expose('json')
    @validate(
        {
            'title': StringLengthValidator(min=2),
            'workspace': WorkspaceExistValidator(required=True),
            'html': DocumentContentValidator(strip=False),
            'description': StringLengthValidator(min=0),
            'license': StringLengthValidator(min=0, max=100),
            'version': StringLengthValidator(min=0, max=100),
            'tags': StringLengthValidator(min=0, max=100)
        },
        error_handler=validation_errors_response)
    def post(self, title, workspace, description, license, version, tags, html,
             **kw):
        user = request.identity['user']
        tags = {__.strip() for __ in tags.split(',')} if tags else []

        doc = model.Document(_owner=user._id,
                             _workspace=ObjectId(workspace),
                             title=title,
                             public=True,
                             visible=True,
                             html=html,
                             description=description,
                             license=license,
                             version=version,
                             tags=list(tags))
        return dict(errors=None)

    @decode_params('json')
    @expose('json')
    @validate(
        {
            '_id': DocumentExistValidator(required=True),
            'title': StringLengthValidator(min=2),
            'workspace': WorkspaceExistValidator(required=True),
            'html': DocumentContentValidator(strip=False),
            'description': StringLengthValidator(min=0),
            'license': StringLengthValidator(min=0, max=100),
            'version': StringLengthValidator(min=0, max=100),
            'tags': StringLengthValidator(min=0),
        },
        error_handler=validation_errors_response)
    @require(
        CanManageEntityOwner(
            msg=l_(u'You are not allowed to edit this document.'),
            field='_id',
            entity_model=model.Document))
    def put(self, _id, title, html, workspace, description, license, version,
            tags, **kw):
        tags = {__.strip() for __ in tags.split(',')} if tags else []
        document = model.Document.query.find({'_id': ObjectId(_id)}).first()
        document.title = title
        document._workspace = ObjectId(workspace)
        document.html = html
        document.tags = list(tags)
        document.description = description
        document.license = license
        document.version = version
        return dict(errors=None)

    @expose('ksweb.templates.document.new')
    @validate(
        {
            '_id': DocumentExistValidator(required=True),
            'workspace': WorkspaceExistValidator(required=True)
        },
        error_handler=validation_errors_response)
    @require(
        CanManageEntityOwner(
            msg=l_(u'You are not allowed to edit this document.'),
            field='_id',
            entity_model=model.Document))
    def edit(self, _id, workspace, **kw):
        tmpl_context.sidebar_document = "document-new"
        document = model.Document.by_id(_id)
        return dict(document=document, workspace=workspace, errors=None)

    @expose('json')
    @decode_params('json')
    @validate({
        '_id': DocumentExistValidator(required=True),
    },
              error_handler=validation_errors_response)
    def human_readable_details(self, _id, **kw):
        # TODO: implement something meaningful
        document = model.Document.query.find({'_id': ObjectId(_id)}).first()
        return dict(document=document)

    @expose("json", content_type='application/json')
    @validate({
        '_id': DocumentExistValidator(required=True),
    },
              error_handler=validation_errors_response)
    def export(self, _id):
        document = model.Document.query.get(_id=ObjectId(_id))
        filename = slugify(document, document.title)
        response.headerlist.append(
            ('Content-Disposition',
             str('attachment;filename=%s.json' % filename)))
        encoded = json_render.encode(document.export())
        return json.dumps(json.loads(encoded), sort_keys=True, indent=4)

    @expose()
    @validate({
        'workspace': WorkspaceExistValidator(required=True),
    },
              error_handler=validation_errors_response)
    def import_document(self, workspace, file_import):
        owner = request.identity['user']._id
        file_content = file_import.file.read()
        importer = JsonImporter(file_content, ObjectId(workspace), owner)
        importer.run()
        tg.flash(_('Document successfully imported!'))
        return redirect(tg.url('/document', params=dict(workspace=workspace)))