I am using Django to make a website with a bunch of different pages. I only have views, I have not defined any models in my project. I want certain users to have restricted access (they can only see some of the views I've created). I've set up some users in the Django admin site and added login functionality to my website using the Python #login_required decorator.
I'm a little lost on how to set viewing permissions for each user though. I've looked at the #permission_required decorator but it seems to only pertain to models and not views. How do you set page viewing permissions in Django?
Permissions are linked to models. If your authorization logic is linked to the view and not to a model, consider creating a group and using the user_passes_test decorator. For example, lets say you have a report that only supervisors can see: create a group named Supervisors and test for membership:
def must_be_supervisor(user):
return user.groups.filter(name='Supervisors').count()
#user_passes_test(must_be_supervisor)
def quarter_report(request):
...
You should use user_passes_test decorator for views. Django documentation has a nice example of it's usage
https://docs.djangoproject.com/en/1.8/topics/auth/default/#django.contrib.auth.decorators.user_passes_test
Edited: actually you can use permission_required decorator for views also
https://docs.djangoproject.com/en/1.8/topics/auth/default/#django.contrib.auth.decorators.permission_required
Take a look at django-braces. It's a superb app for exactly this purpose;
https://django-braces.readthedocs.org/en/latest/index.html
It provides a mixin for almost every eventuality for use in views & forms which allow you to perform checks to restrict access how you see fit.
you can use permission_required in urls to lock
example: https://docs.djangoproject.com/en/3.2/topics/class-based-views/intro/#decorating-in-urlconf
Related
I am using Django Rest Framework with React on the Frontend. I am using Token Athentication and its all working fine. I now have a requirement of making sure different users can access different things depending on their rights. This is possible using Django admin but my users will be using the React frontend.
I looked through Django Rest permissions but I didnt see how I can use this on my React Frontend. I also looked at Django guardian but I am not sure if its what I need for my requirement. I have looked through many tutorials and articles but I can't seem to find any straight forward way to achieve this.
Here is the approach I have used sofar:
Created a Serializer for the inbuilt User Model, then Created a ViewSet and I can now access the list of users through the api.
from django.contrib.auth.models import User
class UserSerializer(SerializerExtensionsMixin,serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
class UserViewSet(SerializerExtensionsAPIViewMixin, viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
router = DefaultRouter()
router.register(r'user', UserViewSet, basename='user')
Using this I am able to access a user with the groups and permissions as shown in the picture below. I am now going ahead to call the api url on my React frontend and somehow use the permissions and groups associated with the user to control what the users can see.
Is there a better way to achieve this requirement? Am I doing this the right way? Has someone done this and may be I can borrow from their experience?
DRF provides permission classes, Also if you need some customization you can do so by creating custom permission classes. Refer https://www.django-rest-framework.org/api-guide/permissions/#api-reference.
On React side if you are using React router you can guard each route on some roles /permissions received from backend.
Refer https://hackernoon.com/role-based-authorization-in-react-c70bb7641db4
This might help you
I have been testing a few django voting apps and found qhonuskan-votes. I have managed to install it and is works great. However, I also want it allow voting rights to non authenticated users which I am not able to do. Need help with this please.
Here is the link for its models.py, views.py and compact.py files of this app.
models
views
compact
You could write a custom view which would look like def vote(request, model, object_id, value) from the external app, but without this piece of code in it:
if not request.user.is_authenticated():
return HttpResponse(status=401)
Also make sure, that you map your custom view to the correct url instead of including app's urls:
url(r'^vote/$', view='custom_vote', name='qhonuskan_vote'))
This is not the best solution, because you are simply rewriting the code from the external app and I can't think of any proper way to override the default view in a way that would suit your needs. A better solution would be to use a different app, which allows votes by unauthenticated users (if a few lines of additional code are not a problem you can use this).
I am looking at the built-in authentication functionality from Django for my custom app.
If I understand this right, I can assign add, change, delete rights to models.
I am looking for a solution to assign view/show rights to a user.
My basic idea is to use the permission_required decorator for this, but as stated this only works for add, change, delete and in addition it seems only to work for models. I have functions where I am using multi-objects from models.
The best would be to have something that collects my custom permission_required decorators and gives me the possibility to edit this e.g. in the Django admin UI.
E.g.
#permission_required('user.profile.view')
def myProfile(request):
...
#permission_required('user.profile.edit')
def editMyProfile(request):
...
Any idea or suggestion is welcome.
Thanks in advanced!
Creating custom permissions is well documented. Once you've created custom permissions, you'll be able to assign them to users through the usual user admin page.
I want to create a helper screen that can create a bunch of Django auth users on my site and have those accounts setup the same exact way as if they were done one by one through the Django auth GUI signup. What methods from Django auth would I have to use in my view to accomplish this?
To create users you can use the method create_user from the UserManager:
from django.contrib.auth.models import User
new_user = User.objects.create_user('username', 'email', 'password')
Then you can set is as staff new_user.is_staff = True or add permissions new_user.permissions.add(permission).
Check this link for more information.
What are you trying to accomplish exactly? Are you just trying to populate your user database with a bunch of fake/test users? Then simply do some logic to do so and save the models like you normally would.
If you require the UI to be used, one option you have is using Django's test client which allows you to pragmatically write get/post requests just like you were to be someone browsing the web page.
Hope that helps as a start.
A quick check here indicates you'd just need to use the input from your form to create a group of django.contrib.auth.models.User objects, and related/relevant groups of django.contrib.auth.models.Permission objects to associate with the User objects. Create, set permissions, save, and you're done.
I am building a Django site framework which will power several independent sites, all using the same apps but with their own templates. I plan to accomplish this by using multiple settings-files and setting a unique SITE_ID for them, like suggested in the Django docs for the django.contrib.sites framework
However, I don't want a user from site A to be able to login on site B. After inspecting the user table created by syncdb, I can see no column which might restrict a user to a specific site. I have also tried to create a user, 'bob', on one site and then using the shell command to list all users on the other side and sure enough, bob shows up there.
How can I ensure all users are restricted to their respective sites?
The most compatible way to do this would be to create a user Profile model that includes a foreign key to the Site model, then write a custom auth backend that checks the current site against the value of that FK. Some sample code:
Define your profile model, let's say in app/models.py:
from django.db import models
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
site = models.ForeignKey(Site)
Write your custom auth backend, inheriting from the default one, let's say in app/auth_backend.py:
from django.contrib.auth.backends import ModelBackend
from django.contrib.sites.models import Site
class SiteBackend(ModelBackend):
def authenticate(self, **credentials):
user_or_none = super(SiteBackend, self).authenticate(**credentials)
if user_or_none and user_or_none.userprofile.site != Site.objects.get_current():
user_or_none = None
return user_or_none
def get_user(self, user_id):
try:
return User.objects.get(
pk=user_id, userprofile__site=Site.objects.get_current())
except User.DoesNotExist:
return None
This auth backend assumes all users have a profile; you'd need to make sure that your user creation/registration process always creates one.
The overridden authenticate method ensures that a user can only login on the correct site. The get_user method is called on every request to fetch the user from the database based on the stored authentication information in the user's session; our override ensures that a user can't login on site A and then use that same session cookie to gain unauthorized access to site B. (Thanks to Jan Wrobel for pointing out the need to handle the latter case.)
You can plug your own authorization and authentication backends that take the site id into consideration.
See other authentication sources on the django documentation and the authentication backends references
Besides that, if your django source is too old, you can always modify the authenticate() or login() code yourself. After all... Isn't that one of the wonders of open source. Be aware that by doing so you may affect your compatibility with other modules.
Hope this helps.
You have to know, that many people complain for Django default authorization system and privileges - it has simply rules for objects, for instances of the objects - what it means, that without writing any code it woudn't be possible.
However, there are some authorization hooks which can helps you to achieve this goal, for example:
Take a look there:
http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
and for class Permission.
You can add your own permission and define rules for them (there is a ForeignKey for User and for ContentType).
However2, without monkeypatching/change some methods it could be difficult.