1

I need an elegant way of disabling or authorizing related field traversal in Django templates.

Imagine following setup for models.py:

class Person(models.Model):
    pass

class Secret(models.Model):
    owner = models.ForeignKey(Person, related_name="secrets")

Now imagine this simple view that gives the template QuerySet of all Person instances in the system just so the template could put them in a list.

def show_people(request):
    render_to_response("people.html", {people=Person.objects.all()})

Now my problem is that I would not provide the templates myself in this imaginary system and I don't fully trust those who make the templates. The show_people view gives the people.html template the secrets of the Person instances through the related_name="secrets". This example is quite silly but in reality I have model structures where template providers could access all kind of vulnerable data through related managers.

The obvious solution would be not to give models to templates but to convert them in to some more secure data objects. But that would be pain in my case because the system is already quite big and it's up and running.

I think a cool solution to this would be somehow preventing related field traversal in templates. Another solution would be to have such custom related managers that could have access to the request object and filter the initial query set according to the request.user.

Rubinous
  • 464
  • 6
  • 12
  • People you dont trust should not have access to sensitive data. Let them designe their templates in a test environment with fake data. I know this is no direct answer on your question, but this will definetly avoid trouble in the future. – Jingo Dec 17 '12 at 19:27
  • I agree with that. However in this case, by trust, I mean that I don't know those people who make the templates. I am just providing a Django application as a third party module to external organizations but I require the organizations to make their own templates as I don't want to put any constrains to their html and I am also only interested in the logic myself. But I want to handle security in the logic (in the views) so that template providers have less responsibility and smaller risk of exposings something they shouldn't. It would be difficult to keep the question simple with a real case. – Rubinous Dec 19 '12 at 08:22

1 Answers1

1

A possible solution could be to use a custom model.Manager with your related models. Set use_for_related_fields = True to force Django to use it instead of the plain manager. modify the manager to filter the data as needed.

also have a look at this:

Django: using managers for related object access (use_for_related_fields docs)

stackoverflow: use_for_related_fields howto, very good explanation here.

Community
  • 1
  • 1
Jakob
  • 778
  • 3
  • 9
  • 25