Source

django-extauth / extperms / fieldperms / management / __init__.py

Full commit
'''
Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
All rights reserved.

@author: Michael Hall <mhall119@gmail.com>
'''

from django.db.models import get_models, signals
from django.contrib.auth import models as auth_app
from django.db.models import get_apps, get_models, signals

def create_model_permissions(app, created_models, verbosity, **kargs):
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.auth.models import Permission
    app_models = get_models(app)
    if not app_models:
        return
    for klass in app_models:
        ctype = ContentType.objects.get_for_model(klass)
        for codename, name in _get_all_permissions(klass):
            p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id,
                defaults={'name': name, 'content_type': ctype})
            if created and verbosity >= 2:
                print "Adding permission '%s'" % p
        
def _get_all_permissions(klass):
    "Returns (codename, name) for all permissions in the given opts."
    from o9 import permissions
    perms = [('read_%s' % klass._meta.object_name.lower(), u'Can read %s' % klass._meta.verbose_name_raw),]
    for field in klass._meta.fields + klass._meta.many_to_many:
        if field.name != 'id':
            perms.append(('modify_%s__%s' % (klass._meta.object_name.lower(), field.name), u'Can modify %s %s' % (klass._meta.verbose_name_raw, field.name)))
            perms.append(('view_%s__%s' % (klass._meta.object_name.lower(), field.name), u'Can view %s %s' % (klass._meta.verbose_name_raw, field.name)))
    return perms

signals.post_syncdb.connect(create_model_permissions,
    dispatch_uid = "o9.management.create_model_permissions")

def create_page_permissions(app, created_models, verbosity, **kwargs):
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.auth.models import Permission
    from django.contrib.sites.models import Site
    from o9 import sites
    
    ctype = ContentType.objects.get_for_model(Site)
    
    for s in sites.managed_sites:
        if hasattr(s.Meta, 'permissions') and isinstance(s.Meta.permissions, (list, tuple)):
            for (codename, name) in s.Meta.permissions:
                p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id,
                    defaults={'name': name, 'content_type': ctype})
                if created and verbosity >= 2:
                    print "Adding permission '%s'" % p            

signals.post_syncdb.connect(create_page_permissions,
    dispatch_uid = "o9.management.create_page_permissions")