User groups and permissions - django

I need to implement user rights for user groups (pretty similar to facebook groups). For example, each group can have members with rights like: can_post, can_delete, can_ban, etc. Of course, one user can be a member of many groups and group can have many different users with different rights.
What models I need for this functionality?

Django has a built in groups system. Whenever you have a question like this, I recommend searching the Django docs, which are extensive, helpful, and well written.
So long as you are using the django.contrib.auth app, you have access to groups. You can then assign permissions to those groups.
from django.contrib.auth.models import User, Group, Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get(app_label='myapp', model='BlogPost')
permission = Permission.objects.create(codename='can_publish',
name='Can Publish Posts',
content_type=content_type)
user = User.objects.get(username='duke_nukem')
group = Group.objects.get(name='wizard')
group.permissions.add(permission)
user.groups.add(group)

Related

How to enforce user permissions using user Groups in Django Class Based Views

In my Django app, I have created Groups and assigned (selectively) Permissions the Groups. And later assigned the Groups to the Users. These steps were carried out in the app's admin.
Now I am trying to restrict certain views to the users (using CBV) like as under:
class UomListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
template_name = "..."
context_object_name = 'unit_meas'
model = U_o_M
permission_required = 'myapp.view_u_o_m'
def get_queryset(self):
return U_o_M.objects.order_by('uom')
As expected I am able to restrict access to the view to users who are assigned the permission "myApp.view_u_o_m".
My understanding of the system is that if a user is attached to a Group which has permission "view_u_o_m" should be automatically assigned the privilege of accessing the view.
To quote (from Admin > Change User page):
The groups this user belongs to. A user will get all permissions
granted to each of their groups.
However, when I remove the line permission_required = 'myApp.view_u_o_m', anticipating that the user Permission will hold good but it doesn't and I get an error saying
View is missing the permission_required attribute. Define... or override .get_permission_required().
Obviously I am wrong about how defining "Groups" affect the Permissions scenario.
May I ask somebody to help clarify the issue here and how to use Groups to control access to views.
Thanks

Django groups, roles and permissions

I have a question: there's employee app in my project and I want employees to have different titles such as sales representative, manager and etc. and my views behave differently depending on employee's title. For now I have model Titles (title_code, title_name) but I feel like it could've been done with Django's builtin modules. So what do I use for building hierarchy? Groups, roles or permissions?
The django groups, role and permissions system is for allow or denay action in administration pannel, for this reason these three components work together.
If in your application all these type of user have access in admin pannel I suggestion you to use the Groups, roles and permission system
But If your users haven't the access to admin pannel you can avoid using it.
In first option you can create a different roles for every users and allow some permissions for each but if you have groups of users with same permission you can regroup they in a group. For more info view this https://docs.djangoproject.com/en/4.0/topics/auth/default/#permissions-and-authorization
If you do not need any specific privileges for each employee title, then choices would be pretty simple to implement like below
Sample Example
from django.db import models
class Employee(models.Model):
SALES_MANAGER = 1
HR_MANAGER = 2
ENGINEERING_MANAGER = 3
ROLE_CHOICES = (
(SALES_MANAGER, 'Sales Manager'),
(HR_MANAGER, 'HR Manager'),
(ENGINEERING_MANAGER, 'Manager'),
)
employee_title = models.CharField(max_length=100, choices=ROLE_CHOICES, default='Manager')
But do note that if you want to add new employee title's then a re-run of migrations would be required. If you need to avoid this then groups would be a better choice.
from django.db import models
from django.contrib.auth.models import Group
class Employee(models.Model):
employee_title = models.ManyToManyField(Group)
With groups, you would be able to create new entries without any migrations directly from admin panel.

How to create user groups for permissions within code (not in admin)

I'm wanting to create user groups for permissions and am wondering how to do this in the code as it sounds like the more proper way to do it (or not?).
I have done some searching and have found a few completely different pieces of code, but I am not even sure in which file this code should be located? Here is one example that I found:
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from api.models import Project
new_group, created = Group.objects.get_or_create(name='new_group')
# Code to add permission to group ???
ct = ContentType.objects.get_for_model(Project)
# Now what - Say I want to add 'Can add project' permission to new_group?
permission = Permission.objects.create(codename='can_add_project',
name='Can add project',
content_type=ct)
new_group.permissions.add(permission)
Thank you.

Django restrict views by User permissions which are editable in the Admin

I have a Django application where I need to restrict specific Views to subset of Users. I also want to be bale to edit which Users have this permission via the Django Admin. So in the admin I would like to be able to see all users and have a check box which can be checked to give permission to see this specific Views.
I believe the way to approach to this is to a permissions decorator on the Views in question:
from django.contrib.auth.decorators import permission_required
#login_required
#permission_required('user.can_view_restricted', login_url='/accounts/login/')
def Restrictedview(request, template_name='restricted.html'):
...
# restricted stuff
Now I know I need to define this permission (in permissions.py?), and register it with the Admin. I am unsure of how to do this and how to properly associate the permission with a specific User instance. Should this be an extra field on 'User', or a separate model to hold model to hole Users and Permissions?
You can read in details about django permissions in the docs
https://docs.djangoproject.com/en/dev/topics/auth/default/#permissions-and-authorization
Basically Django permissions use the Permission model, which is found at django.contrib.auth.models, but for most applications you don't need to directly import or use that model.
By default Django creates 3 default permissions for any model you have in your app. If you have a model named MyModel in an app named myapp, then Django will create create_mymodel, change_mymodel, and delete_mymodel permissions by default.
You can check if the user has a certain permission by calling
user.has_perm('myapp.create_mymodel')
if you're checking for the create permission for example. Or, like you did, you can use the decorator
permission_required('myapp.create_mymodel')
In addition to the default permissions provided by django, you can define custom permissions on your models by specifying the permissions attribute in the Meta class of your model like this:
class MyModel(models.Model):
[...]
class Meta:
permissions = (
("can_deliver_pizzas", "Can deliver pizzas"),
)
More on defining custom permissions here: https://docs.djangoproject.com/en/dev/ref/models/options/#permissions
By default, permissions can be easily edited for every user using the admin interface. Just visit a certain user's page and there will be a field named User Permissions with a list of all permissions in your project, from which you can add or remove permissions for your particular user.

Django: Add multiple user to one group in admin interface

At the moment i'm settting up the permissions in my project and i assigned some permissions to one user group. Now i have to assign a large number of users to this group, so that they can us the permissions of the group.
Problem:
I have to click on every user in the admin interface, add them to the group and the same for the next ones. This takes a large amount of time. Is it possible to select anywhere all users that should belong to a group? That would be much faster...
If it's not possible with the standard admin interface, is there an app I can install and use for this (like "South" for database migration tasks)?
Use the django shell:
$ python manage.py shell
>>> from django.contrib.auth.models import User, Group
>>> the_group = Group.objects.get(name='the_name_in_admin')
>>> users = User.objects.exclude(groups__name='the_group_you_made_in_admin')
>>> for i in users:
... i.groups.add(the_group)
... i.save()
>>>
For more information on the api of the authentication system, have a read through the documentation