I’m trying to secure an application so that users can only see objects which are assigned to them. I’ve got a custom QuerySet which works for this, but I’m trying to find a way to force the use of this additional functionality. Here is my Model:
class Inquiry(models.Model):
ts = models.DateTimeField(auto_now_add=True)
assigned_to_user = models.ForeignKey(User,
blank=True,
null=True,
related_name="assigned_inquiries")
objects = CustomQuerySetManager()
class QuerySet(QuerySet):
def for_user(self, user):
return self.filter(assigned_to_user=user)
(The CustomQuerySetManager is documented over here, if it is important.)
I’m trying to force everything to use this filtering, so that other methods will raise an exception. For example:
Inquiry.objects.all() ## Should raise an exception.
Inquiry.objects.filter(pk=69) ## Should raise an exception.
Inquiry.objects.for_user(request.user).filter(pk=69) ## Should work.
inqs = Inquiry.objects.for_user(request.user) ## Should work.
inqs.filter(pk=69) ## Should work.
It seems to me that there should be a way to force the security of these objects by allowing only certain users to access them.
I am not concerned with how this might impact the admin interface.
I’m assuming the reason you’re doing this is because you want to make sure that you or another developer never forget to filter X model by the user.
I think the proper way to solve this isn’t necessarily to make it throw an exception but to make user of Django’s testing framework and to write tests to make sure that views/whatever don’t return other user’s data.