How to restrict unauthorized user to have access to different pages in django

1.1k Views Asked by At

I have this model:

class Student(Model):
    user = OneToOneField(CustomUser, on_delete=CASCADE, related_name='student', )

and this url:

path('students/<int:student_pk>/', student, name='student')

and this view:

@login_required
def student(request, student_pk):
    return HttpResponse('This is your personal panel')

Well, by using login_required decoration I am restricting users that are not logged in to see student panel page. However, other students who are logged in can see other's panels.

How can I restrict them from this?

I can do this:

@login_required
def student(request, student_pk):
    student_ins = get_object_or_404(Student, pk=student_pk)
    if student_ins == request.user.student:
        return HttpResponse('This is your personal panel')
    else:
        return HttpResponse('Please do not try to see other students' panels! You are not authorized to do this')

However, I prefer to do it in decorator. For example log out the logged in student with primary key pk=1 if he/she entered this in the url: www.example.com/students/2

1

There are 1 best solutions below

3
Pedram Parsian On BEST ANSWER

Try this:

from django.contrib.auth import logout

def check_profile(function):
  @wraps(function)
  def wrap(request, *args, **kwargs):
      user = request.user
      student_ins = get_object_or_404(Student, pk=kwargs.get(student_pk))
      if not student_ins == user:
          logout(request)
          return HttpResponse('Please do not try to see other students' panels! You are not authorized to do this')
  return wrap

and use that like:

@check_profile
@login_required
def student(request, student_pk):
    #...

This should do what you want, but keep in mind that it's not generally a good idea, unless you have a very special use-case. Basically, what you should do is to have a url like /profile/ and show the user profile based on the request.user; This is much more cleaner way.