From 8940d57b252116b42ce7aa2208f33ef538797349 Mon Sep 17 00:00:00 2001 From: voldemort <5692900+yell0wsuit@users.noreply.github.com> Date: Wed, 23 Jul 2025 01:42:33 +0700 Subject: [PATCH] Enhance registration process by adding input validation for username and password length, improve error handling for missing JSON data, and include API key in successful registration response. --- routes/register.py | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/routes/register.py b/routes/register.py index ee6d53a..172c2a8 100644 --- a/routes/register.py +++ b/routes/register.py @@ -1,7 +1,9 @@ +"""Module to handle the register process.""" + import re +import uuid from flask import Blueprint, request, jsonify from custom_functions.database.user_db import add_user -import uuid register_bp = Blueprint("register_bp", __name__) @@ -11,20 +13,26 @@ PASSWORD_REGEX = re.compile(r"^\S+$") @register_bp.route("/register", methods=["POST"]) def register(): - if request.method != "POST": - return jsonify({"error": "Method not supported"}), 405 - + """Handle the register process.""" data = request.get_json() + if data is None: + return jsonify({"error": "Invalid or missing JSON in request body."}), 400 # Check required fields for required_field in ["username", "password"]: if required_field not in data: return jsonify({"error": f"Missing required field: {required_field}"}), 400 - username = data["username"] + username = data["username"].lower() password = data["password"] api_key = str(uuid.uuid4()) + # Length checks + if not (3 <= len(username) <= 32): + return jsonify({"error": "Username must be 3-32 characters."}), 400 + if not (8 <= len(password) <= 128): + return jsonify({"error": "Password must be 8-128 characters."}), 400 + # Validate username and password if not USERNAME_REGEX.fullmatch(username): return ( @@ -41,6 +49,8 @@ def register(): # Attempt to add user if add_user(username, password, api_key): - return jsonify({"message": "User successfully registered!"}), 201 - else: - return jsonify({"error": "User already exists!"}), 409 + return ( + jsonify({"message": "User successfully registered!", "api_key": api_key}), + 201, + ) + return jsonify({"error": "User already exists!"}), 409