- Problem adding documents

This commit is contained in:
Josako
2025-11-18 11:14:49 +01:00
parent 78043ab3ef
commit f2604db5a9
5 changed files with 113 additions and 14 deletions

View File

@@ -9,6 +9,12 @@
{% block content %} {% block content %}
<form method="post" enctype="multipart/form-data"> <form method="post" enctype="multipart/form-data">
{{ form.hidden_tag() }} {{ form.hidden_tag() }}
{# Debug: render CSRF veld expliciet om aanwezigheid in de DOM te garanderen #}
{% if form.csrf_token %}{{ form.csrf_token }}{% endif %}
<script>
// Client-side debug: bevestig dat het CSRF veld in de DOM staat
console.debug('[add_document] CSRF present in DOM?', !!document.querySelector('input[name="csrf_token"]'));
</script>
{% set disabled_fields = [] %} {% set disabled_fields = [] %}
{% set exclude_fields = [] %} {% set exclude_fields = [] %}
{% for field in form.get_static_fields() %} {% for field in form.get_static_fields() %}

View File

@@ -11,18 +11,18 @@
{{ form.hidden_tag() }} {{ form.hidden_tag() }}
{% set disabled_fields = [] %} {% set disabled_fields = [] %}
{% set exclude_fields = [] %} {% set exclude_fields = [] %}
{% for field in form.get_static_fields() %} {% for field in form %}
{{ render_field(field, disabled_fields, exclude_fields) }} {{ render_field(field, disabled_fields, exclude_fields) }}
{% endfor %} {% endfor %}
<!-- Render Dynamic Fields --> <!-- Render Dynamic Fields -->
{% for collection_name, fields in form.get_dynamic_fields().items() %} {# {% for collection_name, fields in form.get_dynamic_fields().items() %}#}
{% if fields|length > 0 %} {# {% if fields|length > 0 %}#}
<h4 class="mt-4">{{ collection_name }}</h4> {# <h4 class="mt-4">{{ collection_name }}</h4>#}
{% endif %} {# {% endif %}#}
{% for field in fields %} {# {% for field in fields %}#}
{{ render_field(field, disabled_fields, exclude_fields) }} {# {{ render_field(field, disabled_fields, exclude_fields) }}#}
{% endfor %} {# {% endfor %}#}
{% endfor %} {# {% endfor %}#}
<button type="submit" class="btn btn-primary">Register Tenant Make</button> <button type="submit" class="btn btn-primary">Register Tenant Make</button>
</form> </form>
{% endblock %} {% endblock %}

View File

@@ -6,6 +6,7 @@ from flask_security import roles_accepted, current_user
from sqlalchemy import desc from sqlalchemy import desc
from sqlalchemy.orm import aliased from sqlalchemy.orm import aliased
from werkzeug.utils import secure_filename from werkzeug.utils import secure_filename
from werkzeug.datastructures import CombinedMultiDict
from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.exc import SQLAlchemyError
import requests import requests
from requests.exceptions import SSLError, HTTPError from requests.exceptions import SSLError, HTTPError
@@ -354,7 +355,17 @@ def handle_retriever_selection():
@document_bp.route('/add_document', methods=['GET', 'POST']) @document_bp.route('/add_document', methods=['GET', 'POST'])
@roles_accepted('Super User', 'Partner Admin', 'Tenant Admin') @roles_accepted('Super User', 'Partner Admin', 'Tenant Admin')
def add_document(): def add_document():
form = AddDocumentForm(request.form) # Log vroege request-info om uploadproblemen te diagnosticeren
try:
current_app.logger.debug(
f"[add_document] method={request.method}, content_type={request.content_type}, "
f"files_keys={list(request.files.keys())}"
)
except Exception:
pass
# Bind expliciet zowel form- als file-data aan de form (belangrijk voor FileField & CSRF)
form = AddDocumentForm(CombinedMultiDict([request.form, request.files]))
catalog_id = session.get('catalog_id', None) catalog_id = session.get('catalog_id', None)
if catalog_id is None: if catalog_id is None:
flash('You need to set a Session Catalog before adding Documents or URLs', 'warning') flash('You need to set a Session Catalog before adding Documents or URLs', 'warning')
@@ -364,6 +375,38 @@ def add_document():
if catalog.configuration and len(catalog.configuration) > 0: if catalog.configuration and len(catalog.configuration) > 0:
form.add_dynamic_fields("tagging_fields", catalog.configuration) form.add_dynamic_fields("tagging_fields", catalog.configuration)
current_app.logger.debug("In Add Document")
# Extra debug logging om CSRF/payload te controleren
try:
current_app.logger.debug(
f"[add_document] request.form keys: {list(request.form.keys())}"
)
current_app.logger.debug(
f"[add_document] csrf_token in form? {request.form.get('csrf_token') is not None}"
)
try:
has_csrf_field = hasattr(form, 'csrf_token')
current_app.logger.debug(
f"[add_document] form has csrf field? {has_csrf_field}"
)
if has_csrf_field:
# Let op: we loggen geen tokenwaarde om lekken te vermijden; enkel aanwezigheid
current_app.logger.debug(
"[add_document] form.csrf_token field is present on form object"
)
# Bevestig of de CSRF-waarde effectief in de form is gebonden
try:
current_app.logger.debug(
f"[add_document] csrf bound? data_present={bool(form.csrf_token.data)} field_name={getattr(form.csrf_token, 'name', None)}"
)
except Exception:
pass
except Exception:
pass
except Exception:
pass
if form.validate_on_submit(): if form.validate_on_submit():
try: try:
current_app.logger.info(f'Adding Document for {catalog_id}') current_app.logger.info(f'Adding Document for {catalog_id}')
@@ -400,6 +443,25 @@ def add_document():
except Exception as e: except Exception as e:
current_app.logger.error(f'Error adding document: {str(e)}') current_app.logger.error(f'Error adding document: {str(e)}')
flash('An error occurred while adding the document.', 'danger') flash('An error occurred while adding the document.', 'danger')
else:
# Toon en log validatiefouten als de submit faalt
if request.method == 'POST':
try:
current_app.logger.warning(
f"[add_document] form validation failed. errors={getattr(form, 'errors', {})}"
)
current_app.logger.debug(
f"[add_document] request.files keys after validation: {list(request.files.keys())}"
)
current_app.logger.debug(
f"[add_document] request.form keys after validation: {list(request.form.keys())}"
)
current_app.logger.debug(
f"[add_document] csrf_token in form after validation? {request.form.get('csrf_token') is not None}"
)
except Exception:
pass
form_validation_failed(request, form)
return render_template('document/add_document.html', form=form) return render_template('document/add_document.html', form=form)
@@ -407,7 +469,16 @@ def add_document():
@document_bp.route('/add_url', methods=['GET', 'POST']) @document_bp.route('/add_url', methods=['GET', 'POST'])
@roles_accepted('Super User', 'Partner Admin', 'Tenant Admin') @roles_accepted('Super User', 'Partner Admin', 'Tenant Admin')
def add_url(): def add_url():
form = AddURLForm(request.form) # Log vroege request-info om submitproblemen te diagnosticeren
try:
current_app.logger.debug(
f"[add_url] method={request.method}, content_type={request.content_type}, files_keys={list(request.files.keys())}"
)
except Exception:
pass
# Bind expliciet zowel form- als file-data (consistentie en duidelijkheid)
form = AddURLForm(CombinedMultiDict([request.form, request.files]))
catalog_id = session.get('catalog_id', None) catalog_id = session.get('catalog_id', None)
if catalog_id is None: if catalog_id is None:
flash('You need to set a Session Catalog before adding Documents or URLs', 'warning') flash('You need to set a Session Catalog before adding Documents or URLs', 'warning')
@@ -417,6 +488,15 @@ def add_url():
if catalog.configuration and len(catalog.configuration) > 0: if catalog.configuration and len(catalog.configuration) > 0:
form.add_dynamic_fields("tagging_fields", catalog.configuration) form.add_dynamic_fields("tagging_fields", catalog.configuration)
url="" url=""
# Kleine debug om te zien of CSRF aan de form gebonden is
try:
if hasattr(form, 'csrf_token'):
current_app.logger.debug(
f"[add_url] csrf bound? data_present={bool(form.csrf_token.data)} field_name={getattr(form.csrf_token, 'name', None)}"
)
except Exception:
pass
if form.validate_on_submit(): if form.validate_on_submit():
try: try:
tenant_id = session['tenant']['id'] tenant_id = session['tenant']['id']
@@ -462,6 +542,15 @@ def add_url():
except Exception as e: except Exception as e:
current_app.logger.error(f'Error adding document: {str(e)}') current_app.logger.error(f'Error adding document: {str(e)}')
flash('An error occurred while adding the document.', 'danger') flash('An error occurred while adding the document.', 'danger')
else:
if request.method == 'POST':
try:
current_app.logger.warning(
f"[add_url] form validation failed. errors={getattr(form, 'errors', {})}"
)
except Exception:
pass
form_validation_failed(request, form)
return render_template('document/add_url.html', form=form) return render_template('document/add_url.html', form=form)

View File

@@ -177,7 +177,7 @@ def validate_make_name(form, field):
raise ValidationError(f'A Make with name "{field.data}" already exists. Choose another name.') raise ValidationError(f'A Make with name "{field.data}" already exists. Choose another name.')
class TenantMakeForm(DynamicFormBase): class TenantMakeForm(FlaskForm):
name = StringField('Name', validators=[DataRequired(), Length(max=50), validate_make_name]) name = StringField('Name', validators=[DataRequired(), Length(max=50), validate_make_name])
description = TextAreaField('Description', validators=[Optional()]) description = TextAreaField('Description', validators=[Optional()])
active = BooleanField('Active', validators=[Optional()], default=True) active = BooleanField('Active', validators=[Optional()], default=True)

View File

@@ -571,10 +571,12 @@ def delete_tenant_project(tenant_project_id):
@roles_accepted('Super User', 'Partner Admin', 'Tenant Admin') @roles_accepted('Super User', 'Partner Admin', 'Tenant Admin')
def tenant_make(): def tenant_make():
form = TenantMakeForm() form = TenantMakeForm()
customisation_config = cache_manager.customisations_config_cache.get_config("CHAT_CLIENT_CUSTOMISATION") current_app.logger.debug(f"ìn tenant_make view")
default_customisation_options = create_default_config_from_type_config(customisation_config["configuration"]) # customisation_config = cache_manager.customisations_config_cache.get_config("CHAT_CLIENT_CUSTOMISATION")
# default_customisation_options = create_default_config_from_type_config(customisation_config["configuration"])
if form.validate_on_submit(): if form.validate_on_submit():
current_app.logger.debug(f"in tenant_make form validate")
tenant_id = session['tenant']['id'] tenant_id = session['tenant']['id']
new_tenant_make = TenantMake() new_tenant_make = TenantMake()
form.populate_obj(new_tenant_make) form.populate_obj(new_tenant_make)
@@ -596,6 +598,8 @@ def tenant_make():
flash(f'Failed to add Tenant Make. Error: {e}', 'danger') flash(f'Failed to add Tenant Make. Error: {e}', 'danger')
current_app.logger.error(f'Failed to add Tenant Make {new_tenant_make.name}' current_app.logger.error(f'Failed to add Tenant Make {new_tenant_make.name}'
f'for tenant {tenant_id}. Error: {str(e)}') f'for tenant {tenant_id}. Error: {str(e)}')
else:
flash('Please fill in all required fields.', 'information')
return render_template('user/tenant_make.html', form=form) return render_template('user/tenant_make.html', form=form)