Setting Django admin permissions programmatically - django

The Django site I'm working on has the possibility for users to sign up for an account. To provide them with some editing functionality, I use the built-in Django admin. However, I'm having a problem: After a user has signed up, they don't have any permissions inside the Django admin, not even view permissions. Thus my question: How do I, in code, assign admin permissions to the user for the relevant models, in the same way I can assign them manually in the "User Permissions" section when editing the user in the admin? I've already tried with the usual has_xxx_permissions() using custom ModelAdmin classes, but that didn't work. So my guess is that I overlooked something obvious. Any ideas?

https://docs.djangoproject.com/en/dev/topics/auth/default/#permissions-and-authorization
new_user.user_permissions.add(permission1, permission2, etc...)

For your purposes, it would probably be much more easy and and efficient to assign all new users to a particular group, and then give that group all the permissions the user needs. Any member of the group will inherit those permissions as well.
You can create the group and assign the permissions to it in the admin. Then, you just need to add something like the following to your registration code.
try:
group = Group.objects.get(name='The User Group')
except Group.DoesNotExist:
# group should exist, but this is just for safety's sake, it case the improbable should happen
pass
else:
user.groups.add(group)

dgel's answer pointed me in the direction which lead to a working solution for me. Essentially, what he seems to be suggesting is:
Retrieve a ContentType for the model you want to set permissions for. In this context, a content type is an object that holds information about a Django model.
Create a Permission object consisting of the content type and the action you want to allow inside the admin, using Permission.objects.get(). The only difficulty here is figuring out the codename parameter, which, for admin permissions, consists of an action ("add", "change" or "delete"), an underscore, and the model name. So if you have a model called Foo and you want to create all permissions for it, you'll need 3 permissions, each with the content type of your Foo model plus the code names add_foo, change_foo, and delete_foo.
Assign these permissions using user.user_permissions.add(permission).
Head over to dgel's answers for code examples. Looking at a data dump of the auth app (manage.py dumpdata auth) of an existing Django database provided me with insights into the inner workings of permissions, too.

I'll answer your question exactly since I found this question with Google. I'll show what I'm doing in Django 1.9 with groups, then show how to do it to a user.
from django.contrib.auth.models import Group, Permission
group, __ = Group.objects.get_or_create(name='my_group')
permissions = Permission.objects.all()
for p in permissions:
group.permissions.add(p)
group.save()
It's pretty easy to adapt to user:
from django.contrib.auth.models import Permission
permissions = Permission.objects.all()
for p in permissions:
youruser.user_permissions.add(p)
youruser.save()
I prefer group because you may be adding permissions in the future and can just add to group instead of re-doing all users.

As of Django 1.6:
Every User has a many-to-many field user_permissions to Permission - you can add permissions to this:
your_user.user_permissions.add(permission)
v1.6 Docs:
Django.contrib.auth API (shows User, Group and Permission objects)
Auth default permissions (shows how to clear, add, remove)

Related

How do I apply higher permissions to child pages in Wagtail?

I am building an intranet site for my organization with Wagtail and we are in the process of adding a knowledge base. The entire site needs to be restricted to logged-in users, but certain pages need to only be accessible to users in certain groups. For instance, only members of the IT group should be able to access the pages underneath the IT Knowledge Base page.
Currently if I set the top-level page to be accessible only by logged-in users, that permission is applied to every page on the site, and I am barred from setting more specific permissions on any child page. It is imperative that I be able to set more specific permissions on child pages.
I was able to find Wagtail Bug #4277 which seems to indicate that the logic for more specific permissions is implemented but not exposed in the admin UI.
I am not familiar with the inner workings of Wagtail yet, especially how Wagtail permissions intersect with Django permissions. How can I add more specific permissions to child pages?
You can restrict or allow users to view a site. You can also restrict or allow users to do some actions (maybe modifying an article).
To pass these restrictions or allowances django uses groups and permissions. Basically it all is based on permissions but sometimes you want to pass the permission to an entire group rather than passing permissions to users explicitly.
Therefore you could create your it_group. Then you would add the permission, let's call it it_permission to that group. When you then add a user to that group, that user then has all the group permissions. As said you don't need to organize these steps with groups. You could also add a permission, let's call it admin_status to a user directly.
When you build your views there are multiple operators that check for permissions of currently logged in user.
You could decorate your view with the permission-required-operator.
See the example:
from django.contrib.auth.decorators import permission_required
#permission_required('your_user_app.it_permission')
def my_view(request):
# only users with permissions can view this view.
Django and Wagtail are both awful at object authorisation.
For your case, it depends how tight you want to make the security, and how complex the authorization model is.
You can set permissions on a per page basis via the group edit page in the admin menu, any page below will inherit those permissions. The problem with this is that the least restrictive permissions apply and there is no deny option. If they have edit permission on a parent page, they'll have edit permission on the child page.
If you just want a superficial prevention to stop unauthorised people editing all knowledge base pages, you might look at using hooks to assess the permissions of the logged in user.
You can use before_edit_page to check before the page form is rendered for editing and redirect to a notification page if they fail, or use after_page_edit to prevent saving (not very friendly after the editor has spent some time on the page).
For before edit, for a simple one-off case and where there is a class for the KB page, where you want to allow only members of the IT Department and Site Managers groups to have access, it could be something like:
# wagtail_hooks.py
from django.contrib import messages
from django.http import HttpResponseRedirect
from wagtail import hooks
from kb.models import KnowledgeBasePage
#hooks.register("before_create_page")
#hooks.register("before_delete_page")
#hooks.register("before_edit_page")
def check_kb_permissions(request, page, page_class=None):
if (page_class or page.specific_class) == KnowledgeBasePage:
if not request.user.groups.get_queryset().filter(name__in=['Site Managers','IT Department']).exists():
messages.error(
request,
'You do not have permission to add, edit or delete knowledge base articles.\
<br><span style="padding-left:2.3em;">Contact support \
to report this issue</span>'
)
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/admin/'))
If the user fails, they stay on the same page with an error message in red banner at the top of the page.
You can build this out to a more complex authorisation model, matching user groups with models and permissions if need be, rather than the hard coded example above.
This doesn't affect CRUD permissions for programmatic operations, but if your concern is just the editor interface then this works.

How to Implement multiple kinds of users in Django?

I am new to Django so please bear with me if my questions seem too basic.
So, I want to create a web app for a kind of a store in which I have three different kinds of users.
Admin(Not Superuser) who can:
create, view, update, delete account for a Seller(agent)
issue them inventory
Seller who can:
sell an inventory item to a Customer(customers cannot themselves purchase it, only the seller can do it by filling in a form)
a Customer account should automatically be created upon submission of the form by Seller or if the Customer already has an account, the purchase should be added to their account
Customer
can login and view their account
What would be the best way to go about it? Using auth Groups, Profile models or anything else?
Any help would be wonderful. If something is not very clear in the question, I can provide more details. Thanks.
Django already has a solution for this: a Group [Django-doc]. A user can belong to zero, one or more groups. A group can have zero, one or more Permissions [Django-doc].
These permissions can be defined by a Django model, for example for all models there are permissions, to view, add, change, and delete objects of a certain model, but you can define custom permissions as well, for example to visit a certain page. A user then has such permission if there is at least one group they are a member of that has such permission.
You can work for example with the #permission_required decorator [Django-doc], or the PermissionRequiredMixin [Django-doc] to enforce that only users that have the required permission(s) can see the given page.
You thus can make groups for a seller, customer, etc. Often people can have multiple roles, for exame being both a seller and a customer which thus is elegantly solved through the permission framework.

Giving default permissions or a default group to new users

Default behaviour seems to be new users have no permissions and no groups. However I'd like not to have to manually grant every single new users basic permissions, and I'd assume they'd like not to have to wait for me to do so.
How should I assign default permissions for new users?
Some similar questions have been asked but with no clear answer for the general case:
Django default user permissions
How do I define default permissions for users in Django Guardian?
Django Assign-perm w/ Post-Save Signal
I'm using python-social-auth so I don't have my own create-user form and view which I guess is where everyone else sets default permissions. I assume I need an on-user-create hook of some sort but not sure what the cleanest approach is.
This is unrelated to creating the default possible permissions that may be granted to users, although for reference,
Default permission/group data in Django
In Django, how do you programmatically create a group with permissions
You can subscribe to post_save signal on User model and put newly created user to desired group or add permissions.
from django.contrib.auth.models import Group
def add_to_default_group(sender, **kwargs):
user = kwargs["instance"]
if kwargs["created"]:
group = Group.objects.get(name='groupname')
user.groups.add(group)
And on django 1.8+ put following code into your AppConfig.ready()
from django.conf import settings
post_save.connect(add_to_default_group, sender=settings.AUTH_USER_MODEL)

Rolling out own permission app or modifying django permission

I am working on a project which needs a separate admin interface. The django admin interface is for the super super user, there will be companies who will sign up for our app and then they will have their own admin interface. Everything is set and done despite the permission. We want model level permission that's what Django provides.
What I did is:
class CompanyGroup(models.Model):
name = models.CharField(max_length=254)
permissions = models.ManyToManyField(Permissions)
Now this list all the permissions of the site itself. So, Should I start working on my own permission app or I can modify django Permissions to provide object level permissions for only some models.
Thanks
Try one of the several existing 'row level' / 'per object' permissions apps for Django:
http://django-guardian.readthedocs.org/en/v1.2/
http://django-object-permissions.readthedocs.org/en/latest/
...there are probably others, those are just the first two in Google
We are using django-guardian in current project at work, seems fine.
I am assuming that you need to control access to sub-sets of each model's objects, depending on which company the current user belongs to (i.e. you don't want people from Company A to see items from Company B). For this reason you need row level permissions.
You probably also need to limit the permissions of all 'company users' to only certain actions:
You do not need to create a CompanyGroup class.
Instead just enable the admin site, log in as super user and create a django.contrib.auth.models.Group which contains the global permissions applicable to company users.
then ensure when you create any new company user logins that they are added to that Group

Differences between various permission levels in Django

As far as I know, there are 3 permission levels available to use in django (whether by django itself or by using 3rd party apps).
1) Model-based permission
2) Object based permission
3) Row-based permission
It would be great if you tell me the exact differences between these 3 levels of permission system.
Not sure where you got that info, but it's not even remotely correct. Django technically doesn't have any permission system. The auth contrib app adds a system of "permissions" but it's optional and could be replaced entirely with something else. The admin app (also a contrib package, and optional) uses auth, so if you're talking about the Django admin, or using the auth package with your own app(s), then we can talk.
In auth, you have Users, Groups and Permissions. Users come in either "superuser" or "regular" user flavors, and every model in your project gets three Permissions automatically when you run syncdb (with auth included in INSTALLED_APPS): can_add, can_change, and can_delete. Users marked as "superusers" (is_superuser == True), can take any action on any model. Other users need to have Permissions explicitly assigned to them. Further, Groups may have Permissions assigned to them, and then, any User assigned to that Group inherits those permissions.
So, a user could have no ability to do anything with any model, some combination of add, change or delete capability with some or all models or complete access to do anything with any model. There's no concept of "object-based" permissions, in the sense of an "instance". You can either either edit every instance of an model or none. There's also no concept of "row-based" permission. A row in the database table is merely an instance of the model, anyways.