|
1 | 1 | from django.conf import settings |
2 | 2 | from django.utils.deprecation import MiddlewareMixin |
3 | 3 | from django.core.cache import cache |
4 | | -from django.db import transaction |
| 4 | +from django.db import transaction, connection |
5 | 5 | from .utils import get_user_agent, get_client_ip, LazyEncoder |
6 | 6 | from .models import ActivityLog |
7 | 7 |
|
@@ -73,20 +73,54 @@ def process_request(self, request): |
73 | 73 | self._enqueue_activity_log_creation(request, user_agent) |
74 | 74 |
|
75 | 75 | def _enqueue_activity_log_creation(self, request, user_agent): |
76 | | - from concurrent.futures import ThreadPoolExecutor |
77 | | - with ThreadPoolExecutor(max_workers=1) as executor: |
78 | | - executor.submit(self._create_activity_log, request, user_agent) |
| 76 | + # Extract data from request before threading to avoid context issues |
| 77 | + log_data = { |
| 78 | + 'user_id': request.user.id, |
| 79 | + 'service': request.POST.get("s", "unknown"), |
| 80 | + 'method': request.method, |
| 81 | + 'params': self.clean_params(request.POST or request.GET or {}), |
| 82 | + 'path': request.path, |
| 83 | + 'ip': get_client_ip(request), |
| 84 | + 'user_agent': user_agent, |
| 85 | + } |
| 86 | + |
| 87 | + # Use threading.Thread instead of ThreadPoolExecutor for simpler lifecycle |
| 88 | + import threading |
| 89 | + thread = threading.Thread(target=self._create_activity_log_safe, args=(log_data,), daemon=True) |
| 90 | + thread.start() |
79 | 91 |
|
| 92 | + def clean_params(self, params): |
| 93 | + """Clean sensitive parameters before logging.""" |
| 94 | + cleaned = dict(params) |
| 95 | + sensitive_keys = ['password', 'passwd', 'pwd', 'secret', 'token', 'api_key', 'apikey'] |
| 96 | + for key in list(cleaned.keys()): |
| 97 | + if any(sensitive in key.lower() for sensitive in sensitive_keys): |
| 98 | + cleaned[key] = '***REDACTED***' |
| 99 | + return cleaned |
| 100 | + |
| 101 | + def _create_activity_log_safe(self, log_data): |
| 102 | + """Thread-safe activity log creation with proper DB connection handling.""" |
| 103 | + try: |
| 104 | + self._create_activity_log(log_data) |
| 105 | + except Exception as e: |
| 106 | + logger.error(f"Failed to create activity log: {str(e)}", exc_info=True) |
| 107 | + finally: |
| 108 | + # Close database connection for this thread |
| 109 | + connection.close() |
| 110 | + |
80 | 111 | @transaction.atomic |
81 | | - def _create_activity_log(self, request, user_agent): |
82 | | - params = self.clean_params(request.POST or request.GET or {}) |
| 112 | + def _create_activity_log(self, log_data): |
| 113 | + from django.contrib.auth import get_user_model |
| 114 | + User = get_user_model() |
| 115 | + |
| 116 | + user = User.objects.get(id=log_data['user_id']) |
83 | 117 | activity_log = ActivityLog( |
84 | | - user=request.user, |
85 | | - service=request.POST.get("s", "unknown"), |
86 | | - method=request.method, |
87 | | - params=json.dumps(params, cls=LazyEncoder), |
88 | | - path=request.path, |
89 | | - ip=get_client_ip(request), |
90 | | - user_agent=json.dumps(user_agent.__dict__ or {}, cls=LazyEncoder), |
| 118 | + user=user, |
| 119 | + service=log_data['service'], |
| 120 | + method=log_data['method'], |
| 121 | + params=json.dumps(log_data['params'], cls=LazyEncoder), |
| 122 | + path=log_data['path'], |
| 123 | + ip=log_data['ip'], |
| 124 | + user_agent=json.dumps(log_data['user_agent'].__dict__ or {}, cls=LazyEncoder), |
91 | 125 | ) |
92 | 126 | activity_log.save() |
0 commit comments