Search code examples
djangorestriction

Restrict user access to pages


I want users to be able to see only their profile information and not have acccess to others users information. I am using a test_func to check if the user login trying to access the profile information is the owner of the information. The problem is that for some reason it always returns true, and when i go to my page an change the id on the link trying to access others users information it somehow automatically login with the user due user account and then return the information, it is, if i'm logged in as "lerton" with id 1 and i try to access the information of user "maguia" with id 2 it automatically log in as "maguia" and return me the information of "maguia"

urls.py

path('profile/<int:pk>/', ProfileView.as_view(), name='profile'),

View.py

class ProfileView(LoginRequiredMixin, DetailView, UserPassesTestMixin):
    model = get_user_model()
    template_name = 'profile.html'
    context_object_name = 'user'
    
    def test_func(self):
        user = self.get_object()
        return user == self.request.user

I tried to compare in the test_func the other properties like id, username, etc, of the users but didn't work


Solution

  • You can try the below code to check if current user and given user is same:

    from django.contrib.auth.mixins import LoginRequiredMixin
    from django.contrib.auth import get_user_model
    from django.views.generic import DetailView
    
    class ProfileView(LoginRequiredMixin, DetailView):
        model = get_user_model()
        template_name = 'profile.html'
        context_object_name = 'user'
    
        def get_object(self, queryset=None):
            # Ensure that the user can only access their own profile
            obj = super().get_object(queryset)
            if obj != self.request.user:
                # If the user is trying to access someone else's profile, raise a 404 error
                raise Http404("You are not allowed to access this page.")
            return obj
    

    Or you can try dispatch method:

    from django.contrib.auth.mixins import LoginRequiredMixin
    from django.contrib.auth import get_user_model
    from django.views.generic import DetailView
    from django.http import Http404
    
    class ProfileView(LoginRequiredMixin, DetailView):
        model = get_user_model()
        template_name = 'profile.html'
        context_object_name = 'user'
    
        def dispatch(self, request, *args, **kwargs):
            obj = self.get_object()
            if obj != self.request.user:
                raise Http404("You are not allowed to access this page.")
            return super().dispatch(request, *args, **kwargs)