MAJOR: Restructured backend Flask application moved all non-routes into utils, renamed routes to not prefix get, created middleware.py to replace utils.py within blueprints

This commit is contained in:
JustIceO7
2025-02-08 14:35:46 +00:00
parent ae623eee0d
commit e6b8ad9b9e
16 changed files with 631 additions and 550 deletions

View File

45
web_server/utils/auth.py Normal file
View File

@@ -0,0 +1,45 @@
from database.database import Database
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
from typing import Optional
from dotenv import load_dotenv
from os import getenv
from werkzeug.security import generate_password_hash
load_dotenv()
serializer = URLSafeTimedSerializer(getenv("AUTH_SECRET_KEY"))
def generate_token(email, salt_value) -> str:
"""
Creates a token for password reset
"""
token = serializer.dumps(email, salt=salt_value)
return token
def verify_token(token: str, salt_value) -> Optional[str]:
"""
Given a token, verifies and decodes it into an email
"""
try:
email = serializer.loads(token, salt=salt_value, max_age=3600)
return email
except SignatureExpired:
# Token expired
print("Token has expired", flush=True)
return None
except BadSignature:
# Invalid token
print("Token is invalid", flush=True)
return None
def reset_password(new_password: str, email: str) -> bool:
"""
Given email and new password reset the password for a given user
"""
with Database() as db:
db.execute("""
UPDATE users
SET password = ?
WHERE email = ?
""", (generate_password_hash(new_password), email))
return True

83
web_server/utils/email.py Normal file
View File

@@ -0,0 +1,83 @@
import smtplib
from email.mime.text import MIMEText
from os import getenv
from dotenv import load_dotenv
from utils.auth import generate_token
from secrets import token_hex
import redis
redis_url = "redis://redis:6379/1"
r = redis.from_url(redis_url, decode_responses=True)
load_dotenv()
def send_email(email, func) -> None:
"""
Send a verification email to the user.
"""
# Setup the sender email details
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
SMTP_EMAIL = getenv("EMAIL")
SMTP_PASSWORD = getenv("EMAIL_PASSWORD")
# Setup up the receiver details
body = func()
msg = MIMEText(body, "html")
msg["Subject"] = "Reset Gander Login"
msg["From"] = SMTP_EMAIL
msg["To"] = email
# Send the email using smtplib
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as smtp:
try:
smtp.starttls() # TLS handshake to start the connection
smtp.login(SMTP_EMAIL, SMTP_PASSWORD)
smtp.ehlo()
smtp.send_message(msg)
except TimeoutError:
print("Server timed out", flush=True)
except Exception as e:
print("Error: ", e, flush=True)
def forgot_password_body(email):
"""
Handles the creation of the email body for resetting password
"""
salt = token_hex(32)
token = generate_token(email, salt)
url = getenv("VITE_API_URL")
r.setex(token, 3600, salt)
full_url = url + "/reset_password/" + token
content = f"""
<html>
<head>
<meta charset="UTF-8">
<title>Password Reset</title>
<style>
body {{ font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px; text-align: center; }}
.container {{ max-width: 400px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); }}
.btn {{ display: inline-block; padding: 10px 20px; color: white; background-color: #007bff; text-decoration: none; border-radius: 5px; }}
.btn:hover {{ background-color: #0056b3; }}
p {{ color: #333; }}
</style>
</head>
<body>
<div class="container">
<h1>Gander</h1>
<h2>Password Reset Request</h2>
<p>Click the button below to reset your password. This link is valid for 1 hour.</p>
<a href="{full_url}" class="btn">Reset Password</a>
</div>
</body>
</html>
"""
return content

View File

@@ -0,0 +1,97 @@
from database.database import Database
from typing import Optional, List
def get_user_preferred_category(user_id: int) -> Optional[int]:
"""
Queries user_preferences database to find users favourite streaming category and returns the category
"""
with Database() as db:
category = db.fetchone("""
SELECT category_id
FROM user_preferences
WHERE user_id = ?
ORDER BY favourability DESC
LIMIT 1
""", (user_id,))
return category["category_id"] if category else None
def get_followed_categories_recommendations(user_id: int, no_streams: int = 4) -> Optional[List[dict]]:
"""
Returns top streams given a user's category following
"""
with Database() as db:
streams = db.fetchall("""
SELECT u.user_id, title, u.username, num_viewers, category_name
FROM streams
JOIN users u ON streams.user_id = u.user_id
JOIN categories ON streams.category_id = categories.category_id
WHERE categories.category_id IN (SELECT category_id FROM followed_categories WHERE user_id = ?)
ORDER BY num_viewers DESC
LIMIT ?;
""", (user_id, no_streams))
return streams
def get_streams_based_on_category(category_id: int, no_streams: int = 4) -> Optional[List[dict]]:
"""
Queries stream database to get top most viewed streams based on given category
"""
with Database() as db:
streams = db.fetchall("""
SELECT u.user_id, title, username, num_viewers, c.category_name
FROM streams s
JOIN users u ON s.user_id = u.user_id
JOIN categories c ON s.category_id = c.category_id
WHERE c.category_id = ?
ORDER BY num_viewers DESC
LIMIT ?
""", (category_id, no_streams))
return streams
def get_highest_view_streams(no_streams: int = 4) -> Optional[List[dict]]:
"""
Return a list of live streams by number of viewers
"""
with Database() as db:
data = db.fetchall("""
SELECT u.user_id, username, title, num_viewers, category_name
FROM streams
JOIN users u ON streams.user_id = u.user_id
JOIN categories ON streams.category_id = categories.category_id
ORDER BY num_viewers DESC
LIMIT ?;
""", (no_streams,))
return data
def get_highest_view_categories(no_categories: int = 4) -> Optional[List[dict]]:
"""
Returns a list of top most popular categories
"""
with Database() as db:
categories = db.fetchall("""
SELECT categories.category_id, categories.category_name, SUM(streams.num_viewers) AS num_viewers
FROM streams
JOIN categories ON streams.category_id = categories.category_id
GROUP BY categories.category_name
ORDER BY SUM(streams.num_viewers) DESC
LIMIT ?;
""", (no_categories,))
return categories
def get_user_category_recommendations(user_id: int) -> Optional[List[dict]]:
"""
Queries user_preferences database to find users top 5 favourite streaming category and returns the category
"""
with Database() as db:
categories = db.fetchall("""
SELECT categories.category_id, categories.category_name
FROM categories
JOIN user_preferences ON categories.category_id = user_preferences.category_id
WHERE user_id = ?
ORDER BY favourability DESC
LIMIT 5
""", (user_id,))
return categories

View File

@@ -1,5 +1,7 @@
from database.database import Database
from typing import Optional
import os, subprocess
from typing import Optional, List
def get_streamer_live_status(user_id: int):
"""
@@ -14,6 +16,72 @@ def get_streamer_live_status(user_id: int):
return is_live
def get_followed_live_streams(user_id: int) -> Optional[List[dict]]:
"""
Searches for streamers who the user followed which are currently live
Returns a list of live streams with the streamer's user id, stream title, and number of viewers
"""
with Database() as db:
live_streams = db.fetchall("""
SELECT users.user_id, streams.title, streams.num_viewers, users.username
FROM streams JOIN users
ON streams.user_id = users.user_id
WHERE users.user_id IN
(SELECT followed_id FROM follows WHERE user_id = ?)
AND users.is_live = 1;
""", (user_id,))
return live_streams
def get_current_stream_data(user_id: int) -> Optional[dict]:
"""
Returns data of the most recent stream by a streamer
"""
with Database() as db:
most_recent_stream = db.fetchone("""
SELECT s.user_id, u.username, s.title, s.start_time, s.num_viewers, c.category_name
FROM streams AS s
JOIN categories AS c ON s.category_id = c.category_id
JOIN users AS u ON s.user_id = u.user_id
WHERE u.user_id = ?
""", (user_id,))
return most_recent_stream
def get_category_id(category_name: str) -> Optional[int]:
"""
Returns the category_id given a category name
"""
with Database() as db:
data = db.fetchone("""
SELECT category_id
FROM categories
WHERE category_name = ?;
""", (category_name,))
return data['category_id'] if data else None
def get_vod(vod_id: int) -> dict:
"""
Returns data of a streamers vod
"""
with Database() as db:
vod = db.fetchone("""SELECT * FROM vods WHERE vod_id = ?;""", (vod_id,))
return vod
def get_latest_vod(user_id: int):
"""
Returns data of the most recent stream by a streamer
"""
with Database() as db:
latest_vod = db.fetchone("""SELECT * FROM vods WHERE user_id = ? ORDER BY vod_id DESC LIMIT 1;""", (user_id,))
return latest_vod
def get_user_vods(user_id: int):
"""
Returns data of all vods by a streamer
"""
with Database() as db:
vods = db.fetchall("""SELECT * FROM vods WHERE user_id = ?;""", (user_id,))
return vods
def generate_thumbnail(user_id: int) -> None:
"""
@@ -42,3 +110,55 @@ def generate_thumbnail(user_id: int) -> None:
subprocess.run(thumbnail_command)
def get_stream_tags(user_id: int) -> Optional[List[str]]:
"""
Given a stream return tags associated with the user's stream
"""
with Database() as db:
tags = db.fetchall("""
SELECT tag_name
FROM tags
JOIN stream_tags ON tags.tag_id = stream_tags.tag_id
WHERE user_id = ?;
""", (user_id,))
return tags
def get_vod_tags(vod_id: int):
"""
Given a vod return tags associated with the vod
"""
with Database() as db:
tags = db.fetchall("""
SELECT tag_name
FROM tags
JOIN vod_tags ON tags.tag_id = vod_tags.tag_id
WHERE vod_id = ?;
""", (vod_id,))
return tags
def transfer_stream_to_vod(user_id: int):
"""
Deletes stream from stream table and moves it to VoD table
TODO: Add functionaliy to save stream permanently
"""
with Database() as db:
stream = db.fetchone("""
SELECT * FROM streams WHERE user_id = ?;
""", (user_id,))
if not stream:
return None
## TODO: calculate length in seconds, currently using temp value
db.execute("""
INSERT INTO vods (user_id, title, datetime, category_id, length, views)
VALUES (?, ?, ?, ?, ?, ?);
""", (stream["user_id"], stream["title"], stream["datetime"], stream["category_id"], 10, stream["num_viewers"]))
db.execute("""
DELETE FROM streams WHERE user_id = ?;
""", (user_id,))
return True

View File

@@ -1,14 +1,72 @@
from database.database import Database
from typing import Optional, List
from datetime import datetime
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
from os import getenv
from werkzeug.security import generate_password_hash
from dateutil import parser
from dotenv import load_dotenv
load_dotenv()
serializer = URLSafeTimedSerializer(getenv("AUTH_SECRET_KEY"))
def get_user_id(username: str) -> Optional[int]:
"""
Returns user_id associated with given username
"""
with Database() as db:
data = db.fetchone("""
SELECT user_id
FROM users
WHERE username = ?
""", (username,))
return data['user_id'] if data else None
def get_username(user_id: str) -> Optional[str]:
"""
Returns username associated with given user_id
"""
with Database() as db:
data = db.fetchone("""
SELECT username
FROM user
WHERE user_id = ?
""", (user_id,))
return data['username'] if data else None
def get_session_info_email(email: str) -> dict:
"""
Returns username and user_id given email
"""
with Database as db:
session_info = db.fetchone("""
SELECT user_id, username
FROM user
WHERE email = ?
""", (email,))
return session_info
def is_user_partner(user_id: int) -> bool:
"""
Returns True if user is a partner, else False
"""
with Database() as db:
data = db.fetchone("""
SELECT is_partnered
FROM users
WHERE user_id = ?
""", (user_id,))
return bool(data)
def is_subscribed(user_id: int, subscribed_to_id: int) -> bool:
"""
Returns True if user is subscribed to a streamer, else False
"""
with Database() as db:
result = db.fetchone("""
SELECT *
FROM subscribes
WHERE user_id = ?
AND subscribed_id = ?
AND expires > ?;
""", (user_id, subscribed_to_id, datetime.now()))
print(result)
if result:
return True
return False
def is_following(user_id: int, followed_id: int) -> bool:
"""
@@ -51,40 +109,56 @@ def unfollow(user_id: int, followed_id: int):
""", (user_id, followed_id))
return {"success": True}
def generate_token(email, salt_value) -> str:
"""
Creates a token for password reset
"""
token = serializer.dumps(email, salt=salt_value)
return token
def verify_token(token: str, salt_value) -> Optional[str]:
def subscription_expiration(user_id: int, subscribed_id: int) -> int:
"""
Given a token, verifies and decodes it into an email
"""
try:
email = serializer.loads(token, salt=salt_value, max_age=3600)
return email
except SignatureExpired:
# Token expired
print("Token has expired", flush=True)
return None
except BadSignature:
# Invalid token
print("Token is invalid", flush=True)
return None
def reset_password(new_password: str, email: str) -> bool:
"""
Given email and new password reset the password for a given user
Returns the amount of time left until user subscription to a streamer ends
"""
with Database() as db:
db.execute("""
UPDATE users
SET password = ?
WHERE email = ?
""", (generate_password_hash(new_password), email))
return True
data = db.fetchone("""
SELECT expires
FROM subscribes
WHERE user_id = ?
AND subscribed_id = ?
AND expires > ?
""", (user_id, subscribed_id, datetime.now()))
if data:
expiration_date = data["expires"]
remaining_time = (parser.parse(expiration_date) - datetime.now()).seconds
return remaining_time
return 0
def get_email(user_id: int) -> Optional[str]:
with Database() as db:
email = db.fetchone("""
SELECT email
FROM users
WHERE user_id = ?
""", (user_id,))
return email["email"] if email else None
def get_followed_streamers(user_id: int) -> Optional[List[dict]]:
"""
Returns a list of streamers who the user follows
"""
with Database() as db:
followed_streamers = db.fetchall("""
SELECT user_id, username
FROM users
WHERE user_id IN (SELECT followed_id FROM follows WHERE user_id = ?);
""", (user_id,))
return followed_streamers
def get_user(user_id: int) -> Optional[dict]:
"""
Returns information about a user from user_id
"""
with Database() as db:
data = db.fetchone("""
SELECT user_id, username, bio, num_followers, is_partnered, is_live FROM users
WHERE user_id = ?;
""", (user_id,))
return data

75
web_server/utils/utils.py Normal file
View File

@@ -0,0 +1,75 @@
from database.database import Database
from typing import Optional, List
from re import match
def get_all_categories() -> Optional[List[dict]]:
"""
Returns all possible streaming categories
"""
with Database() as db:
all_categories = db.fetchall("SELECT * FROM categories")
return all_categories
def get_all_tags() -> Optional[List[dict]]:
"""
Returns all possible streaming tags
"""
with Database() as db:
all_tags = db.fetchall("SELECT * FROM tags")
return all_tags
def get_most_popular_category() -> Optional[List[dict]]:
"""
Returns the most popular category based on live stream viewers
"""
with Database() as db:
category = db.fetchone("""
SELECT categories.category_id, categories.category_name
FROM streams
JOIN categories ON streams.category_id = categories.category_id
WHERE streams.isLive = 1
GROUP BY categories.category_name
ORDER BY SUM(streams.num_viewers) DESC
LIMIT 1;
""")
return category
def sanitize(user_input: str, input_type="username") -> str:
"""
Sanitizes user input based on the specified input type.
`input_type`: The type of input to sanitize (e.g., 'username', 'email', 'password').
"""
# Strip leading and trailing whitespace
sanitised_input = user_input.strip()
# Define allowed patterns and length constraints for each type
rules = {
"username": {
"pattern": r"^[a-zA-Z0-9_]+$", # Alphanumeric + underscores
"min_length": 3,
"max_length": 50,
},
"email": {
"pattern": r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", # Standard email regex
"min_length": 5,
"max_length": 128,
},
"password": {
"pattern": r"^[\S]+$", # Non-whitespace characters only
"min_length": 8,
"max_length": 256,
},
}
# Get the validation rules for the specified type
r = rules.get(input_type)
if not r or \
not (r["min_length"] <= len(sanitised_input) <= r["max_length"]) or \
not match(r["pattern"], sanitised_input):
raise ValueError("Unaccepted character or length in input")
return sanitised_input