Source

django-extauth / extauth / management / __init__.py

'''
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_roles(app, created_models, verbosity, **kwargs):
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.auth.models import Permission
    from extauth.auth.models import Role
    from extauth.auth import roles
    roles.autodiscover()
    
    if not roles.registered_roles:
        return
    for klass in roles.registered_roles.keys():
        ctype = ContentType.objects.get_for_model(klass)
        rm = roles.get_rolemanager(klass)
        
        for rName in rm._roles:
            r, created = Role.objects.get_or_create(role=rName, model__pk=ctype.id,
                defaults={'model': ctype})
            if created and verbosity >= 2:
                print "Adding role '%s'" % r

signals.post_syncdb.connect(create_roles,
    dispatch_uid = "extauth.auth.management.create_roles")

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 extauth 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 = "extauth.management.create_model_permissions")