forked from tpd94/CDRM-Project
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.
This commit is contained in:
parent
c756361da0
commit
8940d57b25
@ -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({"message": "User successfully registered!", "api_key": api_key}),
|
||||
201,
|
||||
)
|
||||
return jsonify({"error": "User already exists!"}), 409
|
||||
|
Loading…
x
Reference in New Issue
Block a user