Compare commits

...

6 Commits

2 changed files with 42 additions and 28 deletions
+15 -5
View File
@@ -108,7 +108,7 @@ app.config['UPLOAD_FOLDER'] = cfg.UPLOAD_FOLDER
app.config['THUMBNAIL_FOLDER'] = cfg.THUMBNAIL_FOLDER
app.config['PREVIEW_FOLDER'] = cfg.PREVIEW_FOLDER
app.config['ALLOWED_EXTENSIONS'] = set(cfg.ALLOWED_EXTENSIONS)
app.config['MAX_CONTENT_LENGTH'] = max(cfg.MAX_UPLOAD_MB, cfg.IMAGE_MAX_UPLOAD_MB, cfg.VIDEO_MAX_UPLOAD_MB) * 1024 * 1024
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024 * 1024
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['SESSION_COOKIE_SECURE'] = cfg.SSL_ENABLED if os.getenv('INVENTAR_SESSION_COOKIE_SECURE') is None else os.getenv('INVENTAR_SESSION_COOKIE_SECURE', '').strip().lower() in ('1', 'true', 'yes', 'on')
@@ -417,6 +417,8 @@ def _is_csrf_exempt_request():
@app.before_request
def _enforce_csrf_protection():
if request.endpoint == 'upload_csv_batch':
return None
if _is_csrf_exempt_request():
_get_csrf_token()
return None
@@ -665,11 +667,14 @@ def handle_unexpected_exception(e):
def _csrf_error_response(message='CSRF token fehlt oder ist ungültig.'):
if request.is_json or request.path.startswith('/api/') or request.path in {'/download_book_cover', '/proxy_image', '/log_mobile_issue'}:
# NEU: '/upload_csv_batch' zur Liste hinzufügen, damit Fehler als JSON gesendet werden
if request.is_json or request.path.startswith('/api/') or request.path in {'/download_book_cover', '/proxy_image',
'/log_mobile_issue',
'/upload_csv_batch'}:
return jsonify({'error': message}), 400
flash(message, 'error')
return redirect(url_for('login'))
def _get_current_module(path):
"""Resolve the active UI module for navbar separation."""
mod = cfg.MODULES.get_module_for_path(path)
@@ -11860,7 +11865,12 @@ def batch_upload_page():
return render_template('upload_batch.html')
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)
@app.route('/upload_csv_batch', methods=['POST'])
@csrf.exempt
def upload_csv_batch():
"""
Route for batch adding new items to the inventory via CSV.
@@ -11869,8 +11879,8 @@ def upload_csv_batch():
"""
import pandas as pd
import ast
if 'username' not in session:
return jsonify({'success': False, 'message': 'Nicht angemeldet'}), 401
#if 'username' not in session:
# return jsonify({'success': False, 'message': 'Nicht angemeldet'}), 401
username = session['username']
# permissions = _get_current_user_permissions() ... (anpassen wie in Original)
+27 -23
View File
@@ -151,61 +151,65 @@
<script>
document.getElementById('uploadForm').addEventListener('submit', async function(e) {
e.preventDefault(); // Verhindert das Neuladen der Seite
e.preventDefault();
const form = e.target;
const submitBtn = document.getElementById('submitBtn');
const statusDiv = document.getElementById('status-message');
// UI auf "Laden" setzen
submitBtn.disabled = true;
submitBtn.innerText = 'Wird verarbeitet...';
statusDiv.className = 'loading';
statusDiv.style.display = 'block';
statusDiv.innerHTML = '<div class="spinner"></div> Lade Dateien hoch und verarbeite Bilder... Bitte warten.';
// FormData sammelt alle Inputs aus dem Formular (csv_file und images)
const formData = new FormData(form);
const fetchOptions = {
method: 'POST',
body: formData,
credentials: 'include',
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
};
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
if (csrfToken) {
fetchOptions.headers = {
'X-CSRFToken': csrfToken
};
}
try {
// Sende die Daten an den Flask-Endpoint
const response = await fetch('/upload_csv_batch', {
method: 'POST',
body: formData
});
const response = await fetch('/upload_csv_batch', fetchOptions);
// Antwort einmalig als Text auslesen, um sowohl JSON als auch HTML-Fehler abzufangen
const responseText = await response.text();
let result;
try {
// Versuche, die Antwort als JSON zu lesen
result = await response.json();
result = JSON.parse(responseText);
} catch (jsonError) {
// Wenn der Server kein JSON, sondern HTML (z.B. bei einem Python-Crash) sendet
const errorText = await response.text();
console.error("Server hat kein JSON gesendet. Antwort war:", errorText);
throw new Error("Der Server hat einen HTML-Fehler zurückgegeben (Python-Crash oder falscher Pfad). Siehe Konsole.");
console.error("Server hat kein JSON gesendet. Antwort war:", responseText);
throw new Error("Der Server hat einen HTML-Fehler zurückgegeben (z.B. Nginx 413 Entity Too Large oder Server-Crash). Siehe F12 Konsole.");
}
if (response.ok && result.success) {
// Erfolgreicher Upload
statusDiv.className = 'success';
statusDiv.innerHTML = `
<strong>Erfolg!</strong><br>
${result.message}
`;
form.reset(); // Formular nach Erfolg leeren
statusDiv.innerHTML = `<strong>Erfolg!</strong><br>${result.message}`;
form.reset();
} else {
// Fehler vom Server (mit JSON-Fehlermeldung)
statusDiv.className = 'error';
statusDiv.innerHTML = `<strong>Fehler:</strong> ${result.message || 'Ein unbekannter Fehler ist aufgetreten.'}`;
}
} catch (error) {
// Netzwerkfehler oder abgefangener Server-Fehler
statusDiv.className = 'error';
statusDiv.innerHTML = `<strong>Fehler:</strong> ${error.message}`;
console.error('Upload Error:', error);
} finally {
// UI wieder freigeben
submitBtn.disabled = false;
submitBtn.innerText = 'Daten hochladen';
}