Ejemplo n.º 1
0
def create_image():

    # create image from url
    url = request.json['url']

    # Check if the image url exist
    existing_image = (Image.query.filter(Image.url == url).one_or_none())

    if existing_image is None:
        # Insert image to the first step of the image
        schema = ImageSchema()
        new_image = Image(url=url)

        # Save to the database
        db.session.add(new_image)
        db.session.commit()

        # Serialize and return the newly created data in the response
        data = schema.dump(new_image)

        return jsonify(data), 201

    # Otherwise, nope, data exists already
    else:
        abort(400, "Image url already exists: {url} ".format(url=url))
Ejemplo n.º 2
0
def get_all_images():
    # Create the list of images from our data
    images = Image.query.order_by(Image.id).all()
    # Serialize the data for the response
    images_schema = ImageSchema(many=True)  # strict=true
    data = images_schema.dump(images)
    return jsonify(data)
Ejemplo n.º 3
0
def create_access(user_id, image_id):
    """
    This function created an access for a person with 
    email provided in the request body to the image of the user with the given user_id
    :param user_id:   Id of user to find
    :param image_id:   Id of image to find
    :return:        201, image to which the access was given to user with the email in request body
    """
    # get the email from the request body
    email = connexion.request.get_json()
    # check if the user_id and the image_is provided is not null or empty string and email is not empty string or null
    if user_id is None or user_id == "" or image_id is None or image_id == "" or email is None or email is {} or email["email"] is None or email["email"] is "":
        abort(400,
              "Bad Request: Please send valid user Id, image Id and email")

    token_info = connexion.context['token_info']

    # Only the authorized user or the admin should be able to access the user details
    if token_info['sub'] != str(user_id) and token_info['sub'] != ADMIN_USER:
        abort(403, "Forbidden: The given user doesnt have an access")

    # get the image which needs to be added to  the email_user
    image = Images.query.filter(Images.id == image_id).filter(
        Images.admin_id == int(user_id)).one_or_none()

    if image is None:
        abort(
            403,
            "Forbidden: The given user doesnt have an admin access to the given image"
        )

    # search for the user with the given email address
    email_user = User.query.filter(User.email == email["email"]).one_or_none()

    # verify admin

    if email_user is None:
        abort(404, " Not Found: User with the given email is not found")

    #  Check if the user with the email already has permission for this image
    existing_permission = (db.session.query(Permissions).filter(
        User.id == Permissions.user_id, ).filter(
            Images.id == Permissions.image_id, ).filter(
                User.email == email["email"], ).filter(
                    Images.id == image_id).one_or_none())
    # User with the email already has persmissions
    if existing_permission is not None:
        abort(409, "Conflict: the permission already exists")

    schema = ImageSchema()
    # append the image to the user
    email_user.images.append(image)
    db.session.merge(email_user)
    db.session.commit()
    # Serialize and return the newly created image in the response
    new_image = Images.query.filter(Images.id == image_id).one_or_none()
    data = schema.dump(new_image)
    return data, 201
Ejemplo n.º 4
0
def get_all():
    """
    call get_image() with random querystring values
    ::return 10::
    """

    images = Image.query.order_by(Image.name).all()

    image_schema = ImageSchema(many=True)

    return image_schema.dump(images)
Ejemplo n.º 5
0
def revoke_access(user_id, image_id):
    """
    This function created to revoke the access of an image by the admin user to the user whose email is provided
    :param user_id:   Id of user to find
    :param image_id:   Id of image to find
    :return:        201, return the image
    """

    # get the email from the request body
    email = connexion.request.get_json()
    # check if the user_id and the image_is provided is not null or empty string and email is not empty string or null
    if user_id is None or user_id == "" or image_id is None or image_id == "" or email is None or email is {} or email["email"] is None or email["email"] is "":
        abort(400,
              "Bad Request: Please send valid user Id, image Id and email")

    token_info = connexion.context['token_info']

    # Only the authorized user or the admin should be able to access the user details
    if token_info['sub'] != str(user_id) and token_info['sub'] != ADMIN_USER:
        abort(403, "Forbidden: The given user doesnt have an access")

    # get the image which needs to be added to  the email_user
    image = Images.query.filter(Images.id == image_id).filter(
        Images.admin_id == int(user_id)).one_or_none()

    if image is None:
        abort(
            403,
            "Forbidden: The given user doesnt have an admin access to the given image"
        )
    #  Check if the user with the email already has permission for this image
    existing_permission = (db.session.query(Permissions).filter(
        User.id == Permissions.user_id, ).filter(
            Images.id == Permissions.image_id, ).filter(
                User.email == email["email"], ).filter(
                    Images.id == image_id).one_or_none())
    # User with the email already has persmissions
    if existing_permission is None:
        abort(
            404,
            "Not Found: The email user doesnt have  access to the given image")

        # Delete the permission from the db
    db.session.delete(existing_permission)
    db.session.commit()
    schema = ImageSchema()
    new_image = Images.query.filter(Images.id == image_id).one_or_none()
    data = schema.dump(new_image)
    return data, 201
Ejemplo n.º 6
0
def get_image(image_id):
    # Get the requested image
    image = Image.query.filter(Image.id == image_id).one_or_none()

    # Check if we got an image
    if image is not None:

        # Serialize the data for the response
        image_schema = ImageSchema()
        data = image_schema.dump(image)
        return jsonify(data)

    # Otherwise, nope, didn't find that image
    else:
        abort(404, "Image not found for Id: {id} ".format(id=image_id))
Ejemplo n.º 7
0
def add(image):
    print(image['name'])

    image_exists = find_image(image['name'])
    # print('>>>>', image)
    if image_exists is False:
        abort(401, "Image already exists. Try another image")

    schema = ImageSchema()
    new_image = schema.load(image, session=db.session)

    db.session.add(new_image)
    db.session.commit()

    return schema.dump(new_image), 201
Ejemplo n.º 8
0
def get_one(image_name):
    """
    scan querystring
    return 5 images by default
    """
    image = Image.query.filter(Image.name == image_name).one_or_none()

    if image is not None:
        image_schema = ImageSchema()
        return image_schema.dump(image)

    else:
        abort(
            404, 'Image does not exist for image name: {image_name}'.format(
                image_name=image_name))
Ejemplo n.º 9
0
def search(subject, portrait, landscape, winter, spring, summer, autumn):
    """
    http://www.leeladharan.com/sqlalchemy-query-with-or-and-like-common-filters
    https://www.sqlitetutorial.net/
    """

    orientation = []
    season = []

    if portrait == 'true':
        orientation.append('portrait')
    if landscape == 'true':
        orientation.append('landscape')

    if winter == 'true':
        season.append('winter')
    if spring == 'true':
        season.append('spring')
    if summer == 'true':
        season.append('summer')
    if autumn == 'true':
        season.append('autumn')

    # try:
    images = Image.query.filter(
        and_(Image.subject == subject, or_(Image.season.in_(season)),
             Image.orientation.in_(orientation))).all()

    return ImageSchema().dump(images, many='many')
Ejemplo n.º 10
0
def get_all_n(n):
    """
    n: integer

    return:: array of dictionaryies
    """

    if n > 10:
        n = 10

    images = Image.query.filter(Image.name).limit(n).all()
    return ImageSchema().dump(images, many='many')
Ejemplo n.º 11
0
def read_images(user_id):
    """
    This function returns the images related to a particular user
    :param user_id:   Id of user
    :return:        200,json string of list of images
    """
    if user_id is None or user_id == "":
        abort(400, "Bad Request: Please send valid user")

    token_info = connexion.context['token_info']

    #  Check the token belongs to the authorized user
    if token_info['sub'] != str(user_id) and token_info['sub'] != ADMIN_USER:
        abort(
            403,
            "Forbidden: The given user doesnt have access to read the image")

    # Search the user with the given user id
    user = User.query.filter(User.id == user_id).one_or_none()

    # The user if not found
    if user is None:
        abort(404, " Not Found: No user found with the given user id")

    #  Search for the image associated with the given user id
    image = db.session.query(Images).filter(
        User.id == Permissions.user_id, ).filter(
            Images.id == Permissions.image_id, ).filter(
                User.id == user_id, ).all()

    if image is not None:
        # Serialize the data for the response
        image_schema = ImageSchema(many=True)
        data = image_schema.dump(image)

        return data, 200
    else:
        # No image found for the given user
        abort(404, " Not Found: No images found")
Ejemplo n.º 12
0
def update_image(image_id):

    url = request.json["url"]

    # Get the image to update
    image = Image.query.filter(Image.id == image_id).one_or_none()

    # Check if we got a image
    if image is not None:

        image.url = url

        # Update the image
        db.session.merge(image)
        db.session.commit()

        # Serialize the data for the response
        image_schema = ImageSchema()
        data = image_schema.dump(image)
        return jsonify(data)

    # Otherwise, nope, didn't find that image
    else:
        abort(404, "Image not found for Id: {id} ".format(id=image_id))
Ejemplo n.º 13
0
def get_subject_n(subject, n):
    """
    subject: string
    n: integer

    return:: array of dictionaryies
    """

    # print('>>>', subject, n)

    if n > 10:
        n = 10

    images = Image.query.filter(Image.subject == subject).limit(n).all()
    return ImageSchema().dump(images, many='many')
Ejemplo n.º 14
0
def upload(user_id):
    """
    This function uploads an image
    :param user_id:   Id of user
    :return:          201 on success,with the user type
    """
    # Get the token info
    token_info = connexion.context['token_info']
    # Get the file from request body
    file = connexion.request.files['filename']

    # Allowing only the file size between 2 KB to 10 MB ,length of the filename to be between 6 to 100 characters
    #  Checking  the type of file is within the supported types
    # Checking if user_id,filename is not None or empty string
    if (user_id is None or user_id is "" or file is None
            or (file.filename is None)
            or (file.content_type not in supported_types) or
        (get_size(file) > MAX_IMAGE_SIZE or get_size(file) < MIN_IMAGE_SIZE)
            or (len(file.filename) > 100 or len(file.filename) < 6)):
        abort(400, "Bad Request: Please send a valid file")

    #  Check the token belongs to the authorized user
    if token_info['sub'] != str(user_id) and token_info['sub'] != ADMIN_USER:
        abort(
            403,
            "Forbidden: The given user doesnt have access to uoload an image")

    # Hash the filename to prevent attacks
    name = file.filename
    path = hashlib.sha224(name.encode('utf-8')).hexdigest()
    # Attach timestamp to the path of the file to help with the upload of files with the same name
    timestamp = int(time.time())
    path = path + str(timestamp)

    # check the user with the given user_id  to avoid conflicts
    user = User.query.filter(User.id == user_id).one_or_none()

    #  Return 404 if no user found
    if user is None:
        abort(404, f"Person not found for Id: {user_id}")

    # Build an image schema
    schema = ImageSchema()
    # build a copy of file type and change its name to the hash name
    image = file
    image.name = path
    image.admin_user = int(user_id)
    # Login using Firebase
    fireb_user = firebase.auth().sign_in_with_email_and_password(
        ADMIN_EMAIL, ADMIN_PASSWORD)
    tok = fireb_user['idToken']

    # Put the image in the firebase storage
    result = storage.child(path).put(image, tok)
    if result is None:
        abort(500,
              "Internal Server Error: the given image could not be stored ")

    # Store the download token returned from firebase
    download_token = result['downloadTokens']

    file_obj = {
        "image": path,
        "download_token": download_token,
        "admin_id": int(user_id)
    }

    # create a new image schema
    new_image_schema = schema.load(file_obj, session=db.session)

    # Add the new image to the user
    user.images.append(new_image_schema)
    failed = False
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        db.session.flush()
        failed = True

    if failed:
        # delete the image from firebase storage
        storage.delete(path)
        abort(500,
              "Internal Server Error: the given image could not be stored ")

    # Serialize and return the newly created image
    image = Images.query.order_by(
        Images.timestamp).filter(Images.image == path).one_or_none()

    # Serialize the data for the response
    image_schema = ImageSchema()
    data = image_schema.dump(image)

    return data, 201
Ejemplo n.º 15
0

connexion_app = connexion.App(__name__, specification_dir="./")
app = connexion_app.app
bcrypt = Bcrypt(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
connexion_app.add_api("api.yml")

# Setup for mail
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '******'
app.config['MAIL_PASSWORD'] = '******'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)

register_to_consul()

# dummy reference for migrations only
from models import User, Image, UserSchema, ImageSchema

image_schema = ImageSchema()
user_schema = UserSchema(
    exclude=['is_verified', 'password', 'verification_code'])

if __name__ == "__main__":
    connexion_app.run(host='0.0.0.0', port=5000, debug=True)