Django role based views? - django

I'm looking for some input on how others would architect this. I'm going to provide class (django group) based views.
For example, a user's group will determine what views/templates he or she will have access to. I'm thinking of perhaps storing paths to view functions in a table to determine what a user's link bar will consist of. Filter specifications can also be stored to determine what rows will fill these templates.
A good example is a hospital nursing units. Nurses at one unit need not see the entire hospital's patients. They only need to see their patients. Doctors on the same unit need only to see those patients as well, but they should have access to much greater functionality.
Has this been done via some third party application? And how would you approach this problem?
Thanks,
Pete

Django already has a groups and permissions system, which may be sufficient for your purpose.
http://docs.djangoproject.com/en/dev/topics/auth/
Generally in your code you check if a user has a permission. A user has his own permissions and those of the groups he belongs to. You can administer this pretty easily from the admin console.
There are two parts you need to look at.
Check that a user requesting a page
has permission to do so.
Only display links to the user if he
has the permission.
For 1. you can check permissions in a decorator as such:
from django.contrib.auth.decorators import permission_required
#permission_required('polls.can_vote')
def some_view(request):
For 2. the currently logged-in user's permissions are stored in the template variable {{ perms }}. This code checks the same permission as above.
{% if perms.polls.can_vote %}
vote
{% endif %}
To generate a list of links you can iterate over user.get_all_permissions() and fetch the links (or function that generates the link) from a dict:
def more_elaborate_list_of_links_for_a_perm(user):
return ["/link1", ...]
_LINKS = {
'polls.can_vote' : lambda u: ["/user/specific/link/" + u.id],
'polls.can_close': lambda u: ['/static/link/1', 'static/link/2'],
'polls.can_open' : more_elaborate_list_of_links_for_a_perm
}
def gen_links(user):
# get_all_permissions also gets permissions for users groups
perms = user.get_all_permissions()
return sum((_LINKS[p](user) for p in perms if p in _LINKS), [])
There are probably many other approaches.

We had a similar problem. Django's groups aren't REALLY suited to this, but you can shoehorn them in.
The way we did it was as follows:
Every access-controlled object has a ManyToMany relation to the groups table. Each group was used to define a specific type of permission ("can view patient basics", "can edit patient contact info", and so on). Users are added to the groups that they should have permissions for (in your example of seeing only patients in this hospital, you could have a "valley-view-hospital" group).
Then when you go to display a list of records to a user, you filter based on the conjunction of the two groups. A user has to have all the associated group permissions to view a given object.
If your system requires it, you can keep a separate ManyToMany of negative permissions, or separate read/write permissions. You could also define a set of meta-groups (doctor, nurse) that result in your lookup filter retrieving the actual subset of permissions.
As far as your link-bar problem goes, you can generate those programatically using the same system - filter based on the classes of objects the user can see or edit, and then use a get_absolute_url() type function (maybe call it get_index_url()) to return the links for the index of each class of object.
Because all this is fairly complex, you'll probably end up wanting to do some level of caching for these things, but get it working before you bother optimizing. It is possible, and it's less ugly in code than it is in words.

There is a new very interesting project about role based permissions in Django:
http://bitbucket.org/nabucosound/django-rbac

I had a similar problem not too long ago. Our solution did the trick, though it might be too simple for your situation. Like everyone is suggesting, we used the django permission system to control what user interactions with models. However, we didn't just try to group users, we also grouped objects through a GenericForeignKey.
We built a model that linked to itself to allow for hierarchies to be developed.
class Group( models.Model ):
name = models.CharField( ... )
parent = models.ForeignKey( 'self', blank=True, null=True)
content_type = models.ForeignKey( ContentType )
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey( 'content_type', 'object_id' )
...
To make it work, we also created a model to serve as the django User model's user profile. All it contained was a ManyToManyField linked to the Group model above. This allowed us to give users access to zero or more Groups as required. (documentation)
class UserProfile( models.Model ):
user = models.ForeignKey( User, unique=True )
groups = models.ManyToManyField( Group )
...
This gave us the best of both worlds and kept us from trying to shoehorn everything into django's permission system. I'm using this basic setup to control user's access to sports content (some users can access whole leagues, some only one or two conferences, some only have access to individual teams), and it works well in that situation. It could probably be a generalized enough to fit your needs.

If you don't need real per-object ACLs, then you can just use the Django permission system. To get a list of all available permissions:
from django.contrib.auth.models import Permission
perms = Permission.objects.all()
There is an API for other authentication and authorization sources, so you do not need to stick with this permissions table.
You may hack this Django system to fit your needs in terms of this authorization model (RBAC) or you may come up with an ACL-like solution.

On a site for an expert on Pinot Noir wine we created per-object access based on a number of different criteria. If the inbound link had a referer field that matched the domain name of a featured winery, then the user got a 'winery token' which expanded to all articles, tasting notes, etc. related to that winery. We use 'named tokens' for give aways at tasting events and they gave access to specific parts of the site. We even use this to grant certain types of permissions to search engine spiders and then make sure that links that come from those search engines have the same permissions as the spider did (ie. no cloaking games).
The short version is that you can create a class (we called them TokenBuckets which hold Tokens) and each object (on a detail page, or a list page, or whatever) can ask the user's TokenBucket if a certain level of access is allowed.
Basically it's a weird kind of ACL system. It wasn't that hard to create the mechanics. All of the magic is in determining under what circumstances which tokens go into the bucket.

You can use django user roles
https://github.com/dabapps/django-user-roles

This question has been asked in Oct 2009 and the problem still exists in July 2012.
I have searched for a good Role-Based app, and found django-permission as the best result.
Three important features that I needed were Roles, view Decorators and Templatetag; apparently django-permissions has all of them. Read it's docs for it's usage.
The only drawback is that it's under development.

We used a role base system for a similar problem.
Basically users have permissions to assume different roles.
View functions got decorated:
def needs_capability(capability,redirect_to="/cms/"):
def view_func_wrapper(view_func):
def wrapped_view_func(request,*args,**kwargs):
if not request.role._can(capability):
return HttpResponseRedirect(redirect_to)
return view_func(request,*args,**kwargs)
return wrapped_view_func
return view_func_wrapper
The rest of the magic is inside the request.role attribute which got
set inside a context processor. Authenticated users got a Role, for the unwashed masses
a DummyRole.
Access to information was restricted further inside the templates:
{% if not request.role.can.view_all_products %}
Lots of products, yeah!
{% endif %}
Not the cleanest solution in my opinion, but worked as expected.

Related

Django-single user with multiple employee account for each organization flow

Im creating an application where user is having multiple employee account with each organization. When i login with user credential it has redirect to choose organization page which has multiple organisations where i hold employee accounts and after choosing any one organization it has to redirect to dashboard page where all details related to the selected organization should be displayed. My doubt is when im doing multiple api calls in dashboard page whether i need to pass selected organization id in all requests?
ex: organization/orgid/team/teamid/members/team-member-id if this goes like this means url will grow long.Please help on this. Thanks in Advance.
No, you probably don't need long urls. In many cases you will just refer to the object(s) which a view should display or manipulate. Before allowing the user to do this, you check that the user has permission to access them. There are various ways to do this, but if the user profile has an organisation and the view object also has an organisation, you might define get_object for class-based views something like this:
def get_object( self, queryset=None):
obj = super().get_object( self, queryset)
if request.user.profile.organisation_id != obj.organisation_id:
raise PermissionDenied('...') # or Http404 "not found"
return obj
You need to do this anyway because a user can feed anything he wants to in though his browser's URL bar, for example to attempt to spy on some other organisation that he knows is sharing the system.
Some might also want to use UUIDs as primary keys for sensitive entities, rather than sequentially increasing integers. (Doing so also makes URLs much longer!). The reason is that successive integers are fairly guessable/ hackable, whereas UUIDs are not.

permissions in django for the group of users

In my wen application i mad different login for different person like for HR ,for engineer ,for owner using django user creation form , and authenticate them using Django authentication ,now everything is work very well i am able to add user from the front add
but the problem is that everyone get same power and authority , i can change it from the admin penal but it will not be beneficial for my client/user I WANT ALLOW DIFFERENT KIND OF PERMISSIONS TO DIFFERENT GROUP OF USER(daynamicaliy with using django penal) show How can i do that.
(i'm beginner so its request to all of you to give answer in some detail format)
THANK YOU
If you refer to the docs here, there is already a default system where you can add or remove permissions to a specific group of users. What you should do next is to create different subclasses for different types of users.
So your models will look something like this eventually:
class User(models.Model):
# just keep whatever you had here
# Engineer and Manager will both be subclasses of User
class Engineer(User):
# add whatever permissions you have
class Manager(User):
# add different permissions
In this way, you will be able to apply custom permissions to different groups of people.

Using the Django auth model for things other than permissions

Is it appropriate to use the Django auth model groups for something other than permission management? I am just learning Django, and am trying to make a site that manages groups of users. As an example, think of a site for managing email groups or local community charities or fan clubs or some such. I want to use the groups for managing things like sending an email to everyone in the group, or organizing an event and dividing the preparations between the group or any number of other things that are not permission related. Is this an appropriate use of the auth model, or am I doing this wrong?
If you're not going to use your groups to handle permissions, you'd better create a separate model, just because you'll hardly benefit of using the stock model (which is just a permissions container). And customization is much, much easier when you have a separate model. You could start with just:
class EmailGroup(models.Model):
name = models.CharField(max_length=100)
users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='email_groups')
and extend it to your needs.
But there's nothing wrong in using contrib.auth models in a different way. Django is a framework, not a CMS, so you're free to use it as you want.

Level Specific Access to pages on Django

I currently have a website that has three kinds of permissions:
Active
Staff
SuperUser
What I want to do is limit what a user can view depending on his subaccess level on Driver i.e. Driver has three sub access levels - 100, 200, 300. I was thinking of doing this by
def email_check(user):
return user.accesslevel
#user_passes_test(accesslevel=100)
def my_view(request):
...
How do I add the additional property of the subaccess level to the user model? Is there any other way to implement this? ALso, since this is a an already live project, there are a lot of user on-board already. I'll also need to provide them a default access value.
Your idea to go with user_passes_test looks good to me.
So your main issue is basically how to extend the user model. This topic is covered thoroughly under Django documentation: Customizing authentication.
To sum up, there are mainly two ways to go with. One is to extend your user model with a custom model with an one-to-one relationship with User and any custom fields such as access level.
Alternatively, you can provide with a custom user model and substitute the Django User model, but this seems not appropriate for your case.

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
can see all documents
can see own organization documents
can see his own documents
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
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.