Update: remove unused imports, added better comments and refactored for all blueprints
This commit is contained in:
@@ -1,16 +1,27 @@
|
|||||||
from flask import Flask
|
from flask import Flask
|
||||||
# from flask_wtf.csrf import CSRFProtect, generate_csrf
|
|
||||||
from flask_session import Session
|
from flask_session import Session
|
||||||
from blueprints.utils import logged_in_user
|
|
||||||
from flask_cors import CORS
|
from flask_cors import CORS
|
||||||
import os
|
from blueprints.utils import logged_in_user
|
||||||
|
# from flask_wtf.csrf import CSRFProtect, generate_csrf
|
||||||
|
|
||||||
|
from blueprints.authentication import auth_bp
|
||||||
|
from blueprints.stripe import stripe_bp
|
||||||
|
from blueprints.user import user_bp
|
||||||
|
from blueprints.streams import stream_bp
|
||||||
|
from blueprints.chat import chat_bp, socketio
|
||||||
|
|
||||||
|
from os import getenv
|
||||||
|
|
||||||
# csrf = CSRFProtect()
|
# csrf = CSRFProtect()
|
||||||
|
|
||||||
|
|
||||||
def create_app():
|
def create_app():
|
||||||
|
"""
|
||||||
|
Set up the flask app by registering all the blueprints and configuring
|
||||||
|
the settings. Also create a CSRF token to prevent Cross-site Request Forgery.
|
||||||
|
And setup web sockets to be used throughout the project.
|
||||||
|
"""
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.config["SECRET_KEY"] = os.getenv("FLASK_SECRET_KEY")
|
app.config["SECRET_KEY"] = getenv("FLASK_SECRET_KEY")
|
||||||
app.config["SESSION_PERMANENT"] = False
|
app.config["SESSION_PERMANENT"] = False
|
||||||
app.config["SESSION_TYPE"] = "filesystem"
|
app.config["SESSION_TYPE"] = "filesystem"
|
||||||
#! ↓↓↓ For development purposes only - Allow cross-origin requests for the frontend
|
#! ↓↓↓ For development purposes only - Allow cross-origin requests for the frontend
|
||||||
@@ -25,16 +36,9 @@ def create_app():
|
|||||||
# return jsonify({'csrf_token': generate_csrf()}), 200
|
# return jsonify({'csrf_token': generate_csrf()}), 200
|
||||||
|
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
from blueprints.authentication import auth_bp
|
|
||||||
from blueprints.main import main_bp
|
|
||||||
from blueprints.stripe import stripe_bp
|
|
||||||
from blueprints.user import user_bp
|
|
||||||
from blueprints.streams import stream_bp
|
|
||||||
from blueprints.chat import chat_bp, socketio
|
|
||||||
|
|
||||||
# Registering Blueprints
|
# Registering Blueprints
|
||||||
app.register_blueprint(auth_bp)
|
app.register_blueprint(auth_bp)
|
||||||
app.register_blueprint(main_bp)
|
|
||||||
app.register_blueprint(stripe_bp)
|
app.register_blueprint(stripe_bp)
|
||||||
app.register_blueprint(user_bp)
|
app.register_blueprint(user_bp)
|
||||||
app.register_blueprint(stream_bp)
|
app.register_blueprint(stream_bp)
|
||||||
|
|||||||
@@ -10,17 +10,20 @@ auth_bp = Blueprint("auth", __name__)
|
|||||||
@auth_bp.route("/signup", methods=["POST"])
|
@auth_bp.route("/signup", methods=["POST"])
|
||||||
@cross_origin(supports_credentials=True)
|
@cross_origin(supports_credentials=True)
|
||||||
def signup():
|
def signup():
|
||||||
|
"""
|
||||||
|
Route that allows a user to sign up by providing a `username`, `email` and `password`.
|
||||||
|
"""
|
||||||
|
# ensure a JSON request is made to contact this route
|
||||||
if not request.is_json:
|
if not request.is_json:
|
||||||
return jsonify({"message": "Expected JSON data"}), 400
|
return jsonify({"message": "Expected JSON data"}), 400
|
||||||
|
|
||||||
|
# Extract data from request via JSON
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
|
|
||||||
# Extract data from request
|
|
||||||
username = data.get('username')
|
username = data.get('username')
|
||||||
email = data.get('email')
|
email = data.get('email')
|
||||||
password = data.get('password')
|
password = data.get('password')
|
||||||
|
|
||||||
# Basic server-side validation
|
# Validation - ensure all fields exist, users cannot have an empty field
|
||||||
if not all([username, email, password]):
|
if not all([username, email, password]):
|
||||||
fields = ["username", "email", "password"]
|
fields = ["username", "email", "password"]
|
||||||
for x in fields:
|
for x in fields:
|
||||||
@@ -32,7 +35,7 @@ def signup():
|
|||||||
"message": "Missing required fields"
|
"message": "Missing required fields"
|
||||||
}), 400
|
}), 400
|
||||||
|
|
||||||
# Sanitize the inputs
|
# Sanitize the inputs - helps to prevent SQL injection
|
||||||
try:
|
try:
|
||||||
username = sanitizer(username, "username")
|
username = sanitizer(username, "username")
|
||||||
email = sanitizer(email, "email")
|
email = sanitizer(email, "email")
|
||||||
@@ -49,7 +52,7 @@ def signup():
|
|||||||
cursor = db.create_connection()
|
cursor = db.create_connection()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Check for duplicate email/username
|
# Check for duplicate email/username, no two users can have the same
|
||||||
dup_email = cursor.execute(
|
dup_email = cursor.execute(
|
||||||
"SELECT * FROM users WHERE email = ?",
|
"SELECT * FROM users WHERE email = ?",
|
||||||
(email,)
|
(email,)
|
||||||
@@ -74,7 +77,7 @@ def signup():
|
|||||||
"message": "Username already taken"
|
"message": "Username already taken"
|
||||||
}), 400
|
}), 400
|
||||||
|
|
||||||
# Create new user
|
# Create new user once input is validated
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
"""INSERT INTO users
|
"""INSERT INTO users
|
||||||
(username, password, email, num_followers, bio)
|
(username, password, email, num_followers, bio)
|
||||||
@@ -89,7 +92,7 @@ def signup():
|
|||||||
)
|
)
|
||||||
db.commit_data()
|
db.commit_data()
|
||||||
|
|
||||||
# Create session for new user
|
# Create session for new user, to avoid them having unnecessary state info
|
||||||
session.clear()
|
session.clear()
|
||||||
session["username"] = username
|
session["username"] = username
|
||||||
|
|
||||||
@@ -112,27 +115,43 @@ def signup():
|
|||||||
@auth_bp.route("/login", methods=["POST"])
|
@auth_bp.route("/login", methods=["POST"])
|
||||||
@cross_origin(supports_credentials=True)
|
@cross_origin(supports_credentials=True)
|
||||||
def login():
|
def login():
|
||||||
|
"""
|
||||||
|
Login to the web app with existing credentials.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# ensure a JSON request is made to contact this route
|
||||||
if not request.is_json:
|
if not request.is_json:
|
||||||
return jsonify({"message": "Expected JSON data"}), 400
|
return jsonify({"message": "Expected JSON data"}), 400
|
||||||
|
|
||||||
|
# Extract data from request via JSON
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
|
|
||||||
# Extract data from request
|
|
||||||
username = data.get('username')
|
username = data.get('username')
|
||||||
password = data.get('password')
|
password = data.get('password')
|
||||||
|
|
||||||
# Basic server-side validation
|
# Validation - ensure all fields exist, users cannot have an empty field
|
||||||
if not all([username, password]):
|
if not all([username, password]):
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"logged_in": False,
|
"logged_in": False,
|
||||||
"message": "Missing required fields"
|
"message": "Missing required fields"
|
||||||
}), 400
|
}), 400
|
||||||
|
|
||||||
|
# Sanitize the inputs - helps to prevent SQL injection
|
||||||
|
try:
|
||||||
|
username = sanitizer(username, "username")
|
||||||
|
password = sanitizer(password, "password")
|
||||||
|
except ValueError as e:
|
||||||
|
return jsonify({
|
||||||
|
"account_created": False,
|
||||||
|
"error_fields": [username, password],
|
||||||
|
"message": "Invalid input received"
|
||||||
|
}), 400
|
||||||
|
|
||||||
|
# Create a connection to the database
|
||||||
db = Database()
|
db = Database()
|
||||||
cursor = db.create_connection()
|
cursor = db.create_connection()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Check if user exists
|
# Check if user exists, only existing users can be logged in
|
||||||
user = cursor.execute(
|
user = cursor.execute(
|
||||||
"SELECT * FROM users WHERE username = ?",
|
"SELECT * FROM users WHERE username = ?",
|
||||||
(username,)
|
(username,)
|
||||||
@@ -145,7 +164,7 @@ def login():
|
|||||||
"message": "Invalid username or password"
|
"message": "Invalid username or password"
|
||||||
}), 401
|
}), 401
|
||||||
|
|
||||||
# Verify password
|
# Verify password matches the password associated with that user
|
||||||
if not check_password_hash(user["password"], password):
|
if not check_password_hash(user["password"], password):
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"logged_in": False,
|
"logged_in": False,
|
||||||
@@ -153,10 +172,11 @@ def login():
|
|||||||
"message": "Invalid username or password"
|
"message": "Invalid username or password"
|
||||||
}), 401
|
}), 401
|
||||||
|
|
||||||
# Set up session
|
# Set up session to avoid having unncessary state information
|
||||||
session.clear()
|
session.clear()
|
||||||
session["username"] = username
|
session["username"] = username
|
||||||
|
|
||||||
|
# User has been logged in, let frontend know that
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"logged_in": True,
|
"logged_in": True,
|
||||||
"message": "Login successful",
|
"message": "Login successful",
|
||||||
@@ -176,6 +196,11 @@ def login():
|
|||||||
|
|
||||||
@auth_bp.route("/logout")
|
@auth_bp.route("/logout")
|
||||||
@login_required
|
@login_required
|
||||||
def logout():
|
def logout() -> dict:
|
||||||
|
"""
|
||||||
|
Log out and clear the users session.
|
||||||
|
|
||||||
|
Can only be accessed by a logged in user.
|
||||||
|
"""
|
||||||
session.clear()
|
session.clear()
|
||||||
return {"logged_in": False}
|
return {"logged_in": False}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
from flask import Blueprint, request, jsonify, session
|
from flask import Blueprint, jsonify, session
|
||||||
from blueprints.utils import login_required
|
|
||||||
from database.database import Database
|
from database.database import Database
|
||||||
from flask_socketio import SocketIO, emit, join_room, leave_room
|
from flask_socketio import SocketIO, emit, join_room, leave_room
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
@@ -11,11 +10,14 @@ socketio = SocketIO()
|
|||||||
# TODO: Add a route that deletes all chat logs when the stream is finished
|
# TODO: Add a route that deletes all chat logs when the stream is finished
|
||||||
|
|
||||||
@socketio.on("connect")
|
@socketio.on("connect")
|
||||||
def handle_connection():
|
def handle_connection() -> None:
|
||||||
print("Client Connected")
|
"""
|
||||||
|
Accept the connection from the frontend.
|
||||||
|
"""
|
||||||
|
print("Client Connected") # Confirmation connect has been made
|
||||||
|
|
||||||
@socketio.on("join")
|
@socketio.on("join")
|
||||||
def handle_join(data):
|
def handle_join(data) -> None:
|
||||||
"""
|
"""
|
||||||
Allow a user to join the chat of the stream they are watching.
|
Allow a user to join the chat of the stream they are watching.
|
||||||
"""
|
"""
|
||||||
@@ -25,7 +27,7 @@ def handle_join(data):
|
|||||||
emit("status", {"message": f"Welcome to the chat, stream_id: {stream_id}"}, room=stream_id)
|
emit("status", {"message": f"Welcome to the chat, stream_id: {stream_id}"}, room=stream_id)
|
||||||
|
|
||||||
@socketio.on("leave")
|
@socketio.on("leave")
|
||||||
def handle_leave(data):
|
def handle_leave(data) -> None:
|
||||||
"""
|
"""
|
||||||
Handle what happens when a user leaves the stream they are watching in regards to the chat.
|
Handle what happens when a user leaves the stream they are watching in regards to the chat.
|
||||||
"""
|
"""
|
||||||
@@ -35,7 +37,7 @@ def handle_leave(data):
|
|||||||
emit("status", {"message": f"user left room {stream_id}"}, room=stream_id)
|
emit("status", {"message": f"user left room {stream_id}"}, room=stream_id)
|
||||||
|
|
||||||
@chat_bp.route("/chat/<int:stream_id>")
|
@chat_bp.route("/chat/<int:stream_id>")
|
||||||
def get_past_chat(stream_id):
|
def get_past_chat(stream_id: int):
|
||||||
"""
|
"""
|
||||||
Returns a JSON object to be passed to the server.
|
Returns a JSON object to be passed to the server.
|
||||||
|
|
||||||
@@ -56,7 +58,7 @@ def get_past_chat(stream_id):
|
|||||||
FROM chat
|
FROM chat
|
||||||
WHERE stream_id = ?
|
WHERE stream_id = ?
|
||||||
ORDER BY time_sent DESC
|
ORDER BY time_sent DESC
|
||||||
LIMIT 50
|
LIMIT 1
|
||||||
)
|
)
|
||||||
ORDER BY time_sent ASC;""", (stream_id,)).fetchall()
|
ORDER BY time_sent ASC;""", (stream_id,)).fetchall()
|
||||||
db.close_connection()
|
db.close_connection()
|
||||||
@@ -68,7 +70,7 @@ def get_past_chat(stream_id):
|
|||||||
return jsonify({"chat_history": chat_history}), 200
|
return jsonify({"chat_history": chat_history}), 200
|
||||||
|
|
||||||
@socketio.on("send_message")
|
@socketio.on("send_message")
|
||||||
def send_chat(data):
|
def send_chat(data) -> None:
|
||||||
"""
|
"""
|
||||||
Using WebSockets to send a chat message to the specified chat
|
Using WebSockets to send a chat message to the specified chat
|
||||||
"""
|
"""
|
||||||
@@ -92,6 +94,7 @@ def send_chat(data):
|
|||||||
db.commit_data()
|
db.commit_data()
|
||||||
db.close_connection()
|
db.close_connection()
|
||||||
|
|
||||||
|
# Send the chat message to the client so it can be displayed
|
||||||
emit("new_message", {
|
emit("new_message", {
|
||||||
"chatter_id":chatter_id,
|
"chatter_id":chatter_id,
|
||||||
"message":message,
|
"message":message,
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
from flask import Blueprint, render_template, session, jsonify
|
|
||||||
|
|
||||||
main_bp = Blueprint("app", __name__)
|
|
||||||
|
|
||||||
# temp, showcasing HLS
|
|
||||||
|
|
||||||
|
|
||||||
@main_bp.route('/hls1/<stream_id>')
|
|
||||||
def hls(stream_id):
|
|
||||||
stream_url = f"http://127.0.0.1:8080/hls/{stream_id}/index.m3u8"
|
|
||||||
return render_template("video.html", video_url=stream_url)
|
|
||||||
# --------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
# TODO Route for saving uploaded thumbnails to database, serving these images to the frontend upon request: →→→ @main_bp.route('/images/<path:filename>') \n def serve_image(filename): ←←←
|
|
||||||
@@ -4,8 +4,8 @@ from utils.user_utils import get_user_id
|
|||||||
stream_bp = Blueprint("stream", __name__)
|
stream_bp = Blueprint("stream", __name__)
|
||||||
|
|
||||||
|
|
||||||
@stream_bp.route('/get_streams', methods=['GET'])
|
@stream_bp.route('/get_streams')
|
||||||
def get_sample_streams():
|
def get_sample_streams() -> list[dict]:
|
||||||
"""
|
"""
|
||||||
Returns a list of (sample) streams live right now
|
Returns a list of (sample) streams live right now
|
||||||
"""
|
"""
|
||||||
@@ -55,8 +55,8 @@ def get_sample_streams():
|
|||||||
return streams
|
return streams
|
||||||
|
|
||||||
|
|
||||||
@stream_bp.route('/get_recommended_streams', methods=['GET'])
|
@stream_bp.route('/get_recommended_streams')
|
||||||
def get_recommended_streams():
|
def get_recommended_streams() -> list[dict]:
|
||||||
"""
|
"""
|
||||||
Queries DB to get a list of recommended streams using an algorithm
|
Queries DB to get a list of recommended streams using an algorithm
|
||||||
"""
|
"""
|
||||||
@@ -83,8 +83,8 @@ def get_recommended_streams():
|
|||||||
}]
|
}]
|
||||||
|
|
||||||
|
|
||||||
@stream_bp.route('/get_categories', methods=['GET'])
|
@stream_bp.route('/get_categories')
|
||||||
def get_categories():
|
def get_categories() -> list[dict]:
|
||||||
"""
|
"""
|
||||||
Returns a list of (sample) categories being watched right now
|
Returns a list of (sample) categories being watched right now
|
||||||
"""
|
"""
|
||||||
@@ -122,8 +122,8 @@ def get_categories():
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@stream_bp.route('/get_followed_categories', methods=['GET'])
|
@stream_bp.route('/get_followed_categories')
|
||||||
def get_followed_categories():
|
def get_followed_categories() -> list | list[dict]:
|
||||||
"""
|
"""
|
||||||
Queries DB to get a list of followed categories
|
Queries DB to get a list of followed categories
|
||||||
Hmm..
|
Hmm..
|
||||||
@@ -134,7 +134,7 @@ def get_followed_categories():
|
|||||||
return get_categories()
|
return get_categories()
|
||||||
|
|
||||||
|
|
||||||
@stream_bp.route('/get_streamer_data/<int:streamer_username>', methods=['GET'])
|
@stream_bp.route('/get_streamer_data/<int:streamer_username>')
|
||||||
def get_streamer_data(streamer_username):
|
def get_streamer_data(streamer_username):
|
||||||
"""
|
"""
|
||||||
Returns a given streamer's data
|
Returns a given streamer's data
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ def create_checkout_session():
|
|||||||
|
|
||||||
return jsonify(clientSecret=session.client_secret)
|
return jsonify(clientSecret=session.client_secret)
|
||||||
|
|
||||||
@stripe_bp.route('/session-status', methods=['GET']) # check for payment status
|
@stripe_bp.route('/session-status') # check for payment status
|
||||||
def session_status():
|
def session_status():
|
||||||
"""
|
"""
|
||||||
Used to query payment status
|
Used to query payment status
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ from utils.user_utils import is_subscribed, is_following, subscription_expiratio
|
|||||||
|
|
||||||
user_bp = Blueprint("user", __name__)
|
user_bp = Blueprint("user", __name__)
|
||||||
|
|
||||||
@user_bp.route('/is_subscribed/<int:user_id>/<int:streamer_id>', methods=['GET'])
|
@user_bp.route('/is_subscribed/<int:user_id>/<int:streamer_id>')
|
||||||
def user_subscribed(user_id, streamer_id):
|
def user_subscribed(user_id: int, streamer_id: int):
|
||||||
"""
|
"""
|
||||||
Checks to see if user is subscribed to a streamer
|
Checks to see if user is subscribed to a streamer
|
||||||
"""
|
"""
|
||||||
@@ -12,8 +12,8 @@ def user_subscribed(user_id, streamer_id):
|
|||||||
return jsonify({"subscribed": True})
|
return jsonify({"subscribed": True})
|
||||||
return jsonify({"subscribed": False})
|
return jsonify({"subscribed": False})
|
||||||
|
|
||||||
@user_bp.route('/is_following/<int:user_id>/<int:streamer_id>', methods=['GET'])
|
@user_bp.route('/is_following/<int:user_id>/<int:streamer_id>')
|
||||||
def user_following(user_id, streamer_id):
|
def user_following(user_id: int, streamer_id: int):
|
||||||
"""
|
"""
|
||||||
Checks to see if user is following a streamer
|
Checks to see if user is following a streamer
|
||||||
"""
|
"""
|
||||||
@@ -22,8 +22,8 @@ def user_following(user_id, streamer_id):
|
|||||||
return jsonify({"following": False})
|
return jsonify({"following": False})
|
||||||
|
|
||||||
|
|
||||||
@user_bp.route('/subscription_remaining/<int:user_id>/<int:streamer_id>', methods=['GET'])
|
@user_bp.route('/subscription_remaining/<int:user_id>/<int:streamer_id>')
|
||||||
def user_subscription_expiration(user_id, streamer_id):
|
def user_subscription_expiration(user_id: int, streamer_id: int):
|
||||||
"""
|
"""
|
||||||
Returns remaining time until subscription expiration
|
Returns remaining time until subscription expiration
|
||||||
"""
|
"""
|
||||||
@@ -31,7 +31,7 @@ def user_subscription_expiration(user_id, streamer_id):
|
|||||||
|
|
||||||
return jsonify({"remaining_time": remaining_time})
|
return jsonify({"remaining_time": remaining_time})
|
||||||
|
|
||||||
@user_bp.route('/get_login_status', methods=['GET'])
|
@user_bp.route('/get_login_status')
|
||||||
def get_login_status():
|
def get_login_status():
|
||||||
"""
|
"""
|
||||||
Returns whether the user is logged in or not
|
Returns whether the user is logged in or not
|
||||||
@@ -39,7 +39,7 @@ def get_login_status():
|
|||||||
return jsonify(session.get("username") is not None)
|
return jsonify(session.get("username") is not None)
|
||||||
|
|
||||||
@user_bp.route('/authenticate_user')
|
@user_bp.route('/authenticate_user')
|
||||||
def authenticate_user():
|
def authenticate_user() -> dict:
|
||||||
"""
|
"""
|
||||||
Authenticates the user
|
Authenticates the user
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -3,11 +3,16 @@ from functools import wraps
|
|||||||
from re import match
|
from re import match
|
||||||
|
|
||||||
def logged_in_user():
|
def logged_in_user():
|
||||||
|
"""
|
||||||
|
Validator to make sure a user is logged in.
|
||||||
|
"""
|
||||||
g.user = session.get("username", None)
|
g.user = session.get("username", None)
|
||||||
g.admin = session.get("username", None)
|
g.admin = session.get("username", None)
|
||||||
|
|
||||||
def login_required(view):
|
def login_required(view):
|
||||||
"""add at start of routes where users need to be logged in to access"""
|
"""
|
||||||
|
Add at start of routes where users need to be logged in to access.
|
||||||
|
"""
|
||||||
@wraps(view)
|
@wraps(view)
|
||||||
def wrapped_view(*args, **kwargs):
|
def wrapped_view(*args, **kwargs):
|
||||||
if g.user is None:
|
if g.user is None:
|
||||||
@@ -16,7 +21,9 @@ def login_required(view):
|
|||||||
return wrapped_view
|
return wrapped_view
|
||||||
|
|
||||||
def admin_required(view):
|
def admin_required(view):
|
||||||
"""add at start of routes where admins need to be logged in to access"""
|
"""
|
||||||
|
Add at start of routes where admins need to be logged in to access.
|
||||||
|
"""
|
||||||
@wraps(view)
|
@wraps(view)
|
||||||
def wrapped_view(*args, **kwargs):
|
def wrapped_view(*args, **kwargs):
|
||||||
if g.admin != "admin":
|
if g.admin != "admin":
|
||||||
@@ -24,8 +31,6 @@ def admin_required(view):
|
|||||||
return view(*args, **kwargs)
|
return view(*args, **kwargs)
|
||||||
return wrapped_view
|
return wrapped_view
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
def sanitizer(user_input: str, input_type="username") -> str:
|
def sanitizer(user_input: str, input_type="username") -> str:
|
||||||
"""
|
"""
|
||||||
Sanitizes user input based on the specified input type.
|
Sanitizes user input based on the specified input type.
|
||||||
@@ -58,7 +63,7 @@ def sanitizer(user_input: str, input_type="username") -> str:
|
|||||||
r = rules.get(input_type)
|
r = rules.get(input_type)
|
||||||
if not r or \
|
if not r or \
|
||||||
not (r["min_length"] <= len(sanitised_input) <= r["max_length"]) or \
|
not (r["min_length"] <= len(sanitised_input) <= r["max_length"]) or \
|
||||||
not re.match(r["pattern"], sanitised_input):
|
not match(r["pattern"], sanitised_input):
|
||||||
raise ValueError("Unaccepted character or length in input")
|
raise ValueError("Unaccepted character or length in input")
|
||||||
|
|
||||||
return sanitised_input
|
return sanitised_input
|
||||||
|
|||||||
Reference in New Issue
Block a user