Reputation: 220
I am trying to create a custom user permission. When user A block user B, when user B login and try to access user A profile through url (localhost:8000/user_a_profile/) it should show 404 Forbidden, but user B can be able to access other users. I have found out the way to do this is to create a decorator.py, i have done that and i have a problem. I have created a decorator.py, but when user A block user B, when user B login and try to access user A profile through url, the reverse is the case. User B was able to access user A profile (which is wrong) but when i try to access other users profile, i get 404 Forbidden. How do i set only user A to show 404 Forbidden when user A already blocked user B, and user B can access other users. But it seems my code is working in u-turn.
Model
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
blocked_users = models.ManyToManyField('Profile', related_name="blocked_by",blank=True)
class Blocked(models.Model):
user_is_blocking = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_is_blocking', null=True, blank=True)
user_is_blocked = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_is_blocked', null=True, blank=True)
Decorator.py
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
from pixmate.models import Profile, Post
#Blocked users can not find current user profile in url
def user_is_blocked(function):
def wrap(request, *args, **kwargs):
profile = get_object_or_404(Profile, user__username=kwargs['username'])
if Profile.objects.filter(blocked_users=profile):
return function(request, *args, **kwargs)
else:
raise PermissionDenied
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
Upvotes: 0
Views: 55
Reputation: 381
You need an decorator like
def user_is_blocked(function):
def wrap(request, *args, **kwargs):
profile = get_object_or_404(Profile, user__username=kwargs['username'])
if Blocked.objects.filter(user_is_blocking=profile.user, user_is_blocked=request.user):
raise PermissionDenied
return function(request, *, **kwargs)
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
We need to check either the requesting user is blocked by the user we are looking at the profile of (In your code you did not check for requesting user anywhere), So we need to use the Blocked object, and search on it if any object for blocked model exists which has requesting user in attribute user_is_blocked and the user we want to fetch profile of in user_is_blocking.
Upvotes: 2