from django.conf import settings
from django.core.exceptions import MiddlewareNotUsed
from ldt.security.utils import protect_models, unprotect_models, _thread_locals

class SecurityMiddleware(object):
    
    def __init__(self):
        if not hasattr(settings, 'USE_GROUP_PERMISSIONS') or not settings.USE_GROUP_PERMISSIONS:
            raise MiddlewareNotUsed()

    def process_request(self, request):
        if not hasattr(_thread_locals, 'user'):
            _thread_locals.user = request.user
            protect_models()
    
    def process_response(self, request, response):
        unprotect_models()
        
        if hasattr(_thread_locals, 'user'):
            del _thread_locals.user
                
        return response
    