diff --git a/backend/app.py b/backend/app.py index f123cff..a0f403b 100644 --- a/backend/app.py +++ b/backend/app.py @@ -15,7 +15,11 @@ from utils.utils import random_string_generator, hash_string from blueprints.profile import profile as profileBlueprint app = Flask(__name__) +# Set configuration directly on the app instance +app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'} + app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI + db.init_app(app) app.register_blueprint(profileBlueprint, url_prefix='/api') diff --git a/backend/blueprints/profile/__init__.py b/backend/blueprints/profile/__init__.py index 83b5beb..4819db6 100644 --- a/backend/blueprints/profile/__init__.py +++ b/backend/blueprints/profile/__init__.py @@ -1,7 +1,84 @@ -from flask import Blueprint +from email.policy import default +from flask import Blueprint, request, jsonify, current_app +from werkzeug.utils import secure_filename +from datetime import datetime +from db.model import db +from db.model import User, UserRole # Adjust based on your model's location +from werkzeug.security import generate_password_hash +import uuid +import os +from config import * profile = Blueprint('profile', __name__) -@profile.route('/profile') -def get_profile(): - return "Profile Page" \ No newline at end of file +# Function to check allowed file extensions +def allowed_file(filename): + """Check if the uploaded file has an allowed extension.""" + return '.' in filename and filename.rsplit('.', 1)[1].lower() in current_app.config['ALLOWED_EXTENSIONS'] + +@profile.route('/register', methods=['POST']) +def register(): + """Handle user registration.""" + data = request.form + + # Extract form data + email = data.get('email') + first_name = data.get('firstName') + last_name = data.get('lastName') + username = data.get('username') + password = data.get('password') + bio = data.get('bio', '') + dob = data.get('dob') # Optional field for date of birth + role = int(data.get('role', UserRole.USER.value)) # Default to 'USER' role if not provided + is_activated = True # New user will be activated initially + profile_picture = request.files.get('profile_picture') + + # Validate required fields + if not all([email, first_name, last_name, username, password]): + return jsonify({"error": "Missing required fields"}), 400 + + # Check if the file is allowed and save it + if profile_picture and allowed_file(profile_picture.filename): + filename = secure_filename(profile_picture.filename) + # file_path = os.path.join(USER_UPLOADS_DIR, filename) + profile_picture.save( + os.path.join(USER_UPLOADS_DIR, filename) + ) + else: + filename = DEFAULT_PROFILE_FILE # Use a default image if no file is uploaded + # Hash the password + hashed_password = generate_password_hash(password) + + # Generate activation key (a UUID for example) + activation_key = str(uuid.uuid4()) + + # Create a new user + new_user = User( + email=email, + firstName=first_name, + lastName=last_name, + username=username, + hash_password=hashed_password, + bio=bio, + dob=datetime.fromisoformat(dob) if dob else datetime(2002, 1, 1), + pfpFilename=filename, + role=role, + isActivated=is_activated, + activationKey=activation_key, + sessions=[], + user_badges=[], + enrollments=[], + quizzes=[], + quiz_attempts=[], + chats=[], + notifications=[] + ) + + # Save the user to the database + try: + db.session.add(new_user) + db.session.commit() + return jsonify({"message": "User registered successfully. Please check your email to activate your account."}), 201 + except Exception as e: + db.session.rollback() + return jsonify({"error": "Registration failed, please try again later."}), 500 diff --git a/backend/config.py b/backend/config.py index 50abd11..692ecdc 100644 --- a/backend/config.py +++ b/backend/config.py @@ -20,4 +20,6 @@ PROJECT_ROOT: os.path = os.path.dirname(os.path.abspath(__file__)) USER_UPLOADS_DIR: str = os.path.join(PROJECT_ROOT, "uploads") DB_URI: str = f"{DB_ENGINE}://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}" -ACTIVATE_ACCOUNTS_ON_SIGNUP: bool = True \ No newline at end of file +ACTIVATE_ACCOUNTS_ON_SIGNUP: bool = True + +os.makedirs(USER_UPLOADS_DIR, exist_ok=True) \ No newline at end of file diff --git a/backend/uploads/1.jpg b/backend/uploads/1.jpg new file mode 100644 index 0000000..1960252 Binary files /dev/null and b/backend/uploads/1.jpg differ