django-perms / perms / managers.py

from django.db import models
from django.contrib.contenttypes.models import ContentType


class SecureQuerySet(models.query.QuerySet):
    def secure(self, user, perm):
        clone = self._clone()
        perms_class = models.get_model('perms', 'ObjectPermission')
        content_type = ContentType.objects.get_for_model(self.model)
        data = {
            'obj_table': clone.model._meta.db_table,
            'obj_column': clone.model._meta.pk.column,
            'perm_table': perms_class._meta.db_table,
            'content_type_id': content_type.pk,
        }
        where = [
            # user constraint
            '%(perm_table)s.user_id = ' % data + '%d',
            # content_type constraint
            "%(perm_table)s.content_type_id = %(content_type_id)s" % data,
            # object id constraint
            "%(obj_table)s.%(obj_column)s = %(perm_table)s.object_id" % data,
        ]
        return clone.extra(tables=[data['perm_table']], where=where,
                           params=[user.pk])


class SecureManager(models.Manager):
    def secure(self, user, perm):
        return SecureQuerySet(model=self.model).secure(user, perm)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.