diff --git a/backend/blueprints/profile/__init__.py b/backend/blueprints/profile/__init__.py index fd01f4b..47717ee 100644 --- a/backend/blueprints/profile/__init__.py +++ b/backend/blueprints/profile/__init__.py @@ -137,3 +137,51 @@ def get_profile(): except Exception as e: return jsonify({"error": f"Failed to fetch profile. Error: {str(e)}"}), 500 + +@profile.route('/update-profile-picture', methods=['PATCH']) +@auth_required() +def update_profile_picture(): + """ + Allow the logged-in user to change their profile picture. + """ + user:User = g.current_user + + # Check if a file is attached + if 'profile_picture' not in request.files: + return jsonify({"error": "No file uploaded"}), 400 + + file = request.files['profile_picture'] + + # Validate file type + if file.filename == '': + return jsonify({"error": "No selected file"}), 400 + if not allowed_file(file.filename): + return jsonify({"error": "Invalid file type"}), 400 + + # Secure the filename and save the new file + filename = secure_filename(f"user_{user.id}_{file.filename}") + new_filepath = os.path.join(USER_UPLOADS_DIR, filename) + file.save(new_filepath) + + # Delete the old profile picture (if it's not the default) + if user.pfpFilename != DEFAULT_PROFILE_FILE: + old_filepath = os.path.join(USER_UPLOADS_DIR, user.pfpFilename) + if os.path.exists(old_filepath): + os.remove(old_filepath) + + # Update the user's profile picture + user.pfpFilename = filename + db.session.commit() + + # Generate the new profile URL + profile_url = url_for('send_file',filename=user.pfpFilename,_external=True) + + return jsonify({"message": "Profile picture updated successfully", "profile_url": profile_url}), 200 + + +def allowed_file(filename): + """ + Validate file extensions. + """ + allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'} + return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions \ No newline at end of file diff --git a/backend/uploads/1.jpg b/backend/uploads/1.jpg deleted file mode 100644 index 1960252..0000000 Binary files a/backend/uploads/1.jpg and /dev/null differ diff --git a/backend/uploads/user_f7ab56f1-d692-409e-98ab-2a563f37e389_1638856701024.jpg b/backend/uploads/user_f7ab56f1-d692-409e-98ab-2a563f37e389_1638856701024.jpg new file mode 100644 index 0000000..1a7da04 Binary files /dev/null and b/backend/uploads/user_f7ab56f1-d692-409e-98ab-2a563f37e389_1638856701024.jpg differ