from django.db.models import Manager
from guardian.shortcuts import get_objects_for_user
from ldt.security import get_current_user, get_anonymous_user

class SafeManager(Manager):
    use_for_related_fields = True
    
    def __init__(self, check_perm=False):
        super(SafeManager, self).__init__()
        self.check_perm = check_perm

    def get_query_set(self):
        
        if not self.check_perm:
            return super(SafeManager, self).get_query_set()   
      
        user = get_current_user()            

        if not user:
            raise AttributeError("No user is attached to the current thread.")
        
        if not user.is_authenticated():
            user = get_anonymous_user()
        
        perm_name = '%s.view_%s' % (self.model._meta.app_label, self.model.__name__.lower()) 
        
        user_objects = get_objects_for_user(user, perm_name, klass=self.model.objects) 
                    
        return user_objects