Does the permission check the group or individual permissions?
so I have been having a small confusion regarding permissions. All my tables are made in the app called app
. And each admin user is assigned to a specific group, which is shown below.
Similarly for every page, depending on the user's permission they would be able to access different pages. And for every view, there is a custom decorator as shown.
Which has the code written in a separate decorators.py
file.
def permissions_allowed(allowed=[]):
def decorator(view_func):
def wrapper_func(request, *args, **kwargs):
if not request.user.is_staff:
messages.warning(request, "403 FORBIDDEN: You are not authorized to view the admin page!")
return redirect('home')
for perm in allowed:
if not request.user.has_perm(perm):
messages.warning(request, "You don't have the permissions to complete this action. Please contact the admin!")
return redirect ('adminHome')
return view_func (request, *args, **kwargs)
return wrapper_func
return decorator
So my questions:
- Is my syntax to check the permission correct? (as shown in the 2nd pic)
- When I use
request.user.has_perm()
does it check the group permissions? the individual permissions? or both of them?
Please let me know what I am doing wrong since the code isn't running the way I want it to.
Thanks!
According to the documentation has_perm()
method checks permission at user's level:
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. For an active superuser, this method will always return True.
Thus, if you want to check permission at group level, you might use get_group_permissions()
:
Returns a set of permission strings that the user has, through their groups.
If you want both, you can also consider using get_all_permissions()
.
In your case, you already check the standard attribute user.is_staff
, so if you stored the group id to consider, checking groups permission will maybe make more sense (there is no standard method, just a common use of a M2M relation between Group
and Permission
models)