Skip to content

Instantly share code, notes, and snippets.

@ab623
Last active May 13, 2023 01:36
Show Gist options
  • Save ab623/7d7da984e20213c33d8d5d11103c54b4 to your computer and use it in GitHub Desktop.
Save ab623/7d7da984e20213c33d8d5d11103c54b4 to your computer and use it in GitHub Desktop.
A view decorator to be used to check the model is owned by the logged in user
from django.core.exceptions import PermissionDenied
from django.apps import apps
def is_owner_permission(model=None, url_field='pk', model_field="owner"):
"""
A decorator to be used on a function based view that will check if
a model instance belongs to the logged in user
Keyword arguments:
model=None - Name of the model to check. Can be a model
class or a dotted lookup to the model via
the format 'app_name.model_name'
url_field='pk' - The url parameter to query the model
model_field="owner" - The field on the model wich is the FK back
to the user object
Usage:
@is_owner_permission(model='contract.contract', url_field="uid")
def view_contract_detail(request, uid):
if request.method == "POST":
....
OR
@is_owner_permission(model=Contract, url_field="uid")
def view_contract_detail(request, uid):
if request.method == "POST":
....
"""
def _wrapper(func):
def _check_permission(request, *args, **kwargs):
if model is None:
raise AttributeError
if type(model) is str:
_model = apps.get_model(*model.split(","))
else:
_model = model
obj = _model.objects.get(pk=kwargs[url_field])
if not (getattr(obj, model_field).id == request.user.id):
raise PermissionDenied()
return func(request, *args, **kwargs)
return _check_permission
return _wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment