I assigned a permission of a user in my Django 1.5 app.
When I list all user permissions with
In [1]: user.get_all_permissions()
Out[1]: set([u'profile.change_profile'])
I can see one permission (which is correct and wanted). The user is also not a superuser, not an admin.
In [2]: user.is_superuser
Out[2]: False
However, if I try to use user.has_perm, I always get True as a return for any submitted permission request.
In [3]: user.has_perm('random_permission')
Out[3]: True
A behaviour I would expect if the user is a superuser/admin. Why is a non-superuser getting always True for every request? Did I miss any setting?
As mentioned in comment by Thane Brimhall you should check your authentication backends.
You can find this comment on has_perm method of User model in django sources:
Returns True if the user has the specified permission. This method
queries all available auth backends, but returns immediately if any
backend returns True. Thus, a user who has permission from a single
auth backend is assumed to have permission in general.
Also don't forget to check user groups. Default backend checks for user groups permissions thus it may be connected.
Related
I'm working on the permissions on a Django 4.1 application. All these permissions are given by groups. First permission first problem:
Permission codename: can_see_all_images
appname for the permission: dating
group having this permission: X-Gold
As you can see on the screenshot it seems that all the informations are correct:
First line: User is in the group
Second line, the group has the permission
Third line: The permission has the good codename
but line4: the user doesn't have the perm.
I restarted the server disconnected the user and reconnected it, nothing changed.
Note that if I give the permission directly to the user, it doesn't work. So I guess the problem does not come from the group.
Any idea?
Here is how the permission is created in the model:
permissions = [('can_see_all_images', _('Can see all images'))]
edit: my view code:
#login_required
def public_images(request, slug):
visited = get_object_or_404(User, slug=slug, is_active=True)
user = User.objects.get(id=request.user.id)
if user.has_perm('dating.can_see_all_images'):
print('ok')
else:
print('KO')
return render(request, 'dating/public_images.html', locals())
Thanks in advance
I found the problem, so I post it here in case someone meet the same.
I am using a custom authentication backend. This backend inherits from BasicBackend. In this case you have to redefine the has_perm() method because in the BaseBackend the original method return an empty tuple.
If you don't want to redefine it you need to inherit from ModelBackend and not BaseBackend.
I'm having trouble understanding how to set permissions in Django. I want to have certain users who have the ability to view and modify a certain model that ordinary users cannot.
But after I assign permissions to a group, I cannot see the permissions assinged to the individual users in that group.
For example, in the shell:
from django.contrib.auth.models import Group, User, Permission
from django.contrib.contenttypes.models import ContentType
somemodel_ct = ContentType.objects.get(app_label='myappname', model='moderation')
can_view = Permission(name='Can View', codename='can_view_something',
content_type=somemodel_ct)
can_view.save()
can_modify = Permission(name='Can Modify', codename='can_modify_something',
content_type=somemodel_ct)
can_modify.save()
g = Group.objects.get(pk=1) # the group of moderators
g.permissions = [can_view, can_modify]
g.user_set.all() # can see alice and bob, alice is the superuser created after syncdb
alice.has_perm('can_view_something') # returns True
bob.has_perm('can_view_something') # returns False
Why aren't the permissions getting assigned to bob?
According to the documentation, permission should be in the format of <app label>.<permission codename>.
Returns True if the user has the specified permission, where perm is
in the format "< app label>.< permission codename>". (see documentation
on permissions). If the user is inactive, this method will always
return False.
Replace the following lines:
alice.has_perm('can_view_something')
bob.has_perm('can_view_something')
with:
alice.has_perm('myappname.can_view_something')
bob.has_perm('myappname.can_view_something')
And make sure that bob is an active user.
Why alive.has_perm(...) returned True
Django does not check permissions for active superuser. has_perm always return True for active superusers.
Relevant code:
def has_perm(self, perm, obj=None):
...
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
I want to do the following with django's authentication:
Log incorrect log-in attempts
Temporarily lock accounts after 'x' number of incorrect log-in attempts
Log successful log-ins.
I thought a custom auth backend would be the solution.
I can do most of what i want, but I want to log the IP and REMOTE_HOST of the user making the attempt.
how can I access the request object in the auth backend?
Thanks
The authentication backend can take any number of custom parameters for the authenticate() method. For example:
class MyBackend:
def authenticate(self, username=None, password=None, request=None):
# check username, password
if request is not None:
# log values from request object
If you are calling authenticate in your own view, you can pass the request object:
from django.contrib.auth import authenticate
def login(request):
# discover username and password
authenticate(username=username, password=password, request=request)
# continue as normal
If you're using django's login view (or the admin login), you wont have the extra information. Put simply, you'll have to use your own custom login view.
Also, be careful when automatically locking accounts: you allow someone to deliberately lock one of your user's accounts (denial of service). There are ways around this. Also, make sure your log of incorrect attempts doesn't contain any attempted passwords.
In recent versions of Django, authenticate() accepts "request" as first parameter:
optionally since Django 1.1
required since Django 2.1
See:
https://docs.djangoproject.com/en/2.1/releases/1.11/#deprecated-features-1-11
https://docs.djangoproject.com/en/2.1/releases/2.1/
I have created a list of 5 users. How do I find out which user has logged in currently? Also please mention, if there is any way to find out if the super-user has logged in?
My requirement is, I want to restrict the access of certain pages in the templates only to the superuser.
Current user is in request object:
def my_view(request):
current_user = request.user
It's django.contrib.auth.models.User class and it has some fields, e.g.
is_staff - Boolean. Designates whether this user can access the admin site;
is_superuser - Boolean. Designates that this user has all permissions without explicitly assigning them.
http://docs.djangoproject.com/en/1.1/topics/auth/#django.contrib.auth.models.User
So to test whether current user is superuser you can:
if user.is_active and user.is_superuser:
...
You can use it in template or pass this to template as variable via context.
Sounds like you should be using the built-in permissions system for this.
Check out the user_passes_test decorator for your views. Django snippets has a related decorator:
These decorators are based on
user_passes_test and
permission_required, but when a user
is logged in and fails the test, it
will render a 403 error instead of
redirecting to login - only anonymous
users will be asked to login.
http://www.djangosnippets.org/snippets/254/
I added some permissions to a user via the admin interface.
From some reason all the perm functions fail, e.g
>>> user.get_all_permissions()
set([])
But accessing the table directly, works:
>>> user.user_permissions.all()
(list of permissions as expected)
What can cause the "get_all_permissions" (and all the perm functions like has_perm()) to fail ?
Thanks
had the same problem. I am guessing that at some point you have used a self-crafted AUTHENTICATION_BACKEND? Most examples on the net of this (INCLUDING THE DJANGO 1.0 DOCUMENTATION!) don't mention that the Backends are responsible for permissions handling as well.
However, no biggie: In whatever backend file your code resides, include this import:
from django.contrib.auth.backends import ModelBackend
Then make sure the Backend you wrote extends ModelBackend, e.g.:
class EmailBackend(ModelBackend):
Should be fine.
In my case it was because of permission caching. I get the user,
added permission to user.user_permissions but user.get_all_permissions was empty set() and user.has_perm was False. This problem is only with shell not admin.
user = User.objects.get(username="User")
permission = Permission.objects.get(
codename="organizations.add_organization",
)
user.user_permissions.add(permission)
user.get_all_permissions() # set()
user.has_perm('organizations.add_organization') # False
I have to add additional line before checking permissions:
user.user_permissions.add(permission)
user = User.objects.get(username="User") # new
user.get_all_permissions()