Skip to content

Commit

Permalink
Formatting changes
Browse files Browse the repository at this point in the history
  • Loading branch information
nnayk committed Nov 29, 2023
1 parent fe4cbb9 commit 3da1d99
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 45 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,5 @@ next-env.d.ts

venv/
.*.swp

.env
103 changes: 64 additions & 39 deletions Backend/backend.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from flask import Flask, request, jsonify
import requests
from flask_cors import CORS, cross_origin
Expand All @@ -17,18 +18,16 @@
cors = CORS(app)
app.config["CORS_HEADERS"] = "Content-Type"

DB_ACCESS_URL = (
"http://127.0.0.1:5001" # This is where db_access.py is running.
DB_ACCESS_URL = ( # This is where db_access.py is running.
"http://127.0.0.1:5001"
)


@app.route("/generate_image", methods=["POST"])
def generate_image():
data = request.get_json()
url = "https://imagegolf.io/api/generate"
url_data = {
"inputValue": data["prompt"]
}
url_data = {"inputValue": data["prompt"]}

r = requests.post(url, json=url_data)

Expand All @@ -54,17 +53,19 @@ def store_image():
# 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 = 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
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,
)
except Exception as e:
return jsonify({"error": str(e)}), 500
data = request.get_json()
Expand All @@ -80,36 +81,50 @@ def login():

try:
# Authenticate the user
user = User.objects.get(username=data['username'])
user = User.objects.get(username=data["username"])

# Verify password (assuming passwords are hashed before storing)
if check_password_hash(user.encrypted_password, data['password']):
if check_password_hash(user.encrypted_password, data["password"]):
# Generate session key/token
# This is just a placeholder for an actual session key/token
session_key = secrets.token_hex(16)
# 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
return (
jsonify(
{
"message": "Logged in successfully!",
"session_key": session_key,
}
),
200,
)
else:
# Incorrect password
return jsonify({
"message": "Login failed, incorrect username or password"
}), 401
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
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
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
Expand All @@ -119,8 +134,12 @@ def login():
def create_user():
print("received register request")
print(request, request.data)
return jsonify({"""message": "No endpoint called create_user,
perhaps you meant: /register"""})
return jsonify(
{
"""message": "No endpoint called create_user,
perhaps you meant: /register"""
}
)


@app.route("/register", methods=["POST"])
Expand All @@ -132,24 +151,30 @@ def register():
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
return (
jsonify(
{
"message": "Request missing required fields",
"missing_fields": missing_fields,
}
),
400,
)

username = data["username"]
plain_text_password = data["password"]
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,
"email": email,
"password": hashed_password
"password": hashed_password,
}

# Send the user data with the hashed password to the database access layer
Expand Down
45 changes: 39 additions & 6 deletions Backend/db_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import secrets
from mongoengine.errors import DoesNotExist
from dotenv import load_dotenv

load_dotenv()

import os
Expand All @@ -27,9 +28,7 @@
class User(Document):
username = StringField(required=True, unique=True)
email = StringField(required=True)
encrypted_password = StringField(
required=True
)
encrypted_password = StringField(required=True)
ranking = IntField()

meta = {"collection": "users"}
Expand All @@ -44,13 +43,43 @@ class Image(Document):
meta = {"collection": "images"}


@app.route("/create_test_user", methods=["POST"])
def create_test_user():
user = User(
username="bob",
encrypted_password="pwd",
email="bob@gmail.com",
)
try:
user.save()
return (
jsonify(
{
"message": "User created successfully!",
"user_id": str(user.id),
}
),
201,
)
except NotUniqueError:
return (
jsonify(
{
"error": """Username or email already exists.
Choose another."""
}
),
400,
)


@app.route("/create_user", methods=["POST"])
def create_user():
data = json.loads(request.data.decode("utf-8"))
user = User(
username=data["username"],
encrypted_password=data["password"],
email=data["email"]
email=data["email"],
)
try:
user.save()
Expand All @@ -65,8 +94,12 @@ def create_user():
)
except NotUniqueError:
return (
jsonify({"error": """Username or email already exists.
Choose another."""}),
jsonify(
{
"error": """Username or email already exists.
Choose another."""
}
),
400,
)

Expand Down

0 comments on commit 3da1d99

Please sign in to comment.