Skip to content

Commit 65d2e30

Browse files
committed
feat(drf): handle scopes for different methods
1 parent cb91a46 commit 65d2e30

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "cardo-python-utils"
7-
version = "0.5.dev14"
7+
version = "0.5.dev15"
88
description = "Python library enhanced with a wide range of functions for different scenarios."
99
readme = "README.rst"
1010
requires-python = ">=3.8"

python_utils/django/keycloak/api/drf.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,18 +42,32 @@ class MyApiView(APIView):
4242
allowed_scopes = ["jobs"]
4343
...
4444
45+
It is possible to define different scopes per HTTP method
46+
by setting `allowed_scopes` as a dict:
47+
48+
class MyApiView(APIView):
49+
permission_classes = [IsAuthenticated, HasScope]
50+
allowed_scopes = {
51+
"get": ["jobs"],
52+
"post": ["jobs_admin"],
53+
}
54+
...
55+
4556
If no particular scope is required, you can set `allowed_scopes = "*"`
4657
to allow access without scope checks.
4758
"""
4859

4960
def has_permission(self, request, view):
50-
allowed_scopes = getattr(view, "allowed_scopes", [])
61+
allowed_scopes = getattr(view, "allowed_scopes", None)
5162

5263
if not allowed_scopes:
5364
raise Exception(
5465
f"No allowed_scopes defined on the view '{view.__class__.__name__}'. "
5566
"Define allowed_scopes or set it to '*' to allow any scope."
5667
)
68+
69+
if isinstance(allowed_scopes, dict):
70+
allowed_scopes = allowed_scopes.get(request.method.lower(), [])
5771

5872
if allowed_scopes == "*":
5973
return True

0 commit comments

Comments
 (0)