Esempio n. 1
0
def tags_remove():
    """
    Remove a tag from all documents and the system tags colleciton.
    
    Returns
    -------
    ObjectID
        ObjectID of the tag removed.
    """
    tagID = request.form.get('tagID')
    password = request.form.get('password')
    if not objectId_is_valid(tagID):
        return ApiException(error_type="Validation Error",
                            message='The tag ID given is not valid.',
                            status=400)
    if not daoAdmin.check_password(
            daoAdmin.get_admin(get_jwt_identity()).password, password):
        return ApiException(
            error_type="Authentication Error",
            message='The password given was does not match our records.',
            status=403)
    tag = dao.remove_tag(tagID)
    if tag is None:
        return ApiException(error_type="Database Error",
                            message='The tag ID given was not found.',
                            status=404)
    return ApiResult(body={'tag': tagID})
def get_revision():
    """
    Retrieve a DocumentCaseRevision to be viewd.

    Returns
    -------
    DocumentCaseRevision[]
        DocumentCaseRevision that matched the given Id.

    ApiException
        Exception if the revision ID given was not fount.
    
    """
    revDocId = request.form.get('revDocId')
    valid_revdoc_id = objectId_is_valid(revDocId)
    if not valid_revdoc_id:
        return ApiException(
            error_type="Validation Error",
            message='The revision document ID given is not valid.',
            status=400)
    revision = dao.get_document_rev(revDocId)
    if revision is None:
        return ApiException(
            error_type="Database Error",
            message='The revision document ID given was not found.',
            status=404)

    body = {
        'new': revision.field_changed.new.to_json(),
        'old': revision.field_changed.old.to_json()
    }
    return ApiResult(body={'revision': body})
Esempio n. 3
0
def documents_view(docID):
    """
    Returns a document to view. 
    
    Parameters
    ----------
    docID : ObjectId
        12-byte MongoDB compliant Object id of the document to be publish.
    
    Returns
    -------
    Document
        Document that is going to be viewed.
    
    ApiException
        If the document id is not valid or if a document with the given id was not found.

    """
    valid_doc_id = objectId_is_valid(docID)
    if not valid_doc_id:
        return ApiException(error_type="Validation Error",
                            message='The documents ID given is not valid.',
                            status=400)
    document = dao.get_document(docID)
    if not document:
        return ApiException(error_type="Database Error",
                            message='The documents ID given was not found.',
                            status=404)
    collab = document.creatoriD
    actors = []
    authors = []
    sections = []
    for author in document.author:
        authors.append(json.loads(author.to_json()))
    for actor in document.actor:
        actors.append(json.loads(actor.to_json()))
    for section in document.section:
        sections.append(json.loads(section.to_json()))
    body = {
        '_id': str(document.id),
        'title': document.title,
        'description': document.description,
        'creatorFullName': collab.first_name + " " + collab.last_name,
        'creatorEmail': collab.email,
        'creationDate': document.creationDate,
        'lastModificationDate': document.lastModificationDate,
        'incidentDate': document.incidentDate,
        'tagsDoc': document.tagsDoc,
        'infrasDocList': document.infrasDocList,
        'damageDocList': document.damageDocList,
        'author': authors,
        'actor': actors,
        'section': sections
    }
    body = json.dumps(body)
    return ApiResult(body={'document': json.loads(body)})
Esempio n. 4
0
def login():
    """
    Generate a new access token for the user. User must have valid credentials in the databse to get a valid token.
    
    Parameters
    ----------
    username : string
        Username of the administrator account.
    password : string
        Password of the administrator account.

    Returns
    -------
    string
        JWT token with the username as identity.
    
    ApiException
        If the username or password fields are empty or are invalid. 

    """
    try:
        username = request.form.get("username").lower()
    except:
        return ApiException(error_type="Authentication Error",
                            message='Invalid username or password.',
                            status=401)
    password = request.form.get("password")
    if not username_isvalid(username) or not password_isvalid(password):
        return ApiException(error_type="Authentication Error",
                            message='Invalid username or password.',
                            status=401)
    admin = dao.get_admin(username)
    if not admin:
        return ApiException(error_type="Authentication Error",
                            message='Invalid username or password.',
                            status=401)
    authorized = dao.check_password(admin['password'], password)
    if not authorized:
        return ApiException(error_type="Authentication Error",
                            message='Invalid username or password.',
                            status=401)

    return ApiResult(
        body={
            'access_token':
            create_access_token(identity=username,
                                fresh=True,
                                expires_delta=timedelta(minutes=10))
        })
Esempio n. 5
0
 def handle_unexpected_error(error):
     TellSpaceError(err=error,
                    msg='An unexpected error has occurred.',
                    status=500)
     return ApiException(error_type='UnexpectedError',
                         message=str(error),
                         status=500)
def access_requests_deny():
    """
    Deny the access request of a user.
    
    Parameters
    ----------
    collabID : ObjectId
        12-byte MongoDB compliant Object id of the access request to be denied.
    
    Returns
    -------
    ObjectID
        ObjectID of the access request that was denied.

    ApiException
        If the access request id is not valid or if an access request with the given id was not found.
    """
    collab_id = request.form.get('collabID')
    password = request.form.get('password')
    valid_collab_id = objectId_is_valid(collab_id)
    if not valid_collab_id:
        return ApiException(
            error_type="Validation Error",
            message='The access request ID given is not valid.',
            status=400)
    if not daoAdmin.check_password(
            daoAdmin.get_admin(get_jwt_identity()).password, password):
        return ApiException(
            error_type="Authentication Error",
            message='The password given does not match our records.',
            status=403)
    access_request = dao.deny_access_request(collab_id)
    if access_request is None:
        return ApiException(
            error_type="Database Error",
            message='The access request ID given was not found.',
            status=404)

    # TODO: Use DAOs to retrieve the necessary information.
    return ApiResult(body={'access_request': collab_id})
def collaborators_ban():
    """
    Ban a collaborator. 
    
    Parameters
    ----------
    collabID : ObjectId
        12-byte MongoDB compliant Object id of the collaborator to be banned.
    
    Returns
    -------
    ObjectID
        ObjectID of the collaborator that was banned.
    
    ApiException
        If the collaborators id is not valid or if a collaborator with the given id was not found.

    """
    collab_id = request.form.get('collabID')
    password = request.form.get('password')
    valid_collab_id = objectId_is_valid(collab_id)
    if not valid_collab_id:
        return ApiException(error_type="Validation Error",
                            message='The collaborators ID given is not valid.',
                            status=400)
    if not daoAdmin.check_password(
            daoAdmin.get_admin(get_jwt_identity()).password, password):
        return ApiException(
            error_type="Authentication Error",
            message='The password given does not match our records.',
            status=403)
    collaborator = dao.ban_collaborator(collab_id)
    if collaborator is None:
        return ApiException(
            error_type="Database Error",
            message='The collaborators ID given was not found.',
            status=404)

    return ApiResult(body={'collaborator': collab_id})
Esempio n. 8
0
def documents_publish():
    """
    Publish a document. 
    
    Parameters
    ----------
    docID : ObjectId
        12-byte MongoDB compliant Object id of the document to be publish.
    
    Returns
    -------
    ObjectID
        ObjectID of the document that was published.
    
    ApiException
        If the document id is not valid or if a document with the given id was not found.

    """
    doc_id = request.form.get('docID')
    password = request.form.get('password')
    valid_doc_id = objectId_is_valid(doc_id)
    if not valid_doc_id:
        return ApiException(error_type="Validation Error",
                            message='The documents ID given is not valid.',
                            status=400)
    if not daoAdmin.check_password(
            daoAdmin.get_admin(get_jwt_identity()).password, password):
        return ApiException(
            error_type="Authentication Error",
            message='The password given was does not match our records.',
            status=403)
    document = dao.publish_document(doc_id)
    if not document:
        return ApiException(error_type="Database Error",
                            message='The documents ID given was not found.',
                            status=404)
    return ApiResult(body={'docID': doc_id})
    def register_error_handlers(self):
        """Register error daos to flask application instance.
        Arguments:
            app {flask application} -- application instance
        """
        if self.config['DEBUG'] == 0:

            # Register marshmallow validator  exceptions
            for name, obj in inspect.getmembers(
                    sys.modules['marshmallow.exceptions']):
                if inspect.isclass(obj):

                    @self.errorhandler(obj)
                    def handle_marshmallow_errors(error):
                        return ApiException(
                            error_type='Validation Error',
                            message=
                            'Please verify you request body and parameters.',
                            status=400)

            # Register mongoengine  exceptions
            for name, obj in inspect.getmembers(
                    sys.modules['mongoengine.errors']):
                if inspect.isclass(obj) and not name == 'defaultdict':

                    @self.errorhandler(obj)
                    def handle_database_errors(error):
                        return ApiException(
                            error_type='Database Connection Error',
                            message='Internal Server Error',
                            status=500)

            @self.errorhandler(SearchSpaceApiError)
            def handle_api_error(error):
                return ApiException(error_type=error.error_type,
                                    message=error.msg,
                                    status=error.status)

            @self.errorhandler(SearchSpaceRequestError)
            def handle_request_error(error):
                return ApiException(error_type=error.error_type,
                                    message=error.msg,
                                    status=error.status)

            @self.errorhandler(SearchSpaceRequestValidationError)
            def handle_request_error(error):
                return ApiException(error_type=error.error_type,
                                    message=error.msg,
                                    status=error.status)

            @self.errorhandler(Exception)
            def handle_unexpected_error():
                return ApiException(
                    error_type='Unexpected Error',
                    message='An unexpected error has occurred.',
                    status=500)

        self.register_error_handler(
            400, lambda err: ApiException(
                message=str(err), status=400, error_type='Bad request'))

        self.register_error_handler(
            404, lambda err: ApiException(
                message=str(err), status=404, error_type='Not found'))

        self.register_error_handler(
            405, lambda err: ApiException(
                message=str(err), status=405, error_type='Request method'))
Esempio n. 10
0
 def handle_custom_errors(error):
     return ApiException(error_type=error.__class__.__name__,
                         message=error.msg,
                         status=error.status)
Esempio n. 11
0
 def request_token_errors(error):
     return ApiException(error_type='JWTTokenError',
                         message=error.messages,
                         status=error.status)
Esempio n. 12
0
 def request_value_error(error):
     return ApiException(error_type='ValidationError',
                         message=error.messages,
                         status=400)
Esempio n. 13
0
 def handle_unexpected_error(error):
     return ApiException(error_type='UnexpectedError',
                         message=str(error),
                         status=500)
Esempio n. 14
0
 def nonfresh_token_callback(callback):
     # Invalid Non-Fresh Access token in auth header
     return ApiException(
         error_type='AdminServerRequestError',
         message='Invalid Authentication Token - Not Fresh.',
         status=400)
Esempio n. 15
0
 def request_value_error(error):
     return ApiException(error_type='ValidationError',
                         message="Validation error in the system",
                         status=400)
Esempio n. 16
0
 def handle_error(error):
     return ApiException(error_type=error.__class__.__name__,
                         message=error.error_stack,
                         status=error.status)
Esempio n. 17
0
 def handle_request_error(error):
     return ApiException(error_type=error.__class__.__name__,
                         message=error.msg,
                         status=error.status)
 def handle_unexpected_error():
     return ApiException(
         error_type='Unexpected Error',
         message='An unexpected error has occurred.',
         status=500)
 def handle_request_error(error):
     return ApiException(error_type=error.error_type,
                         message=error.msg,
                         status=error.status)
 def handle_database_errors(error):
     return ApiException(
         error_type='Database Connection Error',
         message='Internal Server Error',
         status=500)
 def handle_marshmallow_errors(error):
     return ApiException(
         error_type='Validation Error',
         message=
         'Please verify you request body and parameters.',
         status=400)
Esempio n. 22
0
def register_error_handlers(app: ApiFlask):
    """Register exception classes to flask application instance.

        Parameters
        ----------
            app
                the ApiFlask application instance.
    """
    if False:

        @app.errorhandler(TellSpaceError)
        def handle_error(error):
            return ApiException(error_type=error.__class__.__name__,
                                message=error.error_stack,
                                status=error.status)
    else:

        @app.errorhandler(TellSpaceApiError)
        def handle_api_error(error):
            return ApiException(error_type=error.__class__.__name__,
                                message=error.msg,
                                status=error.status)

        @app.errorhandler(TellSpaceAuthError)
        def handle_custom_errors(error):
            return ApiException(error_type=error.__class__.__name__,
                                message=error.msg,
                                status=error.status)

        # JWT Error Handler
        @app.errorhandler(JWTExtendedException)
        def request_token_errors(error):
            return ApiException(error_type='JWTTokenError',
                                message=error.messages,
                                status=error.status)

        @app.errorhandler(ValidationError)
        def request_validator_error(error):
            return ApiException(error_type='ValidationError',
                                message=error.messages,
                                status=400)

        @app.errorhandler(ValueError)
        def request_value_error(error):
            return ApiException(error_type='ValidationError',
                                message=error.messages,
                                status=400)

        @app.errorhandler(Exception)
        def handle_unexpected_error(error):
            TellSpaceError(err=error,
                           msg='An unexpected error has occurred.',
                           status=500)
            return ApiException(error_type='UnexpectedError',
                                message=str(error),
                                status=500)

        app.register_error_handler(
            400, lambda err: ApiException(
                message=str(err), status=400, error_type='Bad request'))

        app.register_error_handler(
            404, lambda err: ApiException(
                message=str(err), status=404, error_type='Not found'))

        app.register_error_handler(
            405, lambda err: ApiException(
                message=str(err), status=405, error_type='Request method'))