From 7ad2654b00bd6c412ce3d1135b3372136e9ffb44 Mon Sep 17 00:00:00 2001 From: keannu125 Date: Sat, 20 May 2023 08:20:20 +0800 Subject: [PATCH] Added permissions to views --- .vscode/settings.json | 6 ++++++ project/config/settings.py | 1 + project/notes/views.py | 3 ++- project/permissions/__init__.py | 0 project/permissions/permissions.py | 9 +++++++++ 5 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 .vscode/settings.json create mode 100644 project/permissions/__init__.py create mode 100644 project/permissions/permissions.py diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..65293fd --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "[python]": { + "editor.defaultFormatter": "ms-python.autopep8" + }, + "python.formatting.provider": "none" +} \ No newline at end of file diff --git a/project/config/settings.py b/project/config/settings.py index 7dc7cb5..0e996e1 100644 --- a/project/config/settings.py +++ b/project/config/settings.py @@ -47,6 +47,7 @@ INSTALLED_APPS = [ 'corsheaders', 'djoser', 'accounts', + 'permissions', ] MIDDLEWARE = [ diff --git a/project/notes/views.py b/project/notes/views.py index 9dbb0f3..a6f2752 100644 --- a/project/notes/views.py +++ b/project/notes/views.py @@ -2,10 +2,11 @@ from rest_framework.permissions import IsAuthenticated from rest_framework import viewsets, generics from .serializers import NoteSerializer from .models import Note +from permissions.permissions import IsOwner class NoteViewSet(viewsets.ModelViewSet): - permission_classes = [IsAuthenticated] + permission_classes = [IsOwner] serializer_class = NoteSerializer queryset = Note.objects.all() diff --git a/project/permissions/__init__.py b/project/permissions/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/project/permissions/permissions.py b/project/permissions/permissions.py new file mode 100644 index 0000000..ef6cae5 --- /dev/null +++ b/project/permissions/permissions.py @@ -0,0 +1,9 @@ +from rest_framework.permissions import BasePermission + +class IsOwner(BasePermission): + """ + Custom permission to only allow the creator of an object to view and manipulate it. + """ + def has_object_permission(self, request, view, obj): + # Only allow the creator of the object to view and manipulate it. + return obj.creator == request.user \ No newline at end of file