Where to place global permission logic?

I have a Django project with a use extension model “UserExtension”.

class UserExtension(models.Model):
    user = OneToOneField(User, on_delete=models.CASCADE)
    ...

The relation is not mandatory. The UserExtension is referenced by other models via a ForeignKey field. A User should be able to manage model instances, where the relation points back to the user.

However, there is also a permission that can be applied to a User. This means that in the views, I cannot solely use request.user.userextension.somemodel_set.all(), but I have to add Somemodel.objects.all() after checking the users permissions.

I want to implement a global failsafe in case of missing permission checks in code. Basically, a User should always have a relation, unless it is a superuser, or a user with a specific permission. So every view should throw an Internal Server Error when request.user.is_superuser == False and request.user.has_perm("myperm.ca_manage_all") == False. This check must be on a global level, so adding this check to views via checks or decorators defeats the reason I want to implement that.

I could maybe do that with a middleware, but before I dive into it, I wanted to ask for a possibly better approach.

Middleware is your best place to handle this. It is your “common connection point” for all requests coming in.

1 Like