mnemo_cards/mnemo_cards_backend/lib/statistics/session_tracking_middleware.dart
Dmitry 306b2fdca7
Some checks are pending
Backend CI / test (push) Waiting to run
Backend CI / build (push) Blocked by required conditions
Deploy Mnemo Cards / Deploy Backend (push) Waiting to run
Deploy Mnemo Cards / Deploy Web App (push) Blocked by required conditions
Deploy Mnemo Cards / Final Verification (push) Blocked by required conditions
Deploy Telegram Bot / Deploy Telegram Bot (push) Waiting to run
fixes
2025-12-13 17:48:00 +03:00

35 lines
1.3 KiB
Dart

import 'dart:developer';
import 'package:mnemo_cards_backend/api/authorize/helpers.dart';
import 'package:mnemo_cards_backend/statistics/session_tracker.dart';
import 'package:shelf/shelf.dart';
/// Middleware for tracking user study sessions based on API activity
///
/// This middleware automatically updates user sessions when they make authenticated
/// API requests, ensuring session tracking covers all user activities beyond just tests.
Middleware sessionTrackingMiddleware(SessionTracker sessionTracker) {
return (Handler inner) {
return (Request request) async {
final user = request.user;
// Only track sessions for authenticated users
if (user != null && user.id != null) {
try {
// Get or create session for this user
// We don't specify packId or testId here since this is general activity tracking
await sessionTracker.getOrCreateSession(user.id!);
// Note: We don't update progress here since we don't know what the user is doing
// Progress updates happen in specific handlers (like test completion)
} catch (e) {
// Log error but don't fail the request - session tracking is not critical
log('Session tracking middleware error: $e');
}
}
// Continue with the request
return await inner(request);
};
};
}