Skip to content

Commit

Permalink
Merge pull request #30 from grant-baer/wiring_up_db_to_backend
Browse files Browse the repository at this point in the history
Wiring up db to backend
  • Loading branch information
gp-sb authored Nov 13, 2023
2 parents bca45d5 + b065a5f commit a511329
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 22 deletions.
Binary file modified Backend/__pycache__/db_access.cpython-39.pyc
Binary file not shown.
114 changes: 97 additions & 17 deletions Backend/backend.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import json
from flask import Flask, request, jsonify
import requests
from flask_cors import CORS, cross_origin
Expand All @@ -8,7 +7,11 @@
from werkzeug.security import check_password_hash
import secrets # For generating a session key

from db_access import User
from datetime import datetime

from db_access import User
from db_access import Image


app = Flask(__name__)
cors = CORS(app)
Expand All @@ -19,8 +22,41 @@
)


@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:
Expand All @@ -34,32 +70,74 @@ def submit():
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 +155,8 @@ def create_user():
return jsonify({"message": "Failed to create user!!"})




if __name__ == "__main__":
try:
app.run(port=5000, debug=True)
Expand Down
12 changes: 7 additions & 5 deletions Backend/db_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@

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 +44,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 +63,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 a511329

Please sign in to comment.