From a5127cefd651796e08a694e179db7f48e5d5eb35 Mon Sep 17 00:00:00 2001 From: Grant <81586842+grant-baer@users.noreply.github.com> Date: Mon, 4 Dec 2023 12:19:10 -0800 Subject: [PATCH] edited db to work with image_store worked on backend to talk to db_access. Still need to confirm detch_portfolio works as well as make tests for new db_access functions. --- Backend/backend.py | 84 +++++++++++++++++++++++++++++--------------- Backend/db_access.py | 65 ++++++++++++++++++++++++++++++++-- 2 files changed, 117 insertions(+), 32 deletions(-) diff --git a/Backend/backend.py b/Backend/backend.py index a51ae61..9b1dc78 100644 --- a/Backend/backend.py +++ b/Backend/backend.py @@ -15,6 +15,7 @@ from db_access import User from db_access import Image from db_access import get_user, create_user +from db_access import get_image, create_image app = Flask(__name__) @@ -30,7 +31,10 @@ @app.route("/generate_image", methods=["POST"]) +@jwt_required() def generate_image(): + current_user = get_jwt_identity() + data = request.get_json() url = "https://imagegolf.io/api/generate" url_data = {"inputValue": data["prompt"]} @@ -41,45 +45,64 @@ def generate_image(): @app.route("/store_image", methods=["POST"]) +@jwt_required() def store_image(): + current_user = get_jwt_identity() # Gets the identity of the current user + data = request.get_json() # Validate required fields - required_fields = ["creator", "prompt", "url"] + required_fields = ["prompt", "url"] for field in required_fields: if field not in data: return jsonify({"error": f"Missing field: {field}"}), 400 - # Retrieve creator user by user + + # Prepare the data for creating an image + image_data = { + "creator": current_user, # Assuming the creator is the logged-in user + "prompt": data["prompt"], + "url": data["url"] + } + + # Call the create_image function from db_access + response = create_image(image_data) + + # Handle the response + if response.status_code == 201: + print("Image created successfully!") + return jsonify({"message": "Image submitted successfully!"}), 201 + else: + print(f"Failed to create image: {response.message}") + return jsonify({"message": response.message}), response.status_code + + +@app.route("/fetch_portfolio", methods=["GET"]) +@jwt_required() +def fetch_portfolio(): + current_user_username = get_jwt_identity() # Get the username from the JWT token + try: - creator = User.objects.get(username=data["creator"]) + # Retrieve the user by username + user = User.objects.get(username=current_user_username) + + # Fetch all images created by this user + user_images = Image.objects(creator=user) + + # Format the response with the list of images + portfolio = [{ + "image_id": str(image.id), + "prompt": image.prompt, + "url": image.url, + "creator": user + } for image in user_images] + + return jsonify(portfolio), 200 + except DoesNotExist: - return jsonify({"error": "Creator user does not exist."}), 404 - except Exception as e: - return jsonify({"error": str(e)}), 400 - try: - # votes default to 0 as defined in the Image class - # timestamp can be added if we want to have more variation - # between similar objects - image = Image(creator=creator, prompt=data["prompt"], url=data["url"]) - image.save() - return ( - jsonify( - { - "message": "Image submitted successfully!", - "image_id": str(image.id), - # if you wish to return the timestamp when - # the image was stored - "timestamp": datetime.utcnow(), - } - ), - 201, - ) + # If the user is not found + return jsonify({"error": "User not found"}), 404 except Exception as e: + # Handle any other exceptions return jsonify({"error": str(e)}), 500 - data = request.get_json() - text = data["text"] - - print(text) - return jsonify({"message": "Text logged successfully!"}) @app.route("/login", methods=["POST"]) @@ -140,6 +163,7 @@ def login(): @app.route("/register", methods=["POST"]) def register(): + data = request.get_json() # Validate required fields @@ -160,6 +184,7 @@ def register(): username = data["username"] plain_text_password = data["password"] email = data["email"] + portfolio = [] #initialized to [] # Hash the password hashed_password = generate_password_hash( @@ -171,6 +196,7 @@ def register(): "username": username, "email": email, "password": hashed_password, + "portfolio": portfolio, } response = get_user(user_data) if response.status_code == 401: diff --git a/Backend/db_access.py b/Backend/db_access.py index 82e3c62..3a40591 100644 --- a/Backend/db_access.py +++ b/Backend/db_access.py @@ -4,6 +4,7 @@ Document, StringField, IntField, + ListField, ReferenceField, NotUniqueError, ) @@ -13,9 +14,10 @@ import secrets from mongoengine.errors import DoesNotExist -# from dotenv import load_dotenv -# load_dotenv() +from dotenv import load_dotenv + +load_dotenv() import os @@ -37,6 +39,7 @@ class User(Document): email = StringField(required=True) encrypted_password = StringField(required=True) ranking = IntField() + portfolio = ListField(ReferenceField('Image')) # List of image references meta = {"collection": "users"} @@ -45,7 +48,6 @@ class Image(Document): creator = ReferenceField(User, required=True) url = StringField(required=True) prompt = StringField(required=True) - votes = IntField(default=0) meta = {"collection": "images"} @@ -56,6 +58,8 @@ def create_user(data): username=data["username"], encrypted_password=data["password"], email=data["email"], + portfolio=[] # Initialize an empty portfolio + ) try: user.save() @@ -86,3 +90,58 @@ def get_user(data): "User credentials are unique.", 200, ) + + +def create_image(data): + try: + # Retrieve the user by username + creator = User.objects.get(username=data["creator"]) + + # Create and save the image + image = Image( + creator=creator, + prompt=data["prompt"], + url=data["url"] + ) + image.save() + + # Optionally, you can also append this image to the user's portfolio here + creator.update(push__portfolio=image) + + return Response("Image created successfully!", 201) + except DoesNotExist: + return Response("Creator user does not exist.", 404) + except Exception as e: + return Response(f"Internal server error {e}", 500) + + +def get_image(image_id): + try: + image = Image.objects.get(id=image_id) + return jsonify({ + "creator": str(image.creator.id), + "prompt": image.prompt, + "url": image.url, + }), 200 + except DoesNotExist: + return Response("Image not found.", 404) + except Exception as e: + return Response(f"Internal server error {e}", 500) + + +def get_portfolio(username): + try: + user = User.objects.get(username=username) + images = Image.objects(creator=user) + + return jsonify([ + { + "image_id": str(image.id), + "prompt": image.prompt, + "url": image.url, + } for image in images + ]), 200 + except DoesNotExist: + return Response("User not found.", 404) + except Exception as e: + return Response(f"Internal server error {e}", 500)