billyJoe
billyJoe

Reputation: 2064

Limit url acces with Django

i've an application to manage cars. each user can add a car and access it, everything is fine but i've a question. suppose that bob has the car 1 and 3 through mysite.com/cars/1 and mysite.com/cars/3 marc has the car 2 through mysite.com/cars/2

The problem is bob can read car information with through mysite.com/cars/2 but it's not his, idem with marc and through mysite.com/cars/1 and through mysite.com/cars/3.

How can i restrict access ? via middleware ?

This question can be extended with pieces. A car is composed of pieces. So for example, bob's car contains mysite.com/pieces/1, mysite.com/pieces/2, mysite.com/ and mysite.com/pieces/3, Marc's car mysite.com/pieces/4 Bob cannot access to mysite.com/pieces/4, marc cannot access to mysite.com/pieces/1 mysite.com/pieces/2 and mysite.com/pieces/3.

Upvotes: 2

Views: 829

Answers (1)

Paulo Bu
Paulo Bu

Reputation: 29804

I'm just guessing about your model and views here but this is a simple way to get you started:

views.py

from django.core.exceptions import PermissionDenied
def cars(request, car_id):
    ...
    if request.user != car.owner:
        raise PermissionDenied
    ...

UPDATE: Added the import directive

UPDATE 2: Added some middleware code still guessing about your views and models.

With middleware the approach should be like this:

my_app/middleware.py

# custom middleware

class CustomMiddleware(object):

    def process_view(self, request, view_func, view_args, view_kwargs):
        # get the car param passed to the view (not sure if it is with kwargs or args
        car_id = view_kwargs['car_id']
        car = # retrieve car from the db
        if request.user != car.owner:
            raise PermissionDenied

You import this in your settings.py adding the full python namespace.

You could take a look at the docs about middleware and their hooks which is at my point of view extremely simple and well documented.

Hope this helps!

Upvotes: 3

Related Questions