Commits

Michael Hall committed ec89597

Renamed to extauth

Comments (0)

Files changed (34)

Empty file added.

Add a comment to this file

extauth/auth/__init__.py

Empty file added.

extauth/auth/admin.py

+from extauth.auth.models import Role
+from django.contrib import admin
+
+class RoleAdmin(admin.ModelAdmin):
+    search_fields = ('model','role')
+    ordering = ('model','role')
+    filter_horizontal = ('permissions',)
+
+admin.site.register(Role, RoleAdmin)

extauth/auth/backend.py

+'''
+Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
+All rights reserved.
+
+@author: Michael Hall <mhall119@gmail.com>
+'''
+

extauth/auth/management/__init__.py

+'''
+Created on Mar 25, 2010
+
+@author: hallmj
+'''
+
+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")
+
Add a comment to this file

extauth/auth/management/commands/__init__.py

Empty file added.

extauth/auth/management/commands/updateroles.py

+'''
+Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
+All rights reserved.
+
+Created on Mar 9, 2010
+
+@author: Michael Hall <mhall119@gmail.com>
+'''
+from django.core.management.base import NoArgsCommand
+from extauth.auth.management import create_roles
+from django.db.models import get_apps
+
+class Command(NoArgsCommand):
+    
+    def handle_noargs(self, **options):
+        verbosity = int(options.pop('verbosity', 1))
+        
+        for app in get_apps():
+            if verbosity >= 1:
+                print "Creating Roles for %s" % app.__name__
+            create_roles(app, [], verbosity, **options)
+
+            

extauth/auth/models.py

+'''
+Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
+All rights reserved.
+
+@author: Michael Hall <mhall119@gmail.com>
+'''
+from django.contrib import auth
+from django.db import models
+from django.contrib.contenttypes.models import ContentType
+
+class Role(models.Model):
+    
+    class Meta:
+        verbose_name = "Role"
+        unique_together = (('model', 'role'),)
+        
+    model = models.ForeignKey(ContentType, verbose_name='Model Type')
+    role = models.CharField(max_length=255, verbose_name='Role Name')
+    permissions = models.ManyToManyField(auth.models.Permission, blank=True, verbose_name='Role Permissions')
+    
+    def __unicode__(self):
+        return "%s.%s: %s" % (self.model.app_label, self.model, self.role)
+

extauth/auth/roles.py

+'''
+Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
+All rights reserved.
+
+@author: Michael Hall <mhall119@gmail.com>
+'''
+
+from extauth import utils, session
+from extauth.auth.models import Role
+from extauth.fieldperms import permissions
+
+from django.contrib.auth.models import User, Group
+from django.contrib.contenttypes.models import ContentType
+from django.utils.functional import curry
+import copy
+
+registered_roles = {}
+def register(model_class, role_class=None):
+    if registered_roles.has_key(model_class):
+        raise RoleException("Model %s has already been registered with a RoleManager" % model_class)
+    else:
+        registered_roles[model_class] = role_class or EmptyRoles
+        
+def get_rolemanager(model_class):
+    if not registered_roles.has_key(model_class):
+        return EmptyRoles
+        #raise RoleException(None, model_class, "Model %s has not been registered with a RoleManager" % model_class)
+    else:
+        return registered_roles[model_class]
+
+def get_roles(model_inst, user=None):
+    if user is None:
+        user = session.get_current_user()
+    role_class = get_rolemanager(model_inst.__class__)
+    role_inst = role_class(model_inst, user)
+    return role_inst
+
+class RoleException(Exception):
+    def __init__(self, user, model, msg):
+        super(RoleException, self).__init__(msg)
+        self.user = user
+        self.model = model
+        
+class RoleManagerBase(type):
+    """
+    Metaclass for all Role Managers.
+    """
+    def __new__(cls, name, bases, attrs):
+        super_new = super(RoleManagerBase, cls).__new__
+        parents = [b for b in bases if isinstance(b, RoleManagerBase)]
+        if not parents:
+            # If this isn't a subclass of RoleManager, don't do anything special.
+            return super_new(cls, name, bases, attrs)
+
+        # Create the class.
+        module = attrs.pop('__module__')
+        new_class = super_new(cls, name, bases, {'__module__': module})
+        
+        roles = dict()
+        for aName, a in attrs.items():
+            if isinstance(a, RoleBase):
+                roles[aName] = a
+            else:
+                setattr(new_class, aName, a)
+        setattr(new_class, '_roles', roles)
+        return new_class
+    
+class RoleManager(object):
+    'Role Managers define the available roles for a given model'
+    
+    __metaclass__ = RoleManagerBase
+    
+    def __init__(self, model, user=None):
+        self.model = model
+        if user is None:
+            self.user = session.get_current_user()
+        else:
+            self.user = user
+        
+        roles = {}
+        _roles = self._roles
+        for (rName, r) in self._roles.items():
+            role = copy.deepcopy(r)
+            role.user = self.user
+            role.model = self.model
+            roles[rName] = role
+        setattr(self, 'roles', roles)
+            
+    def __getattr__(self, aName):
+        if aName in self.roles:
+            return self.roles[aName].hasRole()
+        raise AttributeError
+    
+    def getUserRoles(self):
+        uRoles = []
+        for rName, role in self.roles.items():
+            if role.hasRole():
+                uRoles.append(rName)
+        return uRoles
+    
+    def has_perm(self, pName):
+        model_type = ContentType.objects.get_for_model(self.model.__class__)
+        (app, sep, perm) = pName.partition('.')
+        if not perm or perm == '':
+            perm = app
+            app = self.model._meta.app_label
+            
+        perms = Role.objects.filter(model=model_type, 
+                                        role__in=self.getUserRoles(),
+                                        permissions__content_type__app_label=app,
+                                        permissions__codename=perm)
+        if perms.count() > 0:
+            return True
+        else:
+            return permissions.has_perm(pName, self.user)
+                
+    def has_any_perm(self, *perms):
+        for p in perms:
+            if self.has_perm(p):
+                return True
+        return False
+    
+    def has_all_perms(self, *perms):
+        for p in perms:
+            if not self.has_perm(p):
+                return False
+        return True
+
+    def require_perm(self, perm):
+        if self.has_perm(perm):
+            return True
+        else:
+            raise PermissionDenied("User does not have required permissions: %s" % perm, params={'user': self.user, 'perm': perm})
+    
+class RoleBase(object):
+    'Base class for all Roles'
+    
+    def __init__(self):
+        self._user = None
+        self._model = None
+        pass
+    
+    def setUser(self, user):
+        if isinstance(user, User):
+            self._user = user
+        else:
+            raise TypeError("Argument must be django.contrib.auth.models.User, not %s" % type(user))
+        
+    def getUser(self):
+        return self._user
+    user = property(getUser, setUser)
+    
+    def setModel(self, model):
+        self._model = model
+        
+    def getModel(self):
+        return self._model
+    model = property(getModel, setModel)
+    
+    def hasRole(self):
+        return False
+    
+    def __call__(self):
+        return self.hasRole()    
+    
+class UserIsAuthenticated(RoleBase):
+    'Any Authenticated user will have this role'
+    def __init__(self):
+        super(UserIsAuthenticated, self).__init__()
+    
+    def hasRole(self):
+        if self.user is None:
+            return False
+        
+        return self.user.is_authenticated()
+    
+class IsSelf(RoleBase):
+    """
+    Users will have this role on their own django.contrib.auth.models.User 
+    object (or any child-class of it)
+    """
+    def __init__(self):
+        super(IsSelf, self).__init__()
+    
+    def hasRole(self):
+        if isinstance(self.model, type(self.user)) and self.user.id == self.model.id:
+            return True
+        return False
+    
+class UserIs(RoleBase):
+    """
+    Users will have this role of the given model field is either a ForeignKey
+    to their django.contrib.auth.models.User object (or any child-class of it)
+    or a field who's string value matches their username
+    """    
+    def __init__(self, model_field):
+        super(UserIs, self).__init__()
+        self._model_field = model_field
+        
+    def setModelField(self, model_field):
+        self._model_field = model_field
+    
+    def getModelField(self):
+        return self._model_field
+    model_field = property(getModelField, setModelField)
+    
+    def hasRole(self):
+        if self.model is None or self.user is None:
+            return False
+        
+        v = utils.get_model_value(self.model, self.model_field)
+        if v is None:
+            return False
+        
+        if isinstance(v, User):
+            return v.username == self.user.username
+        else:
+            return v == self.user.username
+    
+class UserIn(RoleBase):
+    """
+    Users will have this role of the given model field is either a ForeignKey
+    to a django.contrib.auth.models.Group object (or any child-class of it)
+    of which they are a member, or the field's string value is that of a group
+    of which they are a member.
+    """    
+    
+    def __init__(self, model_field):
+        super(UserIn, self).__init__()
+        self._model_field = model_field        
+        
+    def setModelField(self, model_field):
+        self._model_field = model_field
+    
+    def getModelField(self):
+        return self._model_field
+    model_field = property(getModelField, setModelField)
+    
+    def hasRole(self):
+        if self.model is None or self.user is None:
+            return False
+        
+        v = utils.get_model_value(self.model, self.model_field)
+        if v is None:
+            return False
+        
+        if isinstance(v, Group):
+            return v in self.user.groups.all()
+        else:
+            return self.user.groups.filter(name=v).count() > 0
+    
+class Not(RoleBase):
+    """
+    Wraps another Role instance, and returns the inverse.  If the user has the
+    given role, this will say that they don't.  If the user doesn't have the
+    role, this will say that they do
+    """
+    def __init__(self, role):
+        self.role = role
+        
+    def setUser(self, user):
+        super(Not, self).setUser(user)
+        self.role.setUser(user)
+        
+    def setModel(self, model):
+        super(Not, self).setModel(model)
+        self.role.setModel(model)
+    
+    def hasRole(self):
+        return not self.role.hasRole()
+        
+class Any(RoleBase):
+    """
+    Wraps multiple Role instances.  A user will have this role if they have any
+    one of the contained roles.
+    """
+    def __init__(self, *roles):
+        self.roles = []
+        for r in roles:
+            if isinstance(r, RoleBase):
+                self.roles.append(r)
+                
+    def setUser(self, user):
+        super(Not, self).setUser(user)
+        for r in self.roles:
+            r.setUser(user)
+        
+    def setModel(self, model):
+        super(Not, self).setModel(model)
+        for r in self.roles:
+            r.setModel(model)
+    
+    def hasRole(self):
+        for r in self.roles:
+            if r.hasRole():
+                return True
+        return False
+        
+class All(Any):
+    """
+    Wraps multiple Role instances.  A user will have this role if they have all
+    of the contained roles.
+    """
+
+    def hasRole(self):
+        for r in self.roles:
+            if not r.hasRole():
+                return False
+        return True
+        
+class EmptyRoles(RoleManager):
+    """
+    Provides no Roles, this is used when requesting Roles from an object type
+    that does not have a RoleManager defined
+    """
+    pass
+    
+def autodiscover():
+    """
+    Auto-discover INSTALLED_APPS admin.py modules and fail silently when 
+    not present. This forces an import on them to register any role bits they
+    may want.
+    """
+    import imp
+    from django.conf import settings
+
+    for app in settings.INSTALLED_APPS:
+        # For each app, we need to look for an admin.py inside that app's
+        # package. We can't use os.path here -- recall that modules may be
+        # imported different ways (think zip files) -- so we need to get
+        # the app's __path__ and look for admin.py on that path.
+
+        # Step 1: find out the app's __path__ Import errors here will (and
+        # should) bubble up, but a missing __path__ (which is legal, but weird)
+        # fails silently -- apps that do weird things with __path__ might
+        # need to roll their own admin registration.
+        try:
+            app_path = __import__(app, {}, {}, [app.split('.')[-1]]).__path__
+        except AttributeError:
+            continue
+
+        # Step 2: use imp.find_module to find the app's admin.py. For some
+        # reason imp.find_module raises ImportError if the app can't be found
+        # but doesn't actually try to import the module. So skip this app if
+        # its admin.py doesn't exist
+        try:
+            imp.find_module('roles', app_path)
+        except ImportError:
+            continue
+
+        # Step 3: import the app's admin file. If this has errors we want them
+        # to bubble up.
+        __import__("%s.roles" % app)
Add a comment to this file

extauth/fieldperms/__init__.py

Empty file added.

extauth/fieldperms/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_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")
+
Add a comment to this file

extauth/fieldperms/management/commands/__init__.py

Empty file added.

extauth/fieldperms/management/commands/updateperms.py

+'''
+Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
+All rights reserved.
+
+@author: Michael Hall <mhall119@gmail.com>
+'''
+from django.core.management.base import NoArgsCommand, CommandError
+from o9.management import create_model_permissions, create_page_permissions
+from django.contrib.auth.management import create_permissions
+from django.db.models import get_app, get_apps
+from django.conf import settings
+from django.db import transaction
+
+class Command(NoArgsCommand):
+    
+    def handle_noargs(self, **options):
+        verbosity = int(options.pop('verbosity', 1))
+        
+        for app in get_apps():
+            if verbosity >= 1:
+                print "Updating Permissions for %s" % app.__name__
+                            
+            if verbosity >= 1:
+                print "Creating standard permissions"
+            create_permissions(app, [], verbosity, **options)
+            
+            if verbosity >= 1:
+                print "Creating O9 model permissions"
+            create_model_permissions(app, [], verbosity, **options)
+            
+            if verbosity >= 1:
+                print "Creating O9 page permissions"
+            create_page_permissions(app, [], verbosity, **options)
+
+            

extauth/fieldperms/permissions.py

+'''
+Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
+All rights reserved.
+
+@author: Michael Hall <mhall119@gmail.com>
+'''
+from extauth import session
+
+ALL_USERS = '*'
+
+def has_perm(perm, user=None):
+    if perm == ALL_USERS:
+        return True
+    
+    if user is None:
+        user = session.get_current_user()
+
+    if user is None:
+        return False
+    else:
+        return user.has_perm(perm)
+
+def require_perm(perm, user=None):
+    if user is None:
+        user = session.get_current_user()
+
+    if has_perm(perm, user):
+        return True
+    else:
+        if user is None or not user.is_authenticated():
+            raise LoginRequiredException(user, perm, None)
+        else:
+            raise InsufficientPermsException(user, perm, None)
+        
+def get_add_permission(model_class):
+    return '%s.add_%s' % (model_class._meta.app_label, model_class._meta.object_name.lower())
+
+def get_read_permission(model_class):
+    return '%s.read_%s' % (model_class._meta.app_label, model_class._meta.object_name.lower())
+
+def get_change_permission(model_class):
+    return '%s.change_%s' % (model_class._meta.app_label, model_class._meta.object_name.lower())
+
+def get_delete_permission(model_class):
+    return '%s.delete_%s' % (model_class._meta.app_label, model_class._meta.object_name.lower())
+
+def get_modify_permission(model_class, field_name):
+    return '%s.modify_%s__%s' % (model_class._meta.app_label, model_class._meta.object_name.lower(), field_name)
+
+def get_view_permission(model_class, field_name):
+    return '%s.view_%s__%s' % (model_class._meta.app_label, model_class._meta.object_name.lower(), field_name)
+
+class PermissionException(Exception):
+    def __init__(self, user, node, perm, msg):
+        self.user = user
+        self.node = node
+        self.msg = msg
+        
+    def __str__(self):
+        return repr(self.msg)
+
+class InsufficientPermsException(PermissionException):
+    
+    def __init__(self, user, perm, node):
+        self.user = user
+        self.perm = perm
+        self.node = node
+        self.msg = "User %s does not have permission to access this page: %s" % (user, perm)
+
+class LoginRequiredException(PermissionException):
+    def __init__(self, user, perm, node):
+        self.user = user
+        self.perm = perm
+        self.node = node
+        self.msg = "User must be logged in to access this page"
+

extauth/fieldperms/utils.py

+import django
+from django import forms
+from django.forms.fields import EMPTY_VALUES
+
+def map_search_fields_to_query(model_class, search_fields):
+    query_fields = {}
+    for f in search_fields:
+        fname, query_key = expand_search_field(model_class, f)
+        query_fields[fname] = query_key
+    return query_fields
+
+def expand_search_field(model_class, f):
+    if f[0:1] in ['*', '>', '<', '?']:
+        fname = f[1:]
+        fopt = f[0:1]
+    else:
+        fname = f
+        fopt = None
+        
+    mf = model_class._meta.get_field_by_name(fname.split('__')[0])
+    if mf is not None and isinstance(mf, django.db.models.ForeignKey):
+        fname.append('_id')
+        
+    if fopt == '*':
+        query_key = "%s__icontains" % fname
+    elif fopt == '>':
+        query_key = "%s__gte" % fname
+    elif fopt == '<':
+        query_key = "%s__lte" % fname
+    elif fopt == '?':
+        query_key = "%s__isnull" % fname
+    else:
+        query_key = fname
+        
+    return (fname, query_key)
+
+def map_search_fields_to_form(search_fields):
+    form_fields = {}
+    for f in search_fields:
+        if f[0:1] in ['*', '>', '<', '?']:
+            form_fields[f] = f[1:]
+        else:
+            form_fields[f] = f
+    return form_fields
+
+def get_model_search_fields(model_class, search_fields):
+    
+    if search_fields is not None:
+        return search_fields
+    elif hasattr(model_class, 'o9_search_fields'):
+        return model_class.o9_search_fields
+    else:
+        return [[f.name for f in model_class._meta.fields if f.name != "id" and not f.name.endswith("_ptr")][0]]
+
+YES=1
+NO=0
+ANY=''
+
+def model_has_field(model, field_name):
+    if isinstance(model, django.db.models.base.ModelBase):
+        model = model()
+    fields = field_name.split('__')
+    while len(fields) > 0:
+        name = fields[0]
+        fields = fields[1:]
+        try:
+            mf = model._meta.get_field(name)
+            if mf is not None and isinstance(mf, django.db.models.ForeignKey):
+                model = mf.rel.to()
+        except:
+            return False
+    return True
+
+def get_model_value(model, field_name):
+    #print "get_model_value(model=%s, field_name=%s)" % (model.__class__.__name__, field_name)
+    value = None
+    fields = field_name.split('__')
+    while len(fields) > 0:
+        name = fields[0]
+        fields = fields[1:]
+        if hasattr(model, name):
+            value = getattr(model, name)
+            if isinstance(value, django.db.models.Model):
+                model = value
+    return value
+
+def get_model_value_display(model, field_name):
+    #print "get_model_value(model=%s, field_name=%s)" % (model.__class__.__name__, field_name)
+    value = None
+    fields = field_name.split('__')
+    while len(fields) > 0:
+        name = fields[0]
+        fields = fields[1:]
+        if hasattr(model, name):
+            value = getattr(model, name)
+            if isinstance(value, django.db.models.Model):
+                model = value
+            elif hasattr(model, 'get_%s_display'%name):
+                 value = getattr(model, 'get_%s_display'%name)()
+                
+    return value
+
+def get_model_field(model, field_name):
+    #print "get_model_field(model=%s, field_name=%s)" % (model.__class__.__name__, field_name)
+    if isinstance(model, django.db.models.base.ModelBase):
+        model = model()
+    fields = field_name.split('__')
+    while len(fields) > 0:
+        name = fields[0]
+        fields = fields[1:]
+        try:
+            mf = model._meta.get_field(name)
+            if mf is not None and isinstance(mf, django.db.models.ForeignKey):
+                model = mf.rel.to()
+        except:
+            #print "ERROR: model: %s has not field %s" % (model.__class__.__name__, name)
+            pass
+    return mf
+    
+def get_model_search_form_fields(model_class, search_fields):
+    from o9.forms import SearchField
+    fields = django.utils.datastructures.SortedDict()
+    model = model_class()
+    for f in search_fields:
+        
+        # If this is an instance of SearchField, use it's properties
+        if isinstance(f, SearchField):
+            field_name = f.field_name
+            field_id = f.field_id
+            if f.form_field is not None:
+                field = f.form_field
+            else:
+                field = get_model_field(model, field_name).formfield()
+                if f.form_widget is not None:
+                    field.widget = f.form_widget
+                if f.default is not None:
+                    field.initial = f.default
+                if f.label is not None:
+                    field.label = f.label
+            field.html_name = field_id
+        elif isinstance(f, (list, tuple)): 
+            if len(f) == 4:
+                field_name, default, query_key, field_id = f
+            elif len(f) == 3:
+                field_name, default, query_key = f
+                field_id = field_name
+            else:
+                field_name, default = f
+                field_name, query_key = expand_search_field(model_class, field_name)
+                field_id = field_name
+            
+            if f[0].startswith('?'):
+                field = forms.fields.ChoiceField(choices=((ANY, '---------'), (YES, u'Yes'), (NO, u'No')), label=get_model_field(model, field_name).verbose_name)
+                default = boolean_to_choice(default)
+                #field = forms.fields.BooleanField(label=model._meta.get_field_by_name(field_name)[0].verbose_name)
+            else:
+                field = get_model_field(model, field_name).formfield()
+                if field is None:
+                    raise Exception("%s.%s has no formfield"%(model.__class__, field_name))
+                field.empty = False
+            field.initial = default
+            field_id = field_name
+            
+        elif isinstance(f, (str, unicode)):
+            field_name, query_key = expand_search_field(model_class, f)
+            if f.startswith('?'):
+                field = forms.fields.ChoiceField(choices=((ANY, '---------'), (YES, u'Yes'), (NO, u'No')), label=get_model_field(model, field_name).verbose_name)
+                default = boolean_to_choice(default)
+                #field = forms.fields.BooleanField(label=model._meta.get_field_by_name(field_name)[0].verbose_name)
+            else:
+                field = get_model_field(model, field_name).formfield()
+                if field is None:
+                    raise Exception("%s.%s has no formfield"%(model.__class__, field_name))
+                if get_model_field(model, field_name).default != django.db.models.fields.NOT_PROVIDED:
+                    default = get_model_field(model, field_name).default
+                else:
+                    default = None
+                field.empty = False
+            field.initial = default
+            field_id = field_name
+    
+        field.widget.attrs['class'] = field.__class__.__name__
+        field.required = False
+        
+        field.help_text = None
+        fields[field_id] = field
+    return fields
+
+def boolean_to_choice(b):
+    if b not in EMPTY_VALUES:
+        if b:
+            return YES
+        else:
+            return NO
+
+def get_model_search_query(model_class, search_fields, form, request):
+    from o9.forms import SearchField
+
+    if form.is_valid():
+        search = {}
+        for f in search_fields:
+            
+            if isinstance(f, SearchField):
+                field_name = f.field_name
+                field_id = f.field_id
+                query_key = f.query_key
+            
+            elif isinstance(f, (list, tuple)):
+                if len(f) == 4:
+                    field_name, default, query_key, field_id = f
+                elif len(f) == 3:
+                    field_name, default, query_key = f
+                    field_id = field_name
+                else:
+                    field_name, default = f
+                    field_name, query_key = expand_search_field(model_class, field_name)
+                    field_id = field_name
+            elif isinstance(f, (str, unicode)):
+                field_name, query_key = expand_search_field(model_class, f)
+                field_id = field_name
+                
+            if form.cleaned_data[field_id] not in EMPTY_VALUES:
+                if query_key.endswith('__isnull'):
+                    if int(form.cleaned_data[field_id]) in (YES, NO):
+                        search[query_key] = int(form.cleaned_data[field_id]) == NO
+                else:
+                    search[query_key] = form.cleaned_data[field_id]
+                
+        if len(search) > 0:
+            return model_class.objects.filter(**search)
+        else:
+            return model_class.objects.all()
+    else:
+        return model_class.objects.none()
+    
+def get_model_search_values(model_class, search_fields, request):
+    from o9.forms import SearchField
+    search = {}
+    for f in search_fields:
+        if isinstance(f, SearchField):
+            field_name = f.field_name
+            field_id = f.field_id
+            default = f.default or ''
+            query_key = f.query_key
+
+        elif isinstance(f, (list, tuple)):
+            if len(f) == 4:
+                field_name, default, query_key, field_id = f
+            elif len(f) == 3:
+                field_name, default, query_key = f
+                field_id = field_name
+            else:
+                field_name, default = f
+                field_name, query_key = expand_search_field(model_class, field_name)
+                field_id = field_name
+
+        elif isinstance(f, (str, unicode)):
+            field_name, query_key = expand_search_field(model_class, f)
+            field_id = field_name
+            default = ''
+        else:
+            raise Exception("Unknown field type: %s (%s)" % (type(f), repr(f)))
+
+        if query_key is not None and query_key.endswith('__isnull'):
+            default = boolean_to_choice(default)
+            
+        if request.has_key(field_id):
+            search[field_id] = request.get(field_id, '')
+        else:
+            search[field_id] = default
+    return search
+    
+def get_model_search_params(model_class, search_fields, form, request):
+    from o9.forms import SearchField
+    search = {}
+    if form.is_valid():
+        for f in search_fields:
+            if isinstance(f, SearchField):
+                field_name = f.field_name
+                field_id = f.field_id
+                default = f.default or ''
+                query_key = f.query_key
+
+            elif isinstance(f, (list, tuple)):
+                field_name, default = f
+                if len(f) == 4:
+                    field_name, default, query_key, field_id = f
+                elif len(f) == 3:
+                    field_name, default, query_key = f
+                    field_id = field_name
+                else:
+                    field_name, default = f
+                    field_name, query_key = expand_search_field(model_class, field_name)
+                    field_id = field_name
+
+            elif isinstance(f, (str, unicode)):
+                field_name, query_key = expand_search_field(model_class, f)
+                if get_model_field(model_class, field_name).default != django.db.models.fields.NOT_PROVIDED:
+                    default = get_model_field(model_class, field_name).default
+                else:
+                    default = ''
+                field_id = field_name
+            
+            if query_key is not None and query_key.endswith('__isnull'):
+                default = boolean_to_choice(default)
+            
+            if request.has_key(field_id):
+                search[field_id] = request.get(field_id, '')
+            else:
+                search[field_id] = default
+    return search
+    
+
+def get_model_result_fields(model_class, result_fields):
+    
+    if result_fields is not None:
+        return result_fields
+    elif hasattr(model_class, 'o9_result_fields'):
+        return model_class.o9_result_fields
+    else:
+        return [f.name for f in model_class._meta.fields if f.name != "id" and not f.name.endswith("_ptr")]
+
+def get_model_export_fields(model_class, export_fields):
+    
+    if export_fields is not None:
+        return export_fields
+    elif hasattr(model_class, 'o9_export_fields'):
+        return model_class.o9_export_fields
+    else:
+        return [f.name for f in model_class._meta.fields if not f.name.endswith("_ptr") ]
+
+def get_model_display_fields(model_class, display_fields=None):
+    
+    if display_fields is not None:
+        return display_fields
+    elif hasattr(model_class, 'o9_display_fields') and model_class.o9_display_fields is not None:
+        return model_class.o9_display_fields
+    else:
+        return [f.name for f in model_class._meta.fields + model_class._meta.many_to_many if f.name != "id" and not f.name.endswith("_ptr")]
+
+def corefilter_to_data(model):
+    filters = model.core_filters
+    data = {}
+    #print "Getting data from %s core_filters" % model
+    
+    for (filter, value) in filters.items():
+        #print "%s Filter: %s: %s" % (model, filter, value)
+        fields = filter.split('__')
+        field_name = fields[0]
+        #print "Field_name: %s" % field_name
+        while len(fields) > 0:
+            name = fields[0]
+            fields = fields[1:]
+            #print "Name: %s" % name
+            try:
+                if model.__class__.__name__ == 'ManyRelatedManager' or model.__class__.__name__ == 'RelatedManager':
+                    mf = model.model._meta.get_field(name)
+                else:
+                    mf = model._meta.get_field(name)
+                    
+                if mf is not None and isinstance(mf, django.db.models.ForeignKey):
+                    #print "%s is a ForeignKey, traversing..." % name
+                    model = mf.rel.to()
+            except:
+                #print "ERROR: model: %s has not field %s" % (model.__class__.__name__, name)
+                pass
+        
+        #print "Model is %s" % model.__class__.__name__
+        if model.__class__.__name__ == 'ManyRelatedManager' or model.__class__.__name__ == 'RelatedManager':
+            #print "Model is a RelatedManager"
+            for f in model.model._meta.fields:
+                #print "Checking field %s" % f.name
+                if f.column == name:
+                    #print "Matched column %s" % f.column
+                    data[field_name] = value
+        elif isinstance(model, django.db.models.Model):
+            #print "Model is a Model"
+            for f in model._meta.fields:
+                #print "Checking field %s" % f.name
+                if f.column == name:
+                    #print "Matched column %s" % f.column
+                    data[field_name] = value
+        else:
+            data[field_name] = value
+    return data
+    

extauth/session.py

+'''
+Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
+All rights reserved.
+
+@author: Michael Hall <mhall119@gmail.com>
+'''
+from django.utils._threading_local import local
+
+_thread_locals = local()
+
+def get_current_user():
+    "Return the owner of the current thread"
+    if _thread_locals is None:
+        raise Exception("Session requires thread local variables")
+
+    from django.contrib.auth.models import AnonymousUser
+    user = getattr(_thread_locals, 'user', None)
+    if user is None:
+        raise Exception("Cannot use None as Session user")
+    return user
+
+def get_current_user_id():
+    user = get_current_user()
+    if (user != None):
+        return getattr(user, 'id', 0)
+    else:
+        return 0
+    
+def set_current_user(user):
+    "Set the owner of the current thread"
+    if _thread_locals is None:
+        raise Exception("Session requires thread local variables")
+    
+    if user is None:
+        raise Exception("Cannot set None as Session user")
+    _thread_locals.user = user
+
+class CaptureRequestUser(object):
+    "Middleware that captures the current HTTP request user for o9 permissions"
+    
+    def process_request(self, request):
+        #if hasattr(request, 'user'):
+        #    set_current_user(getattr(request, 'user'))
+        #else:
+        from django.contrib.auth import get_user
+        set_current_user(get_user(request))
+
+
+'''
+Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
+All rights reserved.
+
+@author: Michael Hall <mhall119@gmail.com>
+'''
+import django
+from django import forms
+from django.forms.fields import EMPTY_VALUES
+
+def map_search_fields_to_query(model_class, search_fields):
+    query_fields = {}
+    for f in search_fields:
+        fname, query_key = expand_search_field(model_class, f)
+        query_fields[fname] = query_key
+    return query_fields
+
+def expand_search_field(model_class, f):
+    if f[0:1] in ['*', '>', '<', '?']:
+        fname = f[1:]
+        fopt = f[0:1]
+    else:
+        fname = f
+        fopt = None
+        
+    mf = model_class._meta.get_field_by_name(fname.split('__')[0])
+    if mf is not None and isinstance(mf, django.db.models.ForeignKey):
+        fname.append('_id')
+        
+    if fopt == '*':
+        query_key = "%s__icontains" % fname
+    elif fopt == '>':
+        query_key = "%s__gte" % fname
+    elif fopt == '<':
+        query_key = "%s__lte" % fname
+    elif fopt == '?':
+        query_key = "%s__isnull" % fname
+    else:
+        query_key = fname
+        
+    return (fname, query_key)
+
+def map_search_fields_to_form(search_fields):
+    form_fields = {}
+    for f in search_fields:
+        if f[0:1] in ['*', '>', '<', '?']:
+            form_fields[f] = f[1:]
+        else:
+            form_fields[f] = f
+    return form_fields
+
+YES=1
+NO=0
+ANY=''
+
+def model_has_field(model, field_name):
+    if isinstance(model, django.db.models.base.ModelBase):
+        model = model()
+    fields = field_name.split('__')
+    while len(fields) > 0:
+        name = fields[0]
+        fields = fields[1:]
+        try:
+            mf = model._meta.get_field(name)
+            if mf is not None and isinstance(mf, django.db.models.ForeignKey):
+                model = mf.rel.to()
+        except:
+            return False
+    return True
+
+def get_model_value(model, field_name):
+    #print "get_model_value(model=%s, field_name=%s)" % (model.__class__.__name__, field_name)
+    value = None
+    fields = field_name.split('__')
+    while len(fields) > 0:
+        name = fields[0]
+        fields = fields[1:]
+        if hasattr(model, name):
+            value = getattr(model, name)
+            if isinstance(value, django.db.models.Model):
+                model = value
+    return value
+
+def get_model_value_display(model, field_name):
+    #print "get_model_value(model=%s, field_name=%s)" % (model.__class__.__name__, field_name)
+    value = None
+    fields = field_name.split('__')
+    while len(fields) > 0:
+        name = fields[0]
+        fields = fields[1:]
+        if hasattr(model, name):
+            value = getattr(model, name)
+            if isinstance(value, django.db.models.Model):
+                model = value
+            elif hasattr(model, 'get_%s_display'%name):
+                 value = getattr(model, 'get_%s_display'%name)()
+                
+    return value
+
+def get_model_field(model, field_name):
+    #print "get_model_field(model=%s, field_name=%s)" % (model.__class__.__name__, field_name)
+    if isinstance(model, django.db.models.base.ModelBase):
+        model = model()
+    fields = field_name.split('__')
+    while len(fields) > 0:
+        name = fields[0]
+        fields = fields[1:]
+        try:
+            mf = model._meta.get_field(name)
+            if mf is not None and isinstance(mf, django.db.models.ForeignKey):
+                model = mf.rel.to()
+        except:
+            #print "ERROR: model: %s has not field %s" % (model.__class__.__name__, name)
+            pass
+    return mf
+    
+def corefilter_to_data(model):
+    filters = model.core_filters
+    data = {}
+    #print "Getting data from %s core_filters" % model
+    
+    for (filter, value) in filters.items():
+        #print "%s Filter: %s: %s" % (model, filter, value)
+        fields = filter.split('__')
+        field_name = fields[0]
+        #print "Field_name: %s" % field_name
+        while len(fields) > 0:
+            name = fields[0]
+            fields = fields[1:]
+            #print "Name: %s" % name
+            try:
+                if model.__class__.__name__ == 'ManyRelatedManager' or model.__class__.__name__ == 'RelatedManager':
+                    mf = model.model._meta.get_field(name)
+                else:
+                    mf = model._meta.get_field(name)
+                    
+                if mf is not None and isinstance(mf, django.db.models.ForeignKey):
+                    #print "%s is a ForeignKey, traversing..." % name
+                    model = mf.rel.to()
+            except:
+                #print "ERROR: model: %s has not field %s" % (model.__class__.__name__, name)
+                pass
+        
+        #print "Model is %s" % model.__class__.__name__
+        if model.__class__.__name__ == 'ManyRelatedManager' or model.__class__.__name__ == 'RelatedManager':
+            #print "Model is a RelatedManager"
+            for f in model.model._meta.fields:
+                #print "Checking field %s" % f.name
+                if f.column == name:
+                    #print "Matched column %s" % f.column
+                    data[field_name] = value
+        elif isinstance(model, django.db.models.Model):
+            #print "Model is a Model"
+            for f in model._meta.fields:
+                #print "Checking field %s" % f.name
+                if f.column == name:
+                    #print "Matched column %s" % f.column
+                    data[field_name] = value
+        else:
+            data[field_name] = value
+    return data
+    
Add a comment to this file

extperms/__init__.py

Empty file removed.

Add a comment to this file

extperms/auth/__init__.py

Empty file removed.

extperms/auth/admin.py

-from extperms.auth.models import Role
-from django.contrib import admin
-
-class RoleAdmin(admin.ModelAdmin):
-    search_fields = ('model','role')
-    ordering = ('model','role')
-    filter_horizontal = ('permissions',)
-
-admin.site.register(Role, RoleAdmin)

extperms/auth/backend.py

-'''
-Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
-All rights reserved.
-
-@author: Michael Hall <mhall119@gmail.com>
-'''
-

extperms/auth/management/__init__.py

-'''
-Created on Mar 25, 2010
-
-@author: hallmj
-'''
-
-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 extperms.auth.models import Role
-    from extperms.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 = "extperms.auth.management.create_roles")
-
Add a comment to this file

extperms/auth/management/commands/__init__.py

Empty file removed.

extperms/auth/management/commands/updateroles.py

-'''
-Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
-All rights reserved.
-
-Created on Mar 9, 2010
-
-@author: Michael Hall <mhall119@gmail.com>
-'''
-from django.core.management.base import NoArgsCommand
-from extperms.auth.management import create_roles
-from django.db.models import get_apps
-
-class Command(NoArgsCommand):
-    
-    def handle_noargs(self, **options):
-        verbosity = int(options.pop('verbosity', 1))
-        
-        for app in get_apps():
-            if verbosity >= 1:
-                print "Creating Roles for %s" % app.__name__
-            create_roles(app, [], verbosity, **options)
-
-            

extperms/auth/models.py

-'''
-Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
-All rights reserved.
-
-@author: Michael Hall <mhall119@gmail.com>
-'''
-from django.contrib import auth
-from django.db import models
-from django.contrib.contenttypes.models import ContentType
-
-class Role(models.Model):
-    
-    class Meta:
-        verbose_name = "Role"
-        unique_together = (('model', 'role'),)
-        
-    model = models.ForeignKey(ContentType, verbose_name='Model Type')
-    role = models.CharField(max_length=255, verbose_name='Role Name')
-    permissions = models.ManyToManyField(auth.models.Permission, blank=True, verbose_name='Role Permissions')
-    
-    def __unicode__(self):
-        return "%s.%s: %s" % (self.model.app_label, self.model, self.role)
-

extperms/auth/roles.py

-'''
-Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
-All rights reserved.
-
-@author: Michael Hall <mhall119@gmail.com>
-'''
-
-from extperms import utils, session
-from extperms.auth.models import Role
-from extperms.fieldperms import permissions
-
-from django.contrib.auth.models import User, Group
-from django.contrib.contenttypes.models import ContentType
-from django.utils.functional import curry
-import copy
-
-registered_roles = {}
-def register(model_class, role_class=None):
-    if registered_roles.has_key(model_class):
-        raise RoleException("Model %s has already been registered with a RoleManager" % model_class)
-    else:
-        registered_roles[model_class] = role_class or EmptyRoles
-        
-def get_rolemanager(model_class):
-    if not registered_roles.has_key(model_class):
-        return EmptyRoles
-        #raise RoleException(None, model_class, "Model %s has not been registered with a RoleManager" % model_class)
-    else:
-        return registered_roles[model_class]
-
-def get_roles(model_inst, user=None):
-    if user is None:
-        user = session.get_current_user()
-    role_class = get_rolemanager(model_inst.__class__)
-    role_inst = role_class(model_inst, user)
-    return role_inst
-
-class RoleException(Exception):
-    def __init__(self, user, model, msg):
-        super(RoleException, self).__init__(msg)
-        self.user = user
-        self.model = model
-        
-class RoleManagerBase(type):
-    """
-    Metaclass for all Role Managers.
-    """
-    def __new__(cls, name, bases, attrs):
-        super_new = super(RoleManagerBase, cls).__new__
-        parents = [b for b in bases if isinstance(b, RoleManagerBase)]
-        if not parents:
-            # If this isn't a subclass of RoleManager, don't do anything special.
-            return super_new(cls, name, bases, attrs)
-
-        # Create the class.
-        module = attrs.pop('__module__')
-        new_class = super_new(cls, name, bases, {'__module__': module})
-        
-        roles = dict()
-        for aName, a in attrs.items():
-            if isinstance(a, RoleBase):
-                roles[aName] = a
-            else:
-                setattr(new_class, aName, a)
-        setattr(new_class, '_roles', roles)
-        return new_class
-    
-class RoleManager(object):
-    'Role Managers define the available roles for a given model'
-    
-    __metaclass__ = RoleManagerBase
-    
-    def __init__(self, model, user=None):
-        self.model = model
-        if user is None:
-            self.user = session.get_current_user()
-        else:
-            self.user = user
-        
-        roles = {}
-        _roles = self._roles
-        for (rName, r) in self._roles.items():
-            role = copy.deepcopy(r)
-            role.user = self.user
-            role.model = self.model
-            roles[rName] = role
-        setattr(self, 'roles', roles)
-            
-    def __getattr__(self, aName):
-        if aName in self.roles:
-            return self.roles[aName].hasRole()
-        raise AttributeError
-    
-    def getUserRoles(self):
-        uRoles = []
-        for rName, role in self.roles.items():
-            if role.hasRole():
-                uRoles.append(rName)
-        return uRoles
-    
-    def has_perm(self, pName):
-        model_type = ContentType.objects.get_for_model(self.model.__class__)
-        (app, sep, perm) = pName.partition('.')
-        if not perm or perm == '':
-            perm = app
-            app = self.model._meta.app_label
-            
-        perms = Role.objects.filter(model=model_type, 
-                                        role__in=self.getUserRoles(),
-                                        permissions__content_type__app_label=app,
-                                        permissions__codename=perm)
-        if perms.count() > 0:
-            return True
-        else:
-            return permissions.has_perm(pName, self.user)
-                
-    def has_any_perm(self, *perms):
-        for p in perms:
-            if self.has_perm(p):
-                return True
-        return False
-    
-    def has_all_perms(self, *perms):
-        for p in perms:
-            if not self.has_perm(p):
-                return False
-        return True
-
-    def require_perm(self, perm):
-        if self.has_perm(perm):
-            return True
-        else:
-            raise PermissionDenied("User does not have required permissions: %s" % perm, params={'user': self.user, 'perm': perm})
-    
-class RoleBase(object):
-    'Base class for all Roles'
-    
-    def __init__(self):
-        self._user = None
-        self._model = None
-        pass
-    
-    def setUser(self, user):
-        if isinstance(user, User):
-            self._user = user
-        else:
-            raise TypeError("Argument must be django.contrib.auth.models.User, not %s" % type(user))
-        
-    def getUser(self):
-        return self._user
-    user = property(getUser, setUser)
-    
-    def setModel(self, model):
-        self._model = model
-        
-    def getModel(self):
-        return self._model
-    model = property(getModel, setModel)
-    
-    def hasRole(self):
-        return False
-    
-    def __call__(self):
-        return self.hasRole()    
-    
-class UserIsAuthenticated(RoleBase):
-    'Any Authenticated user will have this role'
-    def __init__(self):
-        super(UserIsAuthenticated, self).__init__()
-    
-    def hasRole(self):
-        if self.user is None:
-            return False
-        
-        return self.user.is_authenticated()
-    
-class IsSelf(RoleBase):
-    """
-    Users will have this role on their own django.contrib.auth.models.User 
-    object (or any child-class of it)
-    """
-    def __init__(self):
-        super(IsSelf, self).__init__()
-    
-    def hasRole(self):
-        if isinstance(self.model, type(self.user)) and self.user.id == self.model.id:
-            return True
-        return False
-    
-class UserIs(RoleBase):
-    """
-    Users will have this role of the given model field is either a ForeignKey
-    to their django.contrib.auth.models.User object (or any child-class of it)
-    or a field who's string value matches their username
-    """    
-    def __init__(self, model_field):
-        super(UserIs, self).__init__()
-        self._model_field = model_field
-        
-    def setModelField(self, model_field):
-        self._model_field = model_field
-    
-    def getModelField(self):
-        return self._model_field
-    model_field = property(getModelField, setModelField)
-    
-    def hasRole(self):
-        if self.model is None or self.user is None:
-            return False
-        
-        v = utils.get_model_value(self.model, self.model_field)
-        if v is None:
-            return False
-        
-        if isinstance(v, User):
-            return v.username == self.user.username
-        else:
-            return v == self.user.username
-    
-class UserIn(RoleBase):
-    """
-    Users will have this role of the given model field is either a ForeignKey
-    to a django.contrib.auth.models.Group object (or any child-class of it)
-    of which they are a member, or the field's string value is that of a group
-    of which they are a member.
-    """    
-    
-    def __init__(self, model_field):
-        super(UserIn, self).__init__()
-        self._model_field = model_field        
-        
-    def setModelField(self, model_field):
-        self._model_field = model_field
-    
-    def getModelField(self):
-        return self._model_field
-    model_field = property(getModelField, setModelField)
-    
-    def hasRole(self):
-        if self.model is None or self.user is None:
-            return False
-        
-        v = utils.get_model_value(self.model, self.model_field)
-        if v is None:
-            return False
-        
-        if isinstance(v, Group):
-            return v in self.user.groups.all()
-        else:
-            return self.user.groups.filter(name=v).count() > 0
-    
-class Not(RoleBase):
-    """
-    Wraps another Role instance, and returns the inverse.  If the user has the
-    given role, this will say that they don't.  If the user doesn't have the
-    role, this will say that they do
-    """
-    def __init__(self, role):
-        self.role = role
-        
-    def setUser(self, user):
-        super(Not, self).setUser(user)
-        self.role.setUser(user)
-        
-    def setModel(self, model):
-        super(Not, self).setModel(model)
-        self.role.setModel(model)
-    
-    def hasRole(self):
-        return not self.role.hasRole()
-        
-class Any(RoleBase):
-    """
-    Wraps multiple Role instances.  A user will have this role if they have any
-    one of the contained roles.
-    """
-    def __init__(self, *roles):
-        self.roles = []
-        for r in roles:
-            if isinstance(r, RoleBase):
-                self.roles.append(r)
-                
-    def setUser(self, user):
-        super(Not, self).setUser(user)
-        for r in self.roles:
-            r.setUser(user)
-        
-    def setModel(self, model):
-        super(Not, self).setModel(model)
-        for r in self.roles:
-            r.setModel(model)
-    
-    def hasRole(self):
-        for r in self.roles:
-            if r.hasRole():
-                return True
-        return False
-        
-class All(Any):
-    """
-    Wraps multiple Role instances.  A user will have this role if they have all
-    of the contained roles.
-    """
-
-    def hasRole(self):
-        for r in self.roles:
-            if not r.hasRole():
-                return False
-        return True
-        
-class EmptyRoles(RoleManager):
-    """
-    Provides no Roles, this is used when requesting Roles from an object type
-    that does not have a RoleManager defined
-    """
-    pass
-    
-def autodiscover():
-    """
-    Auto-discover INSTALLED_APPS admin.py modules and fail silently when 
-    not present. This forces an import on them to register any role bits they
-    may want.
-    """
-    import imp
-    from django.conf import settings
-
-    for app in settings.INSTALLED_APPS:
-        # For each app, we need to look for an admin.py inside that app's
-        # package. We can't use os.path here -- recall that modules may be
-        # imported different ways (think zip files) -- so we need to get
-        # the app's __path__ and look for admin.py on that path.
-
-        # Step 1: find out the app's __path__ Import errors here will (and
-        # should) bubble up, but a missing __path__ (which is legal, but weird)
-        # fails silently -- apps that do weird things with __path__ might
-        # need to roll their own admin registration.
-        try:
-            app_path = __import__(app, {}, {}, [app.split('.')[-1]]).__path__
-        except AttributeError:
-            continue
-
-        # Step 2: use imp.find_module to find the app's admin.py. For some
-        # reason imp.find_module raises ImportError if the app can't be found
-        # but doesn't actually try to import the module. So skip this app if
-        # its admin.py doesn't exist
-        try:
-            imp.find_module('roles', app_path)
-        except ImportError:
-            continue
-
-        # Step 3: import the app's admin file. If this has errors we want them
-        # to bubble up.
-        __import__("%s.roles" % app)
Add a comment to this file

extperms/fieldperms/__init__.py

Empty file removed.

extperms/fieldperms/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_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")
-
Add a comment to this file

extperms/fieldperms/management/commands/__init__.py

Empty file removed.

extperms/fieldperms/management/commands/updateperms.py

-'''
-Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
-All rights reserved.
-
-@author: Michael Hall <mhall119@gmail.com>
-'''
-from django.core.management.base import NoArgsCommand, CommandError
-from o9.management import create_model_permissions, create_page_permissions
-from django.contrib.auth.management import create_permissions
-from django.db.models import get_app, get_apps
-from django.conf import settings
-from django.db import transaction
-
-class Command(NoArgsCommand):
-    
-    def handle_noargs(self, **options):
-        verbosity = int(options.pop('verbosity', 1))
-        
-        for app in get_apps():
-            if verbosity >= 1:
-                print "Updating Permissions for %s" % app.__name__
-                            
-            if verbosity >= 1:
-                print "Creating standard permissions"
-            create_permissions(app, [], verbosity, **options)
-            
-            if verbosity >= 1:
-                print "Creating O9 model permissions"
-            create_model_permissions(app, [], verbosity, **options)
-            
-            if verbosity >= 1:
-                print "Creating O9 page permissions"
-            create_page_permissions(app, [], verbosity, **options)
-
-            

extperms/fieldperms/permissions.py

-'''
-Copyright 2009 H. Lee Moffitt Cancer Center and Research Institute, Inc. 
-All rights reserved.
-
-@author: Michael Hall <mhall119@gmail.com>
-'''
-from extperms import session
-
-ALL_USERS = '*'
-
-def has_perm(perm, user=None):
-    if perm == ALL_USERS:
-        return True
-    
-    if user is None:
-        user = session.get_current_user()
-
-    if user is None:
-        return False
-    else:
-        return user.has_perm(perm)
-
-def require_perm(perm, user=None):
-    if user is None:
-        user = session.get_current_user()
-
-    if has_perm(perm, user):
-        return True
-    else:
-        if user is None or not user.is_authenticated():
-            raise LoginRequiredException(user, perm, None)
-        else:
-            raise InsufficientPermsException(user, perm, None)
-        
-def get_add_permission(model_class):
-    return '%s.add_%s' % (model_class._meta.app_label, model_class._meta.object_name.lower())
-
-def get_read_permission(model_class):
-    return '%s.read_%s' % (model_class._meta.app_label, model_class._meta.object_name.lower())
-
-def get_change_permission(model_class):
-    return '%s.change_%s' % (model_class._meta.app_label, model_class._meta.object_name.lower())
-
-def get_delete_permission(model_class):
-    return '%s.delete_%s' % (model_class._meta.app_label, model_class._meta.object_name.lower())
-
-def get_modify_permission(model_class, field_name):
-    return '%s.modify_%s__%s' % (model_class._meta.app_label, model_class._meta.object_name.lower(), field_name)
-
-def get_view_permission(model_class, field_name):
-    return '%s.view_%s__%s' % (model_class._meta.app_label, model_class._meta.object_name.lower(), field_name)
-
-class PermissionException(Exception):
-    def __init__(self, user, node, perm, msg):
-        self.user = user
-        self.node = node
-        self.msg = msg
-        
-    def __str__(self):
-        return repr(self.msg)
-
-class InsufficientPermsException(PermissionException):
-    
-    def __init__(self, user, perm, node):
-        self.user = user
-        self.perm = perm
-        self.node = node
-        self.msg = "User %s does not have permission to access this page: %s" % (user, perm)
-
-class LoginRequiredException(PermissionException):
-    def __init__(self, user, perm, node):
-        self.user = user
-        self.perm = perm
-        self.node = node
-        self.msg = "User must be logged in to access this page"
-

extperms/fieldperms/utils.py

-import django
-from django import forms
-from django.forms.fields import EMPTY_VALUES
-
-def map_search_fields_to_query(model_class, search_fields):
-    query_fields = {}
-    for f in search_fields:
-        fname, query_key = expand_search_field(model_class, f)
-        query_fields[fname] = query_key
-    return query_fields
-
-def expand_search_field(model_class, f):
-    if f[0:1] in ['*', '>', '<', '?']:
-        fname = f[1:]
-        fopt = f[0:1]
-    else:
-        fname = f
-        fopt = None
-        
-    mf = model_class._meta.get_field_by_name(fname.split('__')[0])
-    if mf is not None and isinstance(mf, django.db.models.ForeignKey):
-        fname.append('_id')
-        
-    if fopt == '*':
-        query_key = "%s__icontains" % fname
-    elif fopt == '>':
-        query_key = "%s__gte" % fname
-    elif fopt == '<':
-        query_key = "%s__lte" % fname
-    elif fopt == '?':
-        query_key = "%s__isnull" % fname
-    else:
-        query_key = fname
-        
-    return (fname, query_key)
-
-def map_search_fields_to_form(search_fields):
-    form_fields = {}
-    for f in search_fields:
-        if f[0:1] in ['*', '>', '<', '?']:
-            form_fields[f] = f[1:]
-        else:
-            form_fields[f] = f
-    return form_fields
-
-def get_model_search_fields(model_class, search_fields):
-    
-    if search_fields is not None:
-        return search_fields
-    elif hasattr(model_class, 'o9_search_fields'):
-        return model_class.o9_search_fields
-    else:
-        return [[f.name for f in model_class._meta.fields if f.name != "id" and not f.name.endswith("_ptr")][0]]
-
-YES=1
-NO=0
-ANY=''
-
-def model_has_field(model, field_name):
-    if isinstance(model, django.db.models.base.ModelBase):
-        model = model()
-    fields = field_name.split('__')
-    while len(fields) > 0:
-        name = fields[0]
-        fields = fields[1:]
-        try:
-            mf = model._meta.get_field(name)
-            if mf is not None and isinstance(mf, django.db.models.ForeignKey):
-                model = mf.rel.to()
-        except:
-            return False
-    return True
-
-def get_model_value(model, field_name):
-    #print "get_model_value(model=%s, field_name=%s)" % (model.__class__.__name__, field_name)
-    value = None
-    fields = field_name.split('__')
-    while len(fields) > 0:
-        name = fields[0]
-        fields = fields[1:]
-        if hasattr(model, name):
-            value = getattr(model, name)
-            if isinstance(value, django.db.models.Model):
-                model = value
-    return value
-
-def get_model_value_display(model, field_name):
-    #print "get_model_value(model=%s, field_name=%s)" % (model.__class__.__name__, field_name)
-    value = None
-    fields = field_name.split('__')
-    while len(fields) > 0:
-        name = fields[0]
-        fields = fields[1:]
-        if hasattr(model, name):
-            value = getattr(model, name)
-            if isinstance(value, django.db.models.Model):
-                model = value
-            elif hasattr(model, 'get_%s_display'%name):
-                 value = getattr(model, 'get_%s_display'%name)()
-                
-    return value
-
-def get_model_field(model, field_name):
-    #print "get_model_field(model=%s, field_name=%s)" % (model.__class__.__name__, field_name)
-    if isinstance(model, django.db.models.base.ModelBase):
-        model = model()
-    fields = field_name.split('__')
-    while len(fields) > 0:
-        name = fields[0]
-        fields = fields[1:]
-        try:
-            mf = model._meta.get_field(name)
-            if mf is not None and isinstance(mf, django.db.models.ForeignKey):
-                model = mf.rel.to()
-        except:
-            #print "ERROR: model: %s has not field %s" % (model.__class__.__name__, name)
-            pass
-    return mf
-    
-def get_model_search_form_fields(model_class, search_fields):
-    from o9.forms import SearchField
-    fields = django.utils.datastructures.SortedDict()
-    model = model_class()
-    for f in search_fields:
-        
-        # If this is an instance of SearchField, use it's properties
-        if isinstance(f, SearchField):
-            field_name = f.field_name
-            field_id = f.field_id
-            if f.form_field is not None:
-                field = f.form_field
-            else:
-                field = get_model_field(model, field_name).formfield()
-                if f.form_widget is not None:
-                    field.widget = f.form_widget
-                if f.default is not None:
-                    field.initial = f.default
-                if f.label is not None:
-                    field.label = f.label
-            field.html_name = field_id
-        elif isinstance(f, (list, tuple)): 
-            if len(f) == 4:
-                field_name, default, query_key, field_id = f
-            elif len(f) == 3:
-                field_name, default, query_key = f
-                field_id = field_name
-            else:
-                field_name, default = f
-                field_name, query_key = expand_search_field(model_class, field_name)
-                field_id = field_name
-            
-            if f[0].startswith('?'):
-                field = forms.fields.ChoiceField(choices=((ANY, '---------'), (YES, u'Yes'), (NO, u'No')), label=get_model_field(model, field_name).verbose_name)
-                default = boolean_to_choice(default)
-                #field = forms.fields.BooleanField(label=model._meta.get_field_by_name(field_name)[0].verbose_name)
-            else:
-                field = get_model_field(model, field_name).formfield()
-                if field is None:
-                    raise Exception("%s.%s has no formfield"%(model.__class__, field_name))
-                field.empty = False
-            field.initial = default
-            field_id = field_name
-            
-        elif isinstance(f, (str, unicode)):
-            field_name, query_key = expand_search_field(model_class, f)
-            if f.startswith('?'):
-                field = forms.fields.ChoiceField(choices=((ANY, '---------'), (YES, u'Yes'), (NO, u'No')), label=get_model_field(model, field_name).verbose_name)
-                default = boolean_to_choice(default)
-                #field = forms.fields.BooleanField(label=model._meta.get_field_by_name(field_name)[0].verbose_name)
-            else:
-                field = get_model_field(model, field_name).formfield()
-                if field is None:
-                    raise Exception("%s.%s has no formfield"%(model.__class__, field_name))
-                if get_model_field(model, field_name).default != django.db.models.fields.NOT_PROVIDED:
-                    default = get_model_field(model, field_name).default
-                else:
-                    default = None
-                field.empty = False
-            field.initial = default
-            field_id = field_name
-    
-        field.widget.attrs['class'] = field.__class__.__name__
-        field.required = False
-        
-        field.help_text = None
-        fields[field_id] = field
-    return fields
-
-def boolean_to_choice(b):
-    if b not in EMPTY_VALUES:
-        if b:
-            return YES
-        else:
-            return NO
-
-def get_model_search_query(model_class, search_fields, form, request):
-    from o9.forms import SearchField
-
-    if form.is_valid():
-        search = {}
-        for f in search_fields:
-            
-            if isinstance(f, SearchField):
-                field_name = f.field_name
-                field_id = f.field_id
-                query_key = f.query_key
-            
-            elif isinstance(f, (list, tuple)):
-                if len(f) == 4:
-                    field_name, default, query_key, field_id = f
-                elif len(f) == 3:
-