Julian Popov
Julian Popov

Reputation: 17461

Django Auth, Users and Permissions

I have a Organization and Employee models

class Organization(models.Model):

    is_active = models.BooleanField()
    name = models.CharField(u'Name', max_length = 255)
    ...

class Employee(models.Model):
    user = models.OneToOneField(User)
    organization = models.ForeignKey(Organization)
    ...

Will it be good if I use AUTH_PROFILE_MODULE, so Employee becomes user profile?

This way I can use Django permission system to set employees permissions, like

Is is OK to have a permissions that are not a global one like "can see all documents"?

And what If I also want to have a permissions per Organization? How to do this? And how to distinguish permissions per Organization and per Employee?

Edit: I'm using Django 1.4

Upvotes: 1

Views: 2251

Answers (1)

Tomáš Plešek
Tomáš Plešek

Reputation: 1492

In short, yes, you're ok.

Because:

1) Using AUTH_PROFILE_MODULE=Employee will make Employee instance to be available for instance in this way:

def view(request):
    employee_instance = request.user.get_profile()

2) Using custom permissions is easy, see: https://docs.djangoproject.com/en/dev/topics/auth/#custom-permissions

Edit:

having custom permissions on organizations is possible as well, probably best if you create permissions programatically, like mentioned in the manual, this way:

content_type = ContentType.objects.get(app_label='myapp', model='Organization')
permission = Permission.objects.create(codename='can_do_something', name='Can Do something',
                                       content_type=content_type)

now, you have permission aware organization model, you just assign it to your user.

To clarify more:

Django auth system is sort of a fixed ACL. You assign roles to a user (or group) and that's pretty much it. Django offers helper wrapper function to easily filter out users who don't have a given permission. If you need to decide at runtime and/or in more generic way, whether an object has permission to do something, you either need full blown ACL system (and which django.auth is not) or you code that kind of behavior yourself. This depends on your needs and obviously on the need to manage those permissions. In the OP's case, the behavior is fixed, therefore I would recommend just coding this in and be happy. But the needs may vary and so does the solution. Django auth is good at assigning static permissions to user, gropu or a "profile" object. What that means to your app is up to you in the end.

So in this case, the good solution would be to have a fixed set of permissions like "can view own documents" or "can view organization documents" that is assigned to user/group. And you app should decide, what it means and serve documents accordingly, taking either runtime state in the account or using models structure to determine the proper data set to serve.

Upvotes: 4

Related Questions