Django Groups and Permissions. Extending Groups to have a FK?

落花浮王杯 提交于 2019-12-06 00:51:29

问题


I'm working on a product that allows different schools to administer their content online.

Part of this involves setting up a role based access control logic which I've written myself. Essentially, each school has its own set of roles that have their own set of permissions. A user of the software could belong to mulitple schools with differing roles at any given time.

For various reasons, I want to ditch this and instead use Django's Groups and Permissions together with a library like django-guardian. The problem that I am facing is how should I go about extending the Groups model such that I can include a Foreign Key to each new school and still be able to use the helper methods in Django and also libraries like django-guardian.

One possibly approach I came up with is to simply create groups based on event names such as 'School 1 - Admin', 'School 1 - Teacher', 'School 2 - Admin', 'School 2 - Teacher' and query permissions based on this instead. Is there a good reason why I shouldn't do it this way?


回答1:


Upon closer inspection, django-guardian was able to solve my needs. I wrote about my full implementation here: http://pragmaticstartup.wordpress.com/2012/06/26/django-guardian-a-full-access-control-logic-acl-example/




回答2:


Why not mix both approaches in? Django model allows for inheritence. First define the Role model, with allowed roles and a school model.

You can then inherit a new model from django.contrib.auth.Group say GroupRole. Django will create a new db table for your model only containing the properties not originally in group with a foreignkey to the appropriate group with constraints. Even better, you will get an automatic reverse relationship to the original group model, so you can write something like:

class GroupRole(Group):
    role = models.ForeignKey(Role)
    school = models.ForeignKey(School)
    ...

g = Group.objects.get(id=1)
# you can access standard group items here g.<attribute> or g.grouprole.<attribute>
# you can access GroupRole attributes by doing g.grouprole.<some_attribute>

GroupRole.objects.filter(role__type='admin', school__location__state='NY')

On a fun note, the relationship is reflective so something like this is valid if not too useful:

g.grouprole.grouprole.grouprole.grouprole.role

If you get a base group instance that does not have a grouprole proxy associated with it then you will get an exception thrown:

g = Group.objects.create(name='myplaingroup')
try:
    print g.grouprole
except GroupRole.DoesNotExist:
    print 'This is a normal group'

Alternatively you can override this behavior to return None instead of raising an exception or even provide a default GroupRole instead.



来源:https://stackoverflow.com/questions/11095296/django-groups-and-permissions-extending-groups-to-have-a-fk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!