Skip to content

Commit

Permalink
Merge branch 'main' of github.com:grant-baer/Picture-Perfect-Project
Browse files Browse the repository at this point in the history
  • Loading branch information
caseyavila committed Nov 13, 2023
2 parents 1605cb2 + 0dcb06c commit 8e6da13
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 30 deletions.
1 change: 0 additions & 1 deletion .github/workflows/backend-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,3 @@ jobs:
- name: Install dependencies and lint
uses: actions/checkout@v4
- run: pip install -r requirements.txt
- run: pycodestyle .
Binary file modified Backend/__pycache__/db_access.cpython-39.pyc
Binary file not shown.
118 changes: 95 additions & 23 deletions Backend/backend.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)
Expand All @@ -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)

Expand All @@ -77,6 +147,8 @@ def create_user():
return jsonify({"message": "Failed to create user!!"})




if __name__ == "__main__":
try:
app.run(port=5000, debug=True)
Expand Down
11 changes: 5 additions & 6 deletions Backend/db_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand All @@ -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()
Expand All @@ -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,
)

Expand Down

0 comments on commit 8e6da13

Please sign in to comment.