from django.conf import settings
from ldt.ldt_utils import protect_class, unprotect_class
from ldt.ldt_utils.models import Project, Content
from django.core.exceptions import MiddlewareNotUsed

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

    # This is not thread-safe :
    # It is not granted that the middleware is atomic with the view,
    # so maybe the middleware chose will not be the one used in 
    # the view afterwards

    def process_request(self, request):
        
        if settings.USE_GROUP_PERMISSIONS == 'all':
            protect_class(Project, request.user) 
            protect_class(Content, request.user)
            
        for cls_name in settings.USE_GROUP_PERMISSIONS.split(' '):
            if cls_name == 'Project':
                protect_class(Project, request.user)
            elif cls_name == 'Content':
                protect_class(Content, request.user)
        
    
    def process_response(self, request, response):
        unprotect_class(Project)
        unprotect_class(Content)
        
        return response