Compare commits

...

3 Commits

Author SHA1 Message Date
Aiirondev_dev 5a2d703bc7 Debug of Vapid Keys 2026-07-29 13:35:15 +02:00
Aiirondev_dev 8e6dd17243 Fix of the notification subscription 2026-07-29 11:57:34 +02:00
Aiirondev_dev 2124ca65b2 Fix of the notification subscription 2026-07-29 11:49:54 +02:00
3 changed files with 47 additions and 48 deletions
+21 -32
View File
@@ -10424,7 +10424,7 @@ def notifications_view():
'title': notif.get('Title', 'Benachrichtigung'),
'message': notif.get('Message', ''),
'severity': notif.get('Severity', 'info'),
'type': notif.get('Type', '')
'type': notif.get('Type', ''),
'created_at': created_at_val if created_at_val else None,
'is_read': is_read,
'reference': notif.get('Reference') or {},
@@ -12134,44 +12134,33 @@ def get_optimal_image_quality(img, target_size_kb=80):
def health_check():
return 'OK', 200
@app.route('/api/push/subscribe', methods=['POST'])
def subscribe_to_push():
"""
Subscribe a user to push notifications
Expects JSON payload:
{
'subscription': {
'endpoint': '...',
'keys': {'p256dh': '...', 'auth': '...'}
}
}
"""
if 'username' not in session:
return jsonify({'success': False, 'error': 'Not authenticated'}), 401
return jsonify({'success': False, 'error': 'Unauthorized'}), 401
data = request.get_json(silent=True) or {}
subscription_obj = data.get('subscription') if 'subscription' in data else data
if not subscription_obj or not isinstance(subscription_obj, dict):
app.logger.error("Invalid subscription payload received")
return jsonify({'success': False, 'error': 'Invalid payload'}), 400
username = session['username']
try:
data = request.get_json(silent=True) or {}
subscription = data.get('subscription')
if not subscription or not subscription.get('endpoint'):
return jsonify({'success': False, 'error': 'Invalid subscription'}), 400
username = session['username']
success = pn.save_push_subscription(username, subscription)
success = pn.save_push_subscription(username, subscription_obj)
if success:
app.logger.info(f'Push subscription saved for {encrypt_text(username)}')
return jsonify({
'success': True,
'message': 'Successfully subscribed to push notifications'
})
return jsonify({'success': True})
else:
return jsonify({'success': False, 'error': 'Failed to save subscription'}), 500
return jsonify({'success': False, 'error': 'Failed to save in DB'}), 400
except Exception as e:
app.logger.error(f'Error subscribing to push: {e}')
return jsonify({'success': False}), 500
app.logger.error(f"Error in subscribe_to_push route: {e}")
return jsonify({'success': False, 'error': 'Internal server error'}), 500
@app.route('/api/push/unsubscribe', methods=['POST'])
+16 -10
View File
@@ -122,29 +122,33 @@ def get_user_subscriptions(username):
def save_push_subscription(username, subscription_obj):
"""Save a new push subscription for a user with field-level encryption."""
import traceback # Hilft uns, Fehler genau zu sehen
try:
print("--- DEBUG PUSH PAYLOAD ---")
print(subscription_obj)
endpoint = subscription_obj.get('endpoint')
keys = subscription_obj.get('keys', {})
if not endpoint or not keys.get('p256dh') or not keys.get('auth'):
logger.warning(f'Invalid subscription object for {username}: missing endpoint or keys')
print(
f"DEBUG FEHLER: Keys fehlen! Endpoint: {bool(endpoint)}, p256dh: {bool(keys.get('p256dh'))}, auth: {bool(keys.get('auth'))}")
return False
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
subs_col = get_push_subscriptions_collection(db)
# Create unique hash of subscription using plaintext data to avoid duplicates
sub_hash = hashlib.shake_256(
f"{username}:{endpoint}".encode('utf-8')
).hexdigest()
# Check if subscription already exists by Hash
existing = subs_col.find_one({
'SubscriptionHash': sub_hash
})
if existing:
subs_col.update_one(
{'_id': existing['_id']},
@@ -156,10 +160,10 @@ def save_push_subscription(username, subscription_obj):
logger.info('Updated existing push subscription')
client.close()
return True
# Format keys as JSON string for your encrypt_text module
keys_str = json.dumps(subscription_obj.get('keys', {}))
# Save new subscription, encrypting sensitive fields
subscription_doc = {
'UsernameHash': _get_username_hash(username),
@@ -172,14 +176,16 @@ def save_push_subscription(username, subscription_obj):
'LastUsed': datetime.datetime.now(),
'UserAgent': subscription_obj.get('userAgent', ''),
}
subs_col.insert_one(subscription_doc)
logger.info('Saved new encrypted push subscription')
client.close()
return True
except Exception as e:
logger.error(f'Error saving push subscription: {e}')
print(f"DEBUG ABSTURZ in save_push_subscription: {e}")
traceback.print_exc()
return False
+10 -6
View File
@@ -161,15 +161,19 @@ class PushNotificationManager {
try {
const subscription = await this.serviceWorkerRegistration.pushManager.getSubscription();
if (!subscription) {
console.warn('No active push subscription');
return true; // Bereits deaktiviert
return true;
}
// Best-Effort: Dem Server Bescheid geben (wir ignorieren absichtlich,
// falls der Server das Abo nicht mehr kennt)
await this.removeSubscriptionFromServer(subscription);
// Best-Effort: Server benachrichtigen (Eigener try/catch Block!)
try {
await this.removeSubscriptionFromServer(subscription);
} catch (serverError) {
// Fehler vom Server ignorieren wir absichtlich.
// Das Skript läuft weiter, statt hier abzubrechen!
console.warn('Server-Abmeldung fehlgeschlagen, lösche lokal trotzdem:', serverError);
}
// WICHTIG: Das Abo im Browser immer zwingend löschen!
// WICHTIG: Das hier wird jetzt garantiert ausgeführt
await subscription.unsubscribe();
return true;