Commits

d3f3nd3r  committed b4dd23c

move auth app to root directory

  • Participants
  • Parent commits 735954b

Comments (0)

Files changed (10)

File djangotoolbox/auth/__init__.py

+import datetime
+from warnings import warn
+from django.core.exceptions import ImproperlyConfigured
+from django.utils.importlib import import_module
+
+SESSION_KEY = '_auth_user_id'
+BACKEND_SESSION_KEY = '_auth_user_backend'
+REDIRECT_FIELD_NAME = 'next'
+
+def load_backend(path):
+    i = path.rfind('.')
+    module, attr = path[:i], path[i+1:]
+    try:
+        mod = import_module(module)
+    except ImportError, e:
+        raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (module, e))
+    except ValueError, e:
+        raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?')
+    try:
+        cls = getattr(mod, attr)
+    except AttributeError:
+        raise ImproperlyConfigured('Module "%s" does not define a "%s" authentication backend' % (module, attr))
+    try:
+        getattr(cls, 'supports_object_permissions')
+    except AttributeError:
+        warn("Authentication backends without a `supports_object_permissions` attribute are deprecated. Please define it in %s." % cls,
+             PendingDeprecationWarning)
+        cls.supports_object_permissions = False
+    try:
+        getattr(cls, 'supports_anonymous_user')
+    except AttributeError:
+        warn("Authentication backends without a `supports_anonymous_user` attribute are deprecated. Please define it in %s." % cls,
+             PendingDeprecationWarning)
+        cls.supports_anonymous_user = False
+    return cls()
+
+def get_backends():
+    from django.conf import settings
+    backends = []
+    for backend_path in settings.AUTHENTICATION_BACKENDS:
+        backends.append(load_backend(backend_path))
+    return backends
+
+def authenticate(**credentials):
+    """
+    If the given credentials are valid, return a User object.
+    """
+    for backend in get_backends():
+        try:
+            user = backend.authenticate(**credentials)
+        except TypeError:
+            # This backend doesn't accept these credentials as arguments. Try the next one.
+            continue
+        if user is None:
+            continue
+        # Annotate the user object with the path of the backend.
+        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
+        return user
+
+def login(request, user):
+    """
+    Persist a user id and a backend in the request. This way a user doesn't
+    have to reauthenticate on every request.
+    """
+    if user is None:
+        user = request.user
+    # TODO: It would be nice to support different login methods, like signed cookies.
+    user.last_login = datetime.datetime.now()
+    user.save()
+
+    if SESSION_KEY in request.session:
+        if request.session[SESSION_KEY] != user.id:
+            # To avoid reusing another user's session, create a new, empty
+            # session if the existing session corresponds to a different
+            # authenticated user.
+            request.session.flush()
+    else:
+        request.session.cycle_key()
+    request.session[SESSION_KEY] = user.id
+    request.session[BACKEND_SESSION_KEY] = user.backend
+    if hasattr(request, 'user'):
+        request.user = user
+
+def logout(request):
+    """
+    Removes the authenticated user's ID from the request and flushes their
+    session data.
+    """
+    request.session.flush()
+    if hasattr(request, 'user'):
+        from djangotoolbox.contrib.auth.models import AnonymousUser
+        request.user = AnonymousUser()
+
+def get_user(request):
+    from djangotoolbox.contrib.auth.models import AnonymousUser
+    try:
+        user_id = request.session[SESSION_KEY]
+        backend_path = request.session[BACKEND_SESSION_KEY]
+        backend = load_backend(backend_path)
+        user = backend.get_user(user_id) or AnonymousUser()
+    except KeyError:
+        user = AnonymousUser()
+    return user

File djangotoolbox/auth/backends.py

+try:
+    set
+except NameError:
+    from sets import Set as set # Python 2.3 fallback
+
+from django.db import connection
+from django.contrib.auth.backends import ModelBackend
+from django.contrib.auth.models import User, Permission, Group
+from django.contrib.contenttypes.models import ContentType
+from djangotoolbox.contrib.auth.models import UserPermissionList, GroupPermissionList, GroupList
+
+
+class NonrelModelBackend(object):
+    """
+    Authenticates against djangotoolbox.contrib.auth.models.User.
+    """
+    supports_object_permissions = False
+    supports_anonymous_user = True
+
+    django_backend = ModelBackend() # use default django backend for authentication
+    
+    # TODO: Model, login attribute name and password attribute name should be
+    # configurable.
+    def authenticate(self, username=None, password=None):
+        return self.django_backend.authenticate(username, password)
+ 
+    def get_group_permissions(self, user_obj):
+        """
+        Returns a set of permission strings that this user has through his/her
+        groups.
+        """
+        if not hasattr(user_obj, '_group_perm_cache'):
+            perm_objs = set([])
+            try:
+                gl = GroupList.objects.get(user=user_obj)
+                group_ids = gl._fk_list
+                if len(group_ids) > 0:
+                    group_permissions = set()
+                    for group_id in group_ids:
+                        group_permissions.update(GroupPermissionList.objects.filter(group__id=group_id))
+                    for group_perm in group_permissions:
+                        perm_objs.update(group_perm.permissions)
+                    
+            except GroupList.DoesNotExist:
+                pass
+            
+            perms = list([[perm.content_type.app_label, perm.codename] for perm in perm_objs])
+            user_obj._group_perm_cache = set(["%s.%s" % (ct, name) for ct, name in perms])
+        return user_obj._group_perm_cache
+
+    def get_all_permissions(self, user_obj):
+        if user_obj.is_anonymous():
+            return set()
+        if not hasattr(user_obj, '_perm_cache'):
+            try:
+                pl = UserPermissionList.objects.get(user=user_obj)
+                user_obj._perm_cache = set([u"%s.%s" % (p.content_type.app_label, p.codename) for p in pl.permissions])
+            except UserPermissionList.DoesNotExist:
+                user_obj._perm_cache = set()
+                pass
+            user_obj._perm_cache.update(self.get_group_permissions(user_obj))
+        return user_obj._perm_cache
+
+    def has_perm(self, user_obj, perm):
+        return perm in self.get_all_permissions(user_obj)
+
+    def has_module_perms(self, user_obj, app_label):
+        """
+        Returns True if user_obj has any permissions in the given app_label.
+        """
+        for perm in self.get_all_permissions(user_obj):
+            if perm[:perm.index('.')] == app_label:
+                return True
+        return False
+
+    def get_user(self, user_id):
+        try:
+            return User.objects.get(pk=user_id)
+        except User.DoesNotExist:
+            return None

File djangotoolbox/auth/models.py

+from django.db import models
+from django.contrib.auth.models import User, Group, Permission
+
+from djangotoolbox.fields import ListField
+
+def get_objs(obj_cls, obj_ids):
+    objs = set()
+    if len(obj_ids) > 0:
+        # order_by() has to be used to override invalid default Permission filter
+        objs.update(obj_cls .objects.filter(id__in=obj_ids).order_by('name'))
+    return objs
+
+class UserPermissionList(models.Model):
+    user = models.ForeignKey(User)
+    _fk_list = ListField(models.ForeignKey(Permission))
+
+    def _get_permissions(self):
+        if not hasattr(self, '_permissions_cache'):
+            setattr(self, '_permissions_cache', get_objs(Permission, self._fk_list))            
+        return self._permissions_cache
+    permissions = property(_get_permissions)
+
+
+class GroupPermissionList(models.Model):
+    group = models.ForeignKey(Group)
+    _fk_list = ListField(models.ForeignKey(Permission))
+
+    def _get_permissions(self):
+        if not hasattr(self, '_permissions_cache'):
+            setattr(self, '_permissions_cache', get_objs(Permission, self._fk_list))            
+        return self._permissions_cache
+    permissions = property(_get_permissions)
+
+class GroupList(models.Model):
+    """
+    GroupLists are used to map a list of groups to a user
+    """
+    user = models.ForeignKey(User)
+    _fk_list = ListField(models.ForeignKey(Group))
+
+    def __unicode__(self):
+        return u'%s' %(self.user.username)
+    
+    def _get_group_list(self):
+        if not hasattr(self, '_groups_cache'):
+            setattr(self, '_groups_cache', get_objs(Group, self._fk_list))
+        return self._groups_cache
+    groups = property(_get_group_list)

File djangotoolbox/auth/tests.py

+from django.conf import settings
+from django.db import models
+from django.contrib.auth import authenticate
+from django.contrib.auth.models import User, Group, Permission, AnonymousUser
+from django.contrib.contenttypes.models import ContentType
+from django.test import TestCase
+
+from djangotoolbox.contrib.auth.models import UserPermissionList, GroupPermissionList, GroupList
+from djangotoolbox.contrib.auth.utils import add_permission_to_user, add_user_to_group, add_permission_to_group
+
+
+class BackendTest(TestCase):
+
+    backend = 'djangotoolbox.contrib.auth.backends.NonrelModelBackend'
+
+    def setUp(self):
+        User.objects.create_user('test', 'test@example.com', 'test')
+
+    def test_add_permission_to_user(self):
+        content_type=ContentType.objects.get_for_model(User)
+        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
+        user = User.objects.get(username='test')
+        self.assertEqual(user.has_perm('auth.test'), False)
+        user = User.objects.get(username='test')
+        add_permission_to_user(perm, user)
+        self.assertEqual(UserPermissionList.objects.count(), 1)
+        pl = UserPermissionList.objects.all()[0]
+        self.assertEqual(pl.permissions , set([perm]))
+        self.assertEqual(user.has_perm('auth.test'), True)
+
+    def test_add_user_to_group(self):
+        user = User.objects.get(username='test')
+        group = Group.objects.create(name='test_group')
+        add_user_to_group(user, group)
+        self.assertEqual(GroupList.objects.count(), 1)
+        self.assertNotEqual(GroupList.objects.all()[0] , None)
+
+    def test_add_permission_to_group(self):
+        content_type=ContentType.objects.get_for_model(Group)
+        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
+        user = User.objects.get(username='test')
+        self.assertEqual(user.has_perm('auth.test'), False)
+        user = User.objects.get(username='test')
+        group = Group.objects.create(name='test_group')
+        add_user_to_group(user, group)
+        add_permission_to_group(perm, group)
+        self.assertEqual(GroupPermissionList.objects.count(), 1)
+        gl = GroupPermissionList.objects.all()[0]
+        self.assertEqual(gl.permissions , set([perm]))
+        self.assertEqual(user.has_perm('auth.test'), True)
+        
+    def test_has_perm(self):
+        user = User.objects.get(username='test')
+        self.assertEqual(user.has_perm('auth.test'), False)
+        user.is_staff = True
+        user.save()
+        self.assertEqual(user.has_perm('auth.test'), False)
+        user.is_superuser = True
+        user.save()
+        self.assertEqual(user.has_perm('auth.test'), True)
+        user.is_staff = False
+        user.is_superuser = False
+        user.save()
+        self.assertEqual(user.has_perm('auth.test'), False)
+        user.is_staff = True
+        user.is_superuser = True
+        user.is_active = False
+        user.save()
+        self.assertEqual(user.has_perm('auth.test'), False)
+        
+        
+    def test_custom_perms(self):
+        user = User.objects.get(username='test')
+        content_type=ContentType.objects.get_for_model(Permission)
+        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
+        # default django way (ManyToManyField)
+        #user.user_permissions.add(perm)      
+
+        add_permission_to_user(perm, user)
+        
+        # reloading user to purge the _perm_cache
+        user = User.objects.get(username='test')
+        self.assertEqual(user.get_all_permissions() == set([u'auth.test']), True)
+        self.assertEqual(user.get_group_permissions(), set([]))
+        self.assertEqual(user.has_module_perms('Group'), False)
+        self.assertEqual(user.has_module_perms('auth'), True)
+        
+        perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2')
+        
+        # default django way (ManyToManyField)
+        #user.user_permissions.add(perm)
+
+        add_permission_to_user(perm, user)
+        
+        perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3')
+
+        # default django  way (ManyToManyField)
+        #user.user_permissions.add(perm)
+
+        add_permission_to_user(perm, user)
+
+        user = User.objects.get(username='test')
+        self.assertEqual(user.get_all_permissions(), set([u'auth.test2', u'auth.test', u'auth.test3']))
+        self.assertEqual(user.has_perm('test'), False)
+        self.assertEqual(user.has_perm('auth.test'), True)
+        self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True)
+        
+        perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group')
+        group = Group.objects.create(name='test_group')
+
+        # default django way (ManyToManyField)
+        #group.permissions.add(perm)
+
+        add_permission_to_group(perm, group)
+
+        # default django way (ManyToManyField)
+        #user.groups.add(group)
+
+        add_user_to_group(user, group)
+        
+        user = User.objects.get(username='test')
+        exp = set([u'auth.test2', u'auth.test', u'auth.test3', u'auth.test_group'])
+        self.assertEqual(user.get_all_permissions(), exp)
+        self.assertEqual(user.get_group_permissions(), set([u'auth.test_group']))
+        self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True)
+
+        user = AnonymousUser()
+        self.assertEqual(user.has_perm('test'), False)
+        self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), False)
+        
+        
+    def test_has_no_object_perm(self):
+        """Regressiontest for #12462"""
+        
+        user = User.objects.get(username='test')
+        content_type=ContentType.objects.get_for_model(Group)
+        content_type.save()
+        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
+        
+        # default django way (ManyToManyField)
+        #user.user_permissions.add(perm)
+
+        add_permission_to_user(perm, user)
+
+        self.assertEqual(user.has_perm('auth.test', 'object'), False)
+        self.assertEqual(user.get_all_permissions('object'), set([]))
+        self.assertEqual(user.has_perm('auth.test'), True)
+        self.assertEqual(user.get_all_permissions(), set(['auth.test']))
+        
+
+    def test_authenticate(self):
+       user = User.objects.get(username='test')
+       self.assertEquals(authenticate(username='test', password='test'), user)
+       self.assertEquals(authenticate(username='test', password='testNones'), None)

File djangotoolbox/auth/utils.py

+from djangotoolbox.contrib.auth.models import UserPermissionList, GroupPermissionList, GroupList
+
+def add_to(obj, list_cls, filter):
+    try:
+        obj_list = list_cls.objects.get(**filter)
+    except list_cls.DoesNotExist:
+        obj_list = list_cls.objects.create(**filter)
+
+    obj_list._fk_list.append(obj.id)
+    obj_list.save()
+
+def add_permission_to_user(perm, user):
+    add_to(perm, UserPermissionList,  {'user': user }) 
+
+def add_user_to_group(user, group):
+    add_to(group, GroupList, {'user': user})
+        
+def add_permission_to_group(perm, group):
+    add_to(perm, GroupPermissionList, {'group': group})
+

File djangotoolbox/contrib/auth/__init__.py

-import datetime
-from warnings import warn
-from django.core.exceptions import ImproperlyConfigured
-from django.utils.importlib import import_module
-
-SESSION_KEY = '_auth_user_id'
-BACKEND_SESSION_KEY = '_auth_user_backend'
-REDIRECT_FIELD_NAME = 'next'
-
-def load_backend(path):
-    i = path.rfind('.')
-    module, attr = path[:i], path[i+1:]
-    try:
-        mod = import_module(module)
-    except ImportError, e:
-        raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (module, e))
-    except ValueError, e:
-        raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?')
-    try:
-        cls = getattr(mod, attr)
-    except AttributeError:
-        raise ImproperlyConfigured('Module "%s" does not define a "%s" authentication backend' % (module, attr))
-    try:
-        getattr(cls, 'supports_object_permissions')
-    except AttributeError:
-        warn("Authentication backends without a `supports_object_permissions` attribute are deprecated. Please define it in %s." % cls,
-             PendingDeprecationWarning)
-        cls.supports_object_permissions = False
-    try:
-        getattr(cls, 'supports_anonymous_user')
-    except AttributeError:
-        warn("Authentication backends without a `supports_anonymous_user` attribute are deprecated. Please define it in %s." % cls,
-             PendingDeprecationWarning)
-        cls.supports_anonymous_user = False
-    return cls()
-
-def get_backends():
-    from django.conf import settings
-    backends = []
-    for backend_path in settings.AUTHENTICATION_BACKENDS:
-        backends.append(load_backend(backend_path))
-    return backends
-
-def authenticate(**credentials):
-    """
-    If the given credentials are valid, return a User object.
-    """
-    for backend in get_backends():
-        try:
-            user = backend.authenticate(**credentials)
-        except TypeError:
-            # This backend doesn't accept these credentials as arguments. Try the next one.
-            continue
-        if user is None:
-            continue
-        # Annotate the user object with the path of the backend.
-        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
-        return user
-
-def login(request, user):
-    """
-    Persist a user id and a backend in the request. This way a user doesn't
-    have to reauthenticate on every request.
-    """
-    if user is None:
-        user = request.user
-    # TODO: It would be nice to support different login methods, like signed cookies.
-    user.last_login = datetime.datetime.now()
-    user.save()
-
-    if SESSION_KEY in request.session:
-        if request.session[SESSION_KEY] != user.id:
-            # To avoid reusing another user's session, create a new, empty
-            # session if the existing session corresponds to a different
-            # authenticated user.
-            request.session.flush()
-    else:
-        request.session.cycle_key()
-    request.session[SESSION_KEY] = user.id
-    request.session[BACKEND_SESSION_KEY] = user.backend
-    if hasattr(request, 'user'):
-        request.user = user
-
-def logout(request):
-    """
-    Removes the authenticated user's ID from the request and flushes their
-    session data.
-    """
-    request.session.flush()
-    if hasattr(request, 'user'):
-        from djangotoolbox.contrib.auth.models import AnonymousUser
-        request.user = AnonymousUser()
-
-def get_user(request):
-    from djangotoolbox.contrib.auth.models import AnonymousUser
-    try:
-        user_id = request.session[SESSION_KEY]
-        backend_path = request.session[BACKEND_SESSION_KEY]
-        backend = load_backend(backend_path)
-        user = backend.get_user(user_id) or AnonymousUser()
-    except KeyError:
-        user = AnonymousUser()
-    return user

File djangotoolbox/contrib/auth/backends.py

-try:
-    set
-except NameError:
-    from sets import Set as set # Python 2.3 fallback
-
-from django.db import connection
-from django.contrib.auth.backends import ModelBackend
-from django.contrib.auth.models import User, Permission, Group
-from django.contrib.contenttypes.models import ContentType
-from djangotoolbox.contrib.auth.models import UserPermissionList, GroupPermissionList, GroupList
-
-
-class NonrelModelBackend(object):
-    """
-    Authenticates against djangotoolbox.contrib.auth.models.User.
-    """
-    supports_object_permissions = False
-    supports_anonymous_user = True
-
-    django_backend = ModelBackend() # use default django backend for authentication
-    
-    # TODO: Model, login attribute name and password attribute name should be
-    # configurable.
-    def authenticate(self, username=None, password=None):
-        return self.django_backend.authenticate(username, password)
- 
-    def get_group_permissions(self, user_obj):
-        """
-        Returns a set of permission strings that this user has through his/her
-        groups.
-        """
-        if not hasattr(user_obj, '_group_perm_cache'):
-            perm_objs = set([])
-            try:
-                gl = GroupList.objects.get(user=user_obj)
-                group_ids = gl._fk_list
-                if len(group_ids) > 0:
-                    group_permissions = set()
-                    for group_id in group_ids:
-                        group_permissions.update(GroupPermissionList.objects.filter(group__id=group_id))
-                    for group_perm in group_permissions:
-                        perm_objs.update(group_perm.permissions)
-                    
-            except GroupList.DoesNotExist:
-                pass
-            
-            perms = list([[perm.content_type.app_label, perm.codename] for perm in perm_objs])
-            user_obj._group_perm_cache = set(["%s.%s" % (ct, name) for ct, name in perms])
-        return user_obj._group_perm_cache
-
-    def get_all_permissions(self, user_obj):
-        if user_obj.is_anonymous():
-            return set()
-        if not hasattr(user_obj, '_perm_cache'):
-            try:
-                pl = UserPermissionList.objects.get(user=user_obj)
-                user_obj._perm_cache = set([u"%s.%s" % (p.content_type.app_label, p.codename) for p in pl.permissions])
-            except UserPermissionList.DoesNotExist:
-                user_obj._perm_cache = set()
-                pass
-            user_obj._perm_cache.update(self.get_group_permissions(user_obj))
-        return user_obj._perm_cache
-
-    def has_perm(self, user_obj, perm):
-        return perm in self.get_all_permissions(user_obj)
-
-    def has_module_perms(self, user_obj, app_label):
-        """
-        Returns True if user_obj has any permissions in the given app_label.
-        """
-        for perm in self.get_all_permissions(user_obj):
-            if perm[:perm.index('.')] == app_label:
-                return True
-        return False
-
-    def get_user(self, user_id):
-        try:
-            return User.objects.get(pk=user_id)
-        except User.DoesNotExist:
-            return None

File djangotoolbox/contrib/auth/models.py

-from django.db import models
-from django.contrib.auth.models import User, Group, Permission
-
-from djangotoolbox.fields import ListField
-
-def get_objs(obj_cls, obj_ids):
-    objs = set()
-    if len(obj_ids) > 0:
-        # order_by() has to be used to override invalid default Permission filter
-        objs.update(obj_cls .objects.filter(id__in=obj_ids).order_by('name'))
-    return objs
-
-class UserPermissionList(models.Model):
-    user = models.ForeignKey(User)
-    _fk_list = ListField(models.ForeignKey(Permission))
-
-    def _get_permissions(self):
-        if not hasattr(self, '_permissions_cache'):
-            setattr(self, '_permissions_cache', get_objs(Permission, self._fk_list))            
-        return self._permissions_cache
-    permissions = property(_get_permissions)
-
-
-class GroupPermissionList(models.Model):
-    group = models.ForeignKey(Group)
-    _fk_list = ListField(models.ForeignKey(Permission))
-
-    def _get_permissions(self):
-        if not hasattr(self, '_permissions_cache'):
-            setattr(self, '_permissions_cache', get_objs(Permission, self._fk_list))            
-        return self._permissions_cache
-    permissions = property(_get_permissions)
-
-class GroupList(models.Model):
-    """
-    GroupLists are used to map a list of groups to a user
-    """
-    user = models.ForeignKey(User)
-    _fk_list = ListField(models.ForeignKey(Group))
-
-    def __unicode__(self):
-        return u'%s' %(self.user.username)
-    
-    def _get_group_list(self):
-        if not hasattr(self, '_groups_cache'):
-            setattr(self, '_groups_cache', get_objs(Group, self._fk_list))
-        return self._groups_cache
-    groups = property(_get_group_list)

File djangotoolbox/contrib/auth/tests.py

-from django.conf import settings
-from django.db import models
-from django.contrib.auth import authenticate
-from django.contrib.auth.models import User, Group, Permission, AnonymousUser
-from django.contrib.contenttypes.models import ContentType
-from django.test import TestCase
-
-from djangotoolbox.contrib.auth.models import UserPermissionList, GroupPermissionList, GroupList
-from djangotoolbox.contrib.auth.utils import add_permission_to_user, add_user_to_group, add_permission_to_group
-
-
-class BackendTest(TestCase):
-
-    backend = 'djangotoolbox.contrib.auth.backends.NonrelModelBackend'
-
-    def setUp(self):
-        User.objects.create_user('test', 'test@example.com', 'test')
-
-    def test_add_permission_to_user(self):
-        content_type=ContentType.objects.get_for_model(User)
-        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
-        user = User.objects.get(username='test')
-        self.assertEqual(user.has_perm('auth.test'), False)
-        user = User.objects.get(username='test')
-        add_permission_to_user(perm, user)
-        self.assertEqual(UserPermissionList.objects.count(), 1)
-        pl = UserPermissionList.objects.all()[0]
-        self.assertEqual(pl.permissions , set([perm]))
-        self.assertEqual(user.has_perm('auth.test'), True)
-
-    def test_add_user_to_group(self):
-        user = User.objects.get(username='test')
-        group = Group.objects.create(name='test_group')
-        add_user_to_group(user, group)
-        self.assertEqual(GroupList.objects.count(), 1)
-        self.assertNotEqual(GroupList.objects.all()[0] , None)
-
-    def test_add_permission_to_group(self):
-        content_type=ContentType.objects.get_for_model(Group)
-        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
-        user = User.objects.get(username='test')
-        self.assertEqual(user.has_perm('auth.test'), False)
-        user = User.objects.get(username='test')
-        group = Group.objects.create(name='test_group')
-        add_user_to_group(user, group)
-        add_permission_to_group(perm, group)
-        self.assertEqual(GroupPermissionList.objects.count(), 1)
-        gl = GroupPermissionList.objects.all()[0]
-        self.assertEqual(gl.permissions , set([perm]))
-        self.assertEqual(user.has_perm('auth.test'), True)
-        
-    def test_has_perm(self):
-        user = User.objects.get(username='test')
-        self.assertEqual(user.has_perm('auth.test'), False)
-        user.is_staff = True
-        user.save()
-        self.assertEqual(user.has_perm('auth.test'), False)
-        user.is_superuser = True
-        user.save()
-        self.assertEqual(user.has_perm('auth.test'), True)
-        user.is_staff = False
-        user.is_superuser = False
-        user.save()
-        self.assertEqual(user.has_perm('auth.test'), False)
-        user.is_staff = True
-        user.is_superuser = True
-        user.is_active = False
-        user.save()
-        self.assertEqual(user.has_perm('auth.test'), False)
-        
-        
-    def test_custom_perms(self):
-        user = User.objects.get(username='test')
-        content_type=ContentType.objects.get_for_model(Permission)
-        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
-        # default django way (ManyToManyField)
-        #user.user_permissions.add(perm)      
-
-        add_permission_to_user(perm, user)
-        
-        # reloading user to purge the _perm_cache
-        user = User.objects.get(username='test')
-        self.assertEqual(user.get_all_permissions() == set([u'auth.test']), True)
-        self.assertEqual(user.get_group_permissions(), set([]))
-        self.assertEqual(user.has_module_perms('Group'), False)
-        self.assertEqual(user.has_module_perms('auth'), True)
-        
-        perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2')
-        
-        # default django way (ManyToManyField)
-        #user.user_permissions.add(perm)
-
-        add_permission_to_user(perm, user)
-        
-        perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3')
-
-        # default django  way (ManyToManyField)
-        #user.user_permissions.add(perm)
-
-        add_permission_to_user(perm, user)
-
-        user = User.objects.get(username='test')
-        self.assertEqual(user.get_all_permissions(), set([u'auth.test2', u'auth.test', u'auth.test3']))
-        self.assertEqual(user.has_perm('test'), False)
-        self.assertEqual(user.has_perm('auth.test'), True)
-        self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True)
-        
-        perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group')
-        group = Group.objects.create(name='test_group')
-
-        # default django way (ManyToManyField)
-        #group.permissions.add(perm)
-
-        add_permission_to_group(perm, group)
-
-        # default django way (ManyToManyField)
-        #user.groups.add(group)
-
-        add_user_to_group(user, group)
-        
-        user = User.objects.get(username='test')
-        exp = set([u'auth.test2', u'auth.test', u'auth.test3', u'auth.test_group'])
-        self.assertEqual(user.get_all_permissions(), exp)
-        self.assertEqual(user.get_group_permissions(), set([u'auth.test_group']))
-        self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True)
-
-        user = AnonymousUser()
-        self.assertEqual(user.has_perm('test'), False)
-        self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), False)
-        
-        
-    def test_has_no_object_perm(self):
-        """Regressiontest for #12462"""
-        
-        user = User.objects.get(username='test')
-        content_type=ContentType.objects.get_for_model(Group)
-        content_type.save()
-        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
-        
-        # default django way (ManyToManyField)
-        #user.user_permissions.add(perm)
-
-        add_permission_to_user(perm, user)
-
-        self.assertEqual(user.has_perm('auth.test', 'object'), False)
-        self.assertEqual(user.get_all_permissions('object'), set([]))
-        self.assertEqual(user.has_perm('auth.test'), True)
-        self.assertEqual(user.get_all_permissions(), set(['auth.test']))
-        
-
-    def test_authenticate(self):
-       user = User.objects.get(username='test')
-       self.assertEquals(authenticate(username='test', password='test'), user)
-       self.assertEquals(authenticate(username='test', password='testNones'), None)

File djangotoolbox/contrib/auth/utils.py

-from djangotoolbox.contrib.auth.models import UserPermissionList, GroupPermissionList, GroupList
-
-def add_to(obj, list_cls, filter):
-    try:
-        obj_list = list_cls.objects.get(**filter)
-    except list_cls.DoesNotExist:
-        obj_list = list_cls.objects.create(**filter)
-
-    obj_list._fk_list.append(obj.id)
-    obj_list.save()
-
-def add_permission_to_user(perm, user):
-    add_to(perm, UserPermissionList,  {'user': user }) 
-
-def add_user_to_group(user, group):
-    add_to(group, GroupList, {'user': user})
-        
-def add_permission_to_group(perm, group):
-    add_to(perm, GroupPermissionList, {'group': group})
-