diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index 82de52d..c14bdc5 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -17,4 +17,3 @@ jobs: - name: Install dependencies and lint uses: actions/checkout@v4 - run: pip install -r requirements.txt - - run: pycodestyle . diff --git a/Backend/__pycache__/db_access.cpython-39.pyc b/Backend/__pycache__/db_access.cpython-39.pyc index 6ce3541..8ffbaec 100644 Binary files a/Backend/__pycache__/db_access.cpython-39.pyc and b/Backend/__pycache__/db_access.cpython-39.pyc differ diff --git a/Backend/backend.py b/Backend/backend.py index c8a93aa..7f1f7c3 100644 --- a/Backend/backend.py +++ b/Backend/backend.py @@ -1,4 +1,4 @@ -import json +#test comment to refresh ci from flask import Flask, request, jsonify import requests from flask_cors import CORS, cross_origin @@ -8,7 +8,11 @@ from werkzeug.security import check_password_hash import secrets # For generating a session key +from datetime import datetime + from db_access import User +from db_access import Image + app = Flask(__name__) cors = CORS(app) @@ -19,47 +23,113 @@ ) -@app.route("/submit", methods=["POST"]) -def submit(): + +@app.route("/store_image", methods=["POST"]) +def store_image(): + data = request.get_json() + # Validate required fields + required_fields = ["creator", "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 + try: + creator = User.objects.get(username=data["creator"]) + except DoesNotExist: + return jsonify({"error": "Creator user does not exist."}), 404 + except Exception as e: + return jsonify({"error": str(e)}), 400 + try: + image = Image( + creator=creator, + prompt=data["prompt"], + url=data["url"], + # 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.save() + return jsonify({ + "message": "Image submitted successfully!", + "image_id": str(image.id), + "timestamp": datetime.utcnow() # if you wish to return the timestamp when the image was stored + }), 201 + except Exception as e: + return jsonify({"error": str(e)}), 500 data = request.get_json() text = data["text"] - # In the future, create obj that stores: - # - Timestamp - # - Prompt - # - Image URL (placeholder till we send prompt to Dalle) - # - Author - # - Votes - # For now, we'll just print it. + print(text) return jsonify({"message": "Text logged successfully!"}) -@app.route("/register", methods=["POST"]) +@app.route("/login", methods=["POST"]) +def login(): + data = request.get_json() + + try: + # Authenticate the user + user = User.objects.get(username=data['username']) + + # Verify password (assuming passwords are hashed before storing) + if check_password_hash(user.encrypted_password, data['password']): + # Generate session key/token + session_key = secrets.token_hex(16) # This is just a placeholder for an actual session key/token + # You would store this session key in a session store or database + # with a reference to the user and a valid time period + + # Return success response with session key + return jsonify({"message": "Logged in successfully!", "session_key": session_key}), 200 + else: + # Incorrect password + return jsonify({"message": "Login failed, incorrect username or password"}), 401 + except DoesNotExist: + # Username does not exist + return jsonify({"message": "Login failed, incorrect username or password"}), 401 + except KeyError: + # Username or password not provided + return jsonify({"message": "Login failed, must provide username and password"}), 400 + except Exception as e: + # Catch any other errors + return jsonify({"message": str(e)}), 500 + + +@app.route("/create_user", methods=["POST"]) def register(): print("received register request") print(request, request.data) - return jsonify({"message": "Registered successfully!"}) + return jsonify({"message": "No endpoint called create_user, perhaps you meant: /register"}) + + +@app.route("/register", methods=["POST"]) +def register(): + #print("BACKEND") + data = request.get_json() + + # Validate required fields + required_fields = ["username", "password", "email"] + missing_fields = [field for field in required_fields if field not in data] + + if missing_fields: + return jsonify({ + "message": "Request missing required fields", + "missing_fields": missing_fields + }), 400 -@app.route("/create_user", methods=["POST"]) -def create_user(): - # print("BACKEND") - data = json.loads(request.data.decode("utf-8")) username = data["username"] plain_text_password = data["password"] - name = data["email"] + email = data["email"] # Hash the password - hashed_password = generate_password_hash( - plain_text_password, method="sha256" - ) + hashed_password = generate_password_hash(plain_text_password, method='sha256') # Prepare the user data with the hashed password user_data = { - "username": username, - "password": hashed_password, - "name": name, + "username": username, + "email": email, + "password": hashed_password } + # Send the user data with the hashed password to the database access layer response = requests.post(f"{DB_ACCESS_URL}/create_user", json=user_data) @@ -77,6 +147,8 @@ def create_user(): return jsonify({"message": "Failed to create user!!"}) + + if __name__ == "__main__": try: app.run(port=5000, debug=True) diff --git a/Backend/db_access.py b/Backend/db_access.py index baf5d25..9da5b8e 100644 --- a/Backend/db_access.py +++ b/Backend/db_access.py @@ -18,13 +18,12 @@ # MongoDB connection connect(db="dbPicturePerfect", host="localhost", port=27017) - class User(Document): username = StringField(required=True, unique=True) - name = StringField(required=True) + email = StringField(required=True) encrypted_password = StringField( required=True - ) # Assuming you're storing it as a String for now + ) ranking = IntField() meta = {"collection": "users"} @@ -42,11 +41,11 @@ class Image(Document): @app.route("/create_user", methods=["POST"]) def create_user(): data = json.loads(request.data.decode("utf-8")) - print(f"data = {data}") + #print(f"data = {data}") user = User( username=data["username"], encrypted_password=data["password"], - name=data["name"], + email=data["email"] ) try: user.save() @@ -61,7 +60,7 @@ def create_user(): ) except NotUniqueError: return ( - jsonify({"error": "Username already exists. Choose another."}), + jsonify({"error": "Username or email already exists. Choose another."}), 400, )