diff --git a/Backend/backend.py b/Backend/backend.py index fed8261..5d29986 100644 --- a/Backend/backend.py +++ b/Backend/backend.py @@ -18,7 +18,7 @@ from db_access import User from db_access import Image -from db_access import check_user, create_user, db_connect +from db_access import check_user, create_user, db_connect, get_image, create_image app = Flask(__name__) @@ -34,7 +34,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"]} @@ -79,45 +82,64 @@ def update_image_elo(): @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"]) @@ -187,6 +209,7 @@ def login(): @app.route("/register", methods=["POST"]) def register(): + data = request.get_json() # Validate required fields @@ -207,6 +230,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( @@ -218,6 +242,7 @@ def register(): "username": username, "email": email, "password": hashed_password, + "portfolio": portfolio, } response = check_user(user_data) if response.status_code == 401: diff --git a/Backend/db_access.py b/Backend/db_access.py index 81b7ecf..b994ebc 100644 --- a/Backend/db_access.py +++ b/Backend/db_access.py @@ -5,6 +5,7 @@ Document, StringField, IntField, + ListField, ReferenceField, NotUniqueError, ) @@ -12,8 +13,10 @@ import secrets from mongoengine.errors import DoesNotExist + from dotenv import load_dotenv + load_dotenv() app = Flask(__name__) @@ -37,6 +40,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 +49,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 +59,8 @@ def create_user(data): username=data["username"], encrypted_password=data["password"], email=data["email"], + portfolio=[] # Initialize an empty portfolio + ) try: user.save() @@ -82,3 +87,58 @@ def check_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)