diff --git a/app.py b/app.py index 6655c0f..904c2d8 100644 --- a/app.py +++ b/app.py @@ -229,6 +229,16 @@ def serve_css_lib(filename): app.register_blueprint(static_bp) +def user_has_list_access(list_obj, user): + if not user.is_authenticated: + return False + if list_obj.owner_id == user.id: + return True + if db.session.query(SharedList).filter_by(list_id=list_obj.id, user_id=user.id).first(): + return True + return False + + def allowed_file(filename): return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS @@ -246,7 +256,6 @@ def get_list_details(list_id): def generate_share_token(length=8): - """Generuje token do udostępniania. Parametr `length` to liczba znaków (domyślnie 4).""" return secrets.token_hex(length // 2) @@ -1039,7 +1048,12 @@ def all_products(): @app.route("/upload_receipt/", methods=["POST"]) +@login_required def upload_receipt(list_id): + list_obj = db.session.get(ShoppingList, list_id) + if not list_obj or not user_has_list_access(list_obj, current_user): + return _receipt_error("Gość/niezalogowany nie może wgrywać plików") + if "receipt" not in request.files: return _receipt_error("Brak pliku") @@ -1096,6 +1110,7 @@ def upload_receipt(list_id): return _receipt_error("Niedozwolony format pliku") + @app.route("/uploads/") def uploaded_file(filename): response = send_from_directory(app.config["UPLOAD_FOLDER"], filename) @@ -1133,7 +1148,7 @@ def reorder_items(): @login_required def analyze_receipts_for_list(list_id): list_obj = db.session.get(ShoppingList, list_id) - if not list_obj or list_obj.owner_id != current_user.id: + if not list_obj or not user_has_list_access(list_obj, current_user): return jsonify({"error": "Brak dostępu"}), 403 receipt_objs = Receipt.query.filter_by(list_id=list_id).all() @@ -1145,42 +1160,29 @@ def analyze_receipts_for_list(list_id): if not os.path.exists(filepath): continue - temp_path = None - try: - if filepath.lower().endswith(".webp"): - - raw_image = Image.open(filepath).convert("RGB") - image = preprocess_image_for_tesseract(raw_image) - else: - - raw_image = Image.open(filepath).convert("RGB") - image = preprocess_image_for_tesseract(raw_image) - + raw_image = Image.open(filepath).convert("RGB") + image = preprocess_image_for_tesseract(raw_image) value, lines = extract_total_tesseract(image) except Exception as e: - print(f"OCR error for {receipt.filename}: {e}") + import traceback + print(f"OCR error for {receipt.filename}:\n{traceback.format_exc()}") value = 0.0 lines = [] - finally: - if temp_path and os.path.exists(temp_path): - os.unlink(temp_path) - - results.append( - { - "id": receipt.id, - "filename": receipt.filename, - "amount": round(value, 2), - "debug_text": lines, - } - ) + results.append({ + "id": receipt.id, + "filename": receipt.filename, + "amount": round(value, 2), + "debug_text": lines, + }) total += value return jsonify({"results": results, "total": round(total, 2)}) + @app.route("/admin") @login_required @admin_required