import threading
from django.utils.deprecation import MiddlewareMixin

_local = threading.local()

def get_current_username():
    u = getattr(_local, "user", None)
    if not u or not getattr(u, "is_authenticated", False):
        return ""
    return getattr(u, "username", "") or ""

class CurrentUserMiddleware(MiddlewareMixin):
    def process_request(self, request):
        _local.user = getattr(request, "user", None)
    def process_response(self, request, response):
        _local.user = None
        return response
    def process_exception(self, request, exception):
        _local.user = None
        return None