commonground-api-common 1.13.0__py3-none-any.whl → 2.4.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- commonground_api_common-1.13.0.data/scripts/patch_content_types → commonground_api_common-2.4.1.data/scripts/generate_schema +2 -4
- {commonground_api_common-1.13.0.dist-info → commonground_api_common-2.4.1.dist-info}/METADATA +45 -37
- {commonground_api_common-1.13.0.dist-info → commonground_api_common-2.4.1.dist-info}/RECORD +45 -50
- {commonground_api_common-1.13.0.dist-info → commonground_api_common-2.4.1.dist-info}/WHEEL +1 -1
- vng_api_common/__init__.py +1 -1
- vng_api_common/admin.py +1 -20
- vng_api_common/api/views.py +1 -0
- vng_api_common/apps.py +44 -26
- vng_api_common/audittrails/utils.py +44 -0
- vng_api_common/authorizations/admin.py +1 -1
- vng_api_common/authorizations/middleware.py +244 -0
- vng_api_common/authorizations/migrations/0016_remove_authorizationsconfig_api_root_and_more.py +76 -0
- vng_api_common/authorizations/models.py +62 -3
- vng_api_common/authorizations/utils.py +17 -0
- vng_api_common/client.py +61 -29
- vng_api_common/conf/api.py +33 -48
- vng_api_common/contrib/setup_configuration/models.py +32 -0
- vng_api_common/contrib/setup_configuration/steps.py +46 -0
- vng_api_common/extensions/file.py +26 -0
- vng_api_common/extensions/gegevensgroep.py +16 -0
- vng_api_common/extensions/geojson.py +270 -0
- vng_api_common/extensions/hyperlink.py +37 -0
- vng_api_common/extensions/polymorphic.py +68 -0
- vng_api_common/extensions/query.py +20 -0
- vng_api_common/filters.py +0 -1
- vng_api_common/generators.py +12 -113
- vng_api_common/middleware.py +1 -227
- vng_api_common/migrations/0006_delete_apicredential.py +120 -0
- vng_api_common/mocks.py +4 -1
- vng_api_common/models.py +10 -111
- vng_api_common/notifications/api/views.py +8 -8
- vng_api_common/notifications/handlers.py +8 -3
- vng_api_common/notifications/migrations/0011_remove_subscription_config_and_more.py +23 -0
- vng_api_common/oas.py +6 -10
- vng_api_common/pagination.py +10 -0
- vng_api_common/routers.py +3 -3
- vng_api_common/schema.py +414 -158
- vng_api_common/tests/schema.py +13 -0
- vng_api_common/utils.py +0 -22
- vng_api_common/validators.py +92 -73
- vng_api_common/views.py +35 -20
- commonground_api_common-1.13.0.data/scripts/generate_schema +0 -39
- commonground_api_common-1.13.0.data/scripts/use_external_components +0 -16
- vng_api_common/inspectors/cache.py +0 -57
- vng_api_common/inspectors/fields.py +0 -126
- vng_api_common/inspectors/files.py +0 -121
- vng_api_common/inspectors/geojson.py +0 -360
- vng_api_common/inspectors/polymorphic.py +0 -72
- vng_api_common/inspectors/query.py +0 -91
- vng_api_common/inspectors/utils.py +0 -40
- vng_api_common/inspectors/view.py +0 -547
- vng_api_common/management/commands/generate_autorisaties.py +0 -43
- vng_api_common/management/commands/generate_notificaties.py +0 -40
- vng_api_common/management/commands/generate_swagger.py +0 -197
- vng_api_common/management/commands/patch_error_contenttypes.py +0 -61
- vng_api_common/management/commands/use_external_components.py +0 -94
- vng_api_common/notifications/constants.py +0 -3
- vng_api_common/notifications/models.py +0 -97
- vng_api_common/templates/vng_api_common/api_schema_to_markdown_table.md +0 -16
- vng_api_common/templates/vng_api_common/autorisaties.md +0 -15
- vng_api_common/templates/vng_api_common/notificaties.md +0 -24
- {commonground_api_common-1.13.0.dist-info → commonground_api_common-2.4.1.dist-info}/top_level.txt +0 -0
- /vng_api_common/{inspectors → contrib}/__init__.py +0 -0
- /vng_api_common/{management → contrib/setup_configuration}/__init__.py +0 -0
- /vng_api_common/{management/commands → extensions}/__init__.py +0 -0
vng_api_common/middleware.py
CHANGED
@@ -1,242 +1,16 @@
|
|
1
1
|
# https://pyjwt.readthedocs.io/en/latest/usage.html#reading-headers-without-validation
|
2
2
|
# -> we can put the organization/service in the headers itself
|
3
3
|
import logging
|
4
|
-
from typing import Any, Dict, Iterable, List, Optional
|
5
4
|
|
6
5
|
from django.conf import settings
|
7
|
-
from django.db import models, transaction
|
8
|
-
from django.db.models import QuerySet
|
9
|
-
from django.utils.translation import gettext as _
|
10
6
|
|
11
|
-
import jwt
|
12
|
-
from djangorestframework_camel_case.util import underscoreize
|
13
|
-
from rest_framework.exceptions import PermissionDenied
|
14
7
|
from rest_framework.response import Response
|
15
|
-
from zds_client.client import ClientError
|
16
8
|
|
17
|
-
from .
|
18
|
-
from .authorizations.serializers import ApplicatieUuidSerializer
|
19
|
-
from .constants import VERSION_HEADER, VertrouwelijkheidsAanduiding
|
20
|
-
from .models import JWTSecret
|
21
|
-
from .utils import get_uuid_from_path
|
9
|
+
from .constants import VERSION_HEADER
|
22
10
|
|
23
11
|
logger = logging.getLogger(__name__)
|
24
12
|
|
25
13
|
|
26
|
-
class JWTAuth:
|
27
|
-
def __init__(self, encoded: str = None):
|
28
|
-
self.encoded = encoded
|
29
|
-
|
30
|
-
@property
|
31
|
-
def applicaties(self) -> Iterable[Applicatie]:
|
32
|
-
if self.client_id is None:
|
33
|
-
return []
|
34
|
-
|
35
|
-
applicaties = self._get_auth()
|
36
|
-
|
37
|
-
if not applicaties:
|
38
|
-
auth_data = self._request_auth()
|
39
|
-
applicaties = self._save_auth(auth_data)
|
40
|
-
|
41
|
-
return applicaties
|
42
|
-
|
43
|
-
@property
|
44
|
-
def autorisaties(self) -> models.QuerySet:
|
45
|
-
"""
|
46
|
-
Retrieve all authorizations relevant to this component.
|
47
|
-
"""
|
48
|
-
app_ids = [app.id for app in self.applicaties]
|
49
|
-
config = AuthorizationsConfig.get_solo()
|
50
|
-
return Autorisatie.objects.filter(
|
51
|
-
applicatie_id__in=app_ids, component=config.component
|
52
|
-
)
|
53
|
-
|
54
|
-
def _request_auth(self) -> list:
|
55
|
-
client = AuthorizationsConfig.get_client()
|
56
|
-
try:
|
57
|
-
response = client.list(
|
58
|
-
"applicatie", query_params={"clientIds": self.client_id}
|
59
|
-
)
|
60
|
-
except ClientError as exc:
|
61
|
-
response = exc.args[0]
|
62
|
-
# friendly debug - hint at where the problem is located
|
63
|
-
if response["status"] == 403 and response["code"] == "not_authenticated":
|
64
|
-
detail = _(
|
65
|
-
"Component could not authenticate against the AC - "
|
66
|
-
"authorizations could not be retrieved"
|
67
|
-
)
|
68
|
-
raise PermissionDenied(detail=detail, code="not_authenticated_for_ac")
|
69
|
-
logger.warn("Authorization component can't be accessed")
|
70
|
-
return []
|
71
|
-
|
72
|
-
return underscoreize(response["results"])
|
73
|
-
|
74
|
-
def _get_auth(self):
|
75
|
-
return Applicatie.objects.filter(client_ids__contains=[self.client_id])
|
76
|
-
|
77
|
-
@transaction.atomic
|
78
|
-
def _save_auth(self, auth_data):
|
79
|
-
applicaties = []
|
80
|
-
|
81
|
-
for applicatie_data in auth_data:
|
82
|
-
applicatie_serializer = ApplicatieUuidSerializer(data=applicatie_data)
|
83
|
-
uuid = get_uuid_from_path(applicatie_data["url"])
|
84
|
-
applicatie_data["uuid"] = uuid
|
85
|
-
applicatie_serializer.is_valid()
|
86
|
-
applicaties.append(applicatie_serializer.save())
|
87
|
-
|
88
|
-
return applicaties
|
89
|
-
|
90
|
-
@property
|
91
|
-
def payload(self) -> Optional[Dict[str, Any]]:
|
92
|
-
if self.encoded is None:
|
93
|
-
return None
|
94
|
-
|
95
|
-
if not hasattr(self, "_payload"):
|
96
|
-
# decode the JWT and validate it
|
97
|
-
|
98
|
-
# jwt check
|
99
|
-
try:
|
100
|
-
payload = jwt.decode(
|
101
|
-
self.encoded,
|
102
|
-
algorithms=["HS256"],
|
103
|
-
options={"verify_signature": False},
|
104
|
-
leeway=settings.JWT_LEEWAY,
|
105
|
-
)
|
106
|
-
except jwt.DecodeError:
|
107
|
-
logger.info("Invalid JWT encountered")
|
108
|
-
raise PermissionDenied(
|
109
|
-
_(
|
110
|
-
"JWT could not be decoded. Possibly you made a copy-paste mistake."
|
111
|
-
),
|
112
|
-
code="jwt-decode-error",
|
113
|
-
)
|
114
|
-
|
115
|
-
# get client_id
|
116
|
-
try:
|
117
|
-
client_id = payload["client_id"]
|
118
|
-
except KeyError:
|
119
|
-
raise PermissionDenied(
|
120
|
-
"Client identifier is niet aanwezig in JWT",
|
121
|
-
code="missing-client-identifier",
|
122
|
-
)
|
123
|
-
|
124
|
-
# find client_id in DB and retrieve its secret
|
125
|
-
try:
|
126
|
-
jwt_secret = JWTSecret.objects.exclude(secret="").get(
|
127
|
-
identifier=client_id
|
128
|
-
)
|
129
|
-
except JWTSecret.DoesNotExist:
|
130
|
-
raise PermissionDenied(
|
131
|
-
"Client identifier bestaat niet", code="invalid-client-identifier"
|
132
|
-
)
|
133
|
-
else:
|
134
|
-
key = jwt_secret.secret
|
135
|
-
|
136
|
-
# check signature of the token
|
137
|
-
try:
|
138
|
-
payload = jwt.decode(
|
139
|
-
self.encoded,
|
140
|
-
key,
|
141
|
-
algorithms=["HS256"],
|
142
|
-
leeway=settings.JWT_LEEWAY,
|
143
|
-
)
|
144
|
-
except jwt.InvalidSignatureError:
|
145
|
-
logger.exception("Invalid signature - possible payload tampering?")
|
146
|
-
raise PermissionDenied(
|
147
|
-
"Client credentials zijn niet geldig", code="invalid-jwt-signature"
|
148
|
-
)
|
149
|
-
|
150
|
-
self._payload = payload
|
151
|
-
|
152
|
-
return self._payload
|
153
|
-
|
154
|
-
@property
|
155
|
-
def client_id(self) -> str:
|
156
|
-
if not self.payload:
|
157
|
-
return None
|
158
|
-
return self.payload["client_id"]
|
159
|
-
|
160
|
-
def filter_vertrouwelijkheidaanduiding(self, base: QuerySet, value) -> QuerySet:
|
161
|
-
if value is None:
|
162
|
-
return base
|
163
|
-
|
164
|
-
order_provided = VertrouwelijkheidsAanduiding.get_choice_order(value)
|
165
|
-
order_case = VertrouwelijkheidsAanduiding.get_order_expression(
|
166
|
-
"max_vertrouwelijkheidaanduiding"
|
167
|
-
)
|
168
|
-
|
169
|
-
# In this case we are filtering Autorisatie model to look for auth which meets our needs.
|
170
|
-
# Therefore we're only considering authorizations here that have a max_vertrouwelijkheidaanduiding
|
171
|
-
# bigger or equal than what we're checking for the object.
|
172
|
-
# In cases when we are filtering data objects (Zaak, InformatieObject etc) it's the other way around
|
173
|
-
|
174
|
-
return base.annotate(max_vertr=order_case).filter(max_vertr__gte=order_provided)
|
175
|
-
|
176
|
-
def filter_default(self, base: QuerySet, name, value) -> QuerySet:
|
177
|
-
if value is None:
|
178
|
-
return base
|
179
|
-
|
180
|
-
return base.filter(**{name: value})
|
181
|
-
|
182
|
-
def has_auth(
|
183
|
-
self, scopes: List[str], component: Optional[str] = None, **fields
|
184
|
-
) -> bool:
|
185
|
-
if scopes is None:
|
186
|
-
return False
|
187
|
-
|
188
|
-
scopes_provided = set()
|
189
|
-
config = AuthorizationsConfig.get_solo()
|
190
|
-
if component is None:
|
191
|
-
component = config.component
|
192
|
-
|
193
|
-
for applicatie in self.applicaties:
|
194
|
-
# allow everything
|
195
|
-
if applicatie.heeft_alle_autorisaties is True:
|
196
|
-
return True
|
197
|
-
|
198
|
-
autorisaties = applicatie.autorisaties.filter(component=component)
|
199
|
-
|
200
|
-
# filter on all additional components
|
201
|
-
for field_name, field_value in fields.items():
|
202
|
-
if hasattr(self, f"filter_{field_name}"):
|
203
|
-
autorisaties = getattr(self, f"filter_{field_name}")(
|
204
|
-
autorisaties, field_value
|
205
|
-
)
|
206
|
-
else:
|
207
|
-
autorisaties = self.filter_default(
|
208
|
-
autorisaties, field_name, field_value
|
209
|
-
)
|
210
|
-
|
211
|
-
for autorisatie in autorisaties:
|
212
|
-
scopes_provided.update(autorisatie.scopes)
|
213
|
-
|
214
|
-
return scopes.is_contained_in(list(scopes_provided))
|
215
|
-
|
216
|
-
|
217
|
-
class AuthMiddleware:
|
218
|
-
header = "HTTP_AUTHORIZATION"
|
219
|
-
auth_type = "Bearer"
|
220
|
-
|
221
|
-
def __init__(self, get_response=None):
|
222
|
-
self.get_response = get_response
|
223
|
-
|
224
|
-
def __call__(self, request):
|
225
|
-
self.extract_jwt_payload(request)
|
226
|
-
return self.get_response(request) if self.get_response else None
|
227
|
-
|
228
|
-
def extract_jwt_payload(self, request):
|
229
|
-
authorization = request.META.get(self.header, "")
|
230
|
-
prefix = f"{self.auth_type} "
|
231
|
-
if authorization.startswith(prefix):
|
232
|
-
# grab the actual token
|
233
|
-
encoded = authorization[len(prefix) :]
|
234
|
-
else:
|
235
|
-
encoded = None
|
236
|
-
|
237
|
-
request.jwt_auth = JWTAuth(encoded)
|
238
|
-
|
239
|
-
|
240
14
|
class APIVersionHeaderMiddleware:
|
241
15
|
"""
|
242
16
|
Include a header specifying the API-version
|
@@ -0,0 +1,120 @@
|
|
1
|
+
# Generated by Django 5.1.2 on 2024-10-24 13:51
|
2
|
+
|
3
|
+
import logging
|
4
|
+
from typing import Set
|
5
|
+
|
6
|
+
from django.db import migrations, models
|
7
|
+
from django.utils.text import slugify
|
8
|
+
|
9
|
+
from zgw_consumers.constants import APITypes, AuthTypes
|
10
|
+
|
11
|
+
logger = logging.getLogger(__name__)
|
12
|
+
|
13
|
+
|
14
|
+
def _get_api_type(api_root: str) -> APITypes:
|
15
|
+
mapping = {
|
16
|
+
"/autorisaties/api/": APITypes.ac,
|
17
|
+
"/zaken/api/": APITypes.zrc,
|
18
|
+
"/catalogi/api/": APITypes.ztc,
|
19
|
+
"/documenten/api/": APITypes.drc,
|
20
|
+
"/besluiten/api/": APITypes.drc,
|
21
|
+
}
|
22
|
+
|
23
|
+
for path, _type in mapping.items():
|
24
|
+
if path in api_root.lower():
|
25
|
+
return _type
|
26
|
+
|
27
|
+
return APITypes.orc
|
28
|
+
|
29
|
+
|
30
|
+
def _get_service_slug(credential: models.Model, existing_slugs: Set[str]) -> str:
|
31
|
+
default_slug: str = slugify(credential.label)
|
32
|
+
|
33
|
+
if default_slug not in existing_slugs or not existing_slugs:
|
34
|
+
return default_slug
|
35
|
+
|
36
|
+
count = 2
|
37
|
+
slug = f"{default_slug}-{count}"
|
38
|
+
|
39
|
+
while slug in existing_slugs:
|
40
|
+
count += 1
|
41
|
+
slug = f"{default_slug}-{count}"
|
42
|
+
|
43
|
+
return slug
|
44
|
+
|
45
|
+
|
46
|
+
def migrate_credentials_to_service(apps, _) -> None:
|
47
|
+
APICredential = apps.get_model("vng_api_common", "APICredential")
|
48
|
+
Service = apps.get_model("zgw_consumers", "Service")
|
49
|
+
|
50
|
+
credentials = APICredential.objects.all()
|
51
|
+
|
52
|
+
existings_service_slugs = set(Service.objects.values_list("slug", flat=True))
|
53
|
+
|
54
|
+
for credential in credentials:
|
55
|
+
logger.info(f"Creating Service for {credential.client_id}")
|
56
|
+
|
57
|
+
service_slug = _get_service_slug(credential, existings_service_slugs)
|
58
|
+
|
59
|
+
_, created = Service.objects.get_or_create(
|
60
|
+
api_root=credential.api_root,
|
61
|
+
defaults=dict(
|
62
|
+
label=credential.label,
|
63
|
+
slug=service_slug,
|
64
|
+
api_type=_get_api_type(credential.api_root),
|
65
|
+
auth_type=AuthTypes.zgw,
|
66
|
+
client_id=credential.client_id,
|
67
|
+
secret=credential.secret,
|
68
|
+
user_id=credential.user_id,
|
69
|
+
user_representation=credential.user_representation,
|
70
|
+
),
|
71
|
+
)
|
72
|
+
|
73
|
+
existings_service_slugs.add(service_slug)
|
74
|
+
|
75
|
+
if created:
|
76
|
+
logger.info(f"Created new Service for {credential.api_root}")
|
77
|
+
else:
|
78
|
+
logger.info(f"Existing service found for {credential.api_root}")
|
79
|
+
|
80
|
+
|
81
|
+
def migrate_service_to_credentials(apps, _) -> None:
|
82
|
+
APICredential = apps.get_model("vng_api_common", "APICredential")
|
83
|
+
Service = apps.get_model("zgw_consumers", "Service")
|
84
|
+
|
85
|
+
services = Service.objects.filter(auth_type=AuthTypes.zgw)
|
86
|
+
|
87
|
+
for service in services:
|
88
|
+
logger.info(f"Creating APICredentials for {service.client_id}")
|
89
|
+
|
90
|
+
_, created = APICredential.objects.get_or_create(
|
91
|
+
api_root=service.api_root,
|
92
|
+
defaults=dict(
|
93
|
+
label=f"Migrated credentials for {service.client_id}",
|
94
|
+
client_id=service.client_id,
|
95
|
+
secret=service.secret,
|
96
|
+
user_id=service.user_id,
|
97
|
+
user_representation=service.user_representation,
|
98
|
+
),
|
99
|
+
)
|
100
|
+
if created:
|
101
|
+
logger.info(f"Created new APICredentials for {service.api_root}")
|
102
|
+
else:
|
103
|
+
logger.info(f"Existing APICredentials found for {service.api_root}")
|
104
|
+
|
105
|
+
|
106
|
+
class Migration(migrations.Migration):
|
107
|
+
|
108
|
+
dependencies = [
|
109
|
+
("vng_api_common", "0005_auto_20190614_1346"),
|
110
|
+
("zgw_consumers", "0022_set_default_service_slug"),
|
111
|
+
]
|
112
|
+
|
113
|
+
operations = [
|
114
|
+
migrations.RunPython(
|
115
|
+
migrate_credentials_to_service, reverse_code=migrate_service_to_credentials
|
116
|
+
),
|
117
|
+
migrations.DeleteModel(
|
118
|
+
name="APICredential",
|
119
|
+
),
|
120
|
+
]
|
vng_api_common/mocks.py
CHANGED
vng_api_common/models.py
CHANGED
@@ -1,15 +1,7 @@
|
|
1
|
-
from typing import Optional, Union
|
2
|
-
from urllib.parse import urlsplit, urlunsplit
|
3
|
-
|
4
1
|
from django.db import models
|
5
|
-
from django.db.models.functions import Length
|
6
2
|
from django.utils.translation import gettext_lazy as _
|
7
3
|
|
8
4
|
from rest_framework.reverse import reverse
|
9
|
-
from solo.models import SingletonModel
|
10
|
-
from zds_client import Client, ClientAuth
|
11
|
-
|
12
|
-
from .client import get_client as _get_client
|
13
5
|
|
14
6
|
|
15
7
|
class APIMixin:
|
@@ -34,6 +26,11 @@ class APIMixin:
|
|
34
26
|
return url
|
35
27
|
|
36
28
|
|
29
|
+
class JWTSecretManager(models.Manager):
|
30
|
+
def get_by_natural_key(self, identifier):
|
31
|
+
return self.get(identifier=identifier)
|
32
|
+
|
33
|
+
|
37
34
|
class JWTSecret(models.Model):
|
38
35
|
"""
|
39
36
|
Store credentials of clients that want to access our API.
|
@@ -53,112 +50,14 @@ class JWTSecret(models.Model):
|
|
53
50
|
_("secret"), max_length=255, help_text=_("Secret belonging to the client ID.")
|
54
51
|
)
|
55
52
|
|
53
|
+
objects = JWTSecretManager()
|
54
|
+
|
55
|
+
def natural_key(self):
|
56
|
+
return (self.identifier,)
|
57
|
+
|
56
58
|
class Meta:
|
57
59
|
verbose_name = _("client credential")
|
58
60
|
verbose_name_plural = _("client credentials")
|
59
61
|
|
60
62
|
def __str__(self):
|
61
63
|
return self.identifier
|
62
|
-
|
63
|
-
|
64
|
-
class APICredential(models.Model):
|
65
|
-
"""
|
66
|
-
Store credentials for external APIs.
|
67
|
-
|
68
|
-
When we need to authenticate against a remote API, we need to know which
|
69
|
-
client ID and secret to use to sign the JWT.
|
70
|
-
"""
|
71
|
-
|
72
|
-
api_root = models.URLField(
|
73
|
-
_("API-root"),
|
74
|
-
unique=True,
|
75
|
-
help_text=_(
|
76
|
-
"URL of the external API, ending in a trailing slash. Example: https://example.com/api/v1/"
|
77
|
-
),
|
78
|
-
)
|
79
|
-
label = models.CharField(
|
80
|
-
_("label"),
|
81
|
-
max_length=100,
|
82
|
-
default="",
|
83
|
-
help_text=_("Human readable label of the external API."),
|
84
|
-
)
|
85
|
-
client_id = models.CharField(
|
86
|
-
_("client ID"),
|
87
|
-
max_length=255,
|
88
|
-
help_text=_("Client ID to identify this API at the external API."),
|
89
|
-
)
|
90
|
-
secret = models.CharField(
|
91
|
-
_("secret"), max_length=255, help_text=_("Secret belonging to the client ID.")
|
92
|
-
)
|
93
|
-
user_id = models.CharField(
|
94
|
-
_("user ID"),
|
95
|
-
max_length=255,
|
96
|
-
help_text=_(
|
97
|
-
"User ID to use for the audit trail. Although these external API credentials are typically used by"
|
98
|
-
"this API itself instead of a user, the user ID is required."
|
99
|
-
),
|
100
|
-
)
|
101
|
-
user_representation = models.CharField(
|
102
|
-
_("user representation"),
|
103
|
-
max_length=255,
|
104
|
-
default="",
|
105
|
-
help_text=_("Human readable representation of the user."),
|
106
|
-
)
|
107
|
-
|
108
|
-
class Meta:
|
109
|
-
verbose_name = _("external API credential")
|
110
|
-
verbose_name_plural = _("external API credentials")
|
111
|
-
|
112
|
-
def __str__(self):
|
113
|
-
return self.api_root
|
114
|
-
|
115
|
-
@classmethod
|
116
|
-
def get_auth(cls, url: str, **kwargs) -> Union[ClientAuth, None]:
|
117
|
-
split_url = urlsplit(url)
|
118
|
-
scheme_and_domain = urlunsplit(split_url[:2] + ("", "", ""))
|
119
|
-
|
120
|
-
candidates = (
|
121
|
-
cls.objects.filter(api_root__startswith=scheme_and_domain)
|
122
|
-
.annotate(api_root_length=Length("api_root"))
|
123
|
-
.order_by("-api_root_length")
|
124
|
-
)
|
125
|
-
|
126
|
-
# select the one matching
|
127
|
-
for candidate in candidates.iterator():
|
128
|
-
if url.startswith(candidate.api_root):
|
129
|
-
credentials = candidate
|
130
|
-
break
|
131
|
-
else:
|
132
|
-
return None
|
133
|
-
|
134
|
-
auth = ClientAuth(
|
135
|
-
client_id=credentials.client_id,
|
136
|
-
secret=credentials.secret,
|
137
|
-
user_id=credentials.user_id,
|
138
|
-
user_representation=credentials.user_representation,
|
139
|
-
**kwargs,
|
140
|
-
)
|
141
|
-
return auth
|
142
|
-
|
143
|
-
|
144
|
-
class ClientConfig(SingletonModel):
|
145
|
-
api_root = models.URLField(_("api root"), unique=True)
|
146
|
-
|
147
|
-
class Meta:
|
148
|
-
abstract = True
|
149
|
-
|
150
|
-
def __str__(self):
|
151
|
-
return self.api_root
|
152
|
-
|
153
|
-
def save(self, *args, **kwargs):
|
154
|
-
if not self.api_root.endswith("/"):
|
155
|
-
self.api_root = f"{self.api_root}/"
|
156
|
-
super().save(*args, **kwargs)
|
157
|
-
|
158
|
-
@classmethod
|
159
|
-
def get_client(cls) -> Optional[Client]:
|
160
|
-
"""
|
161
|
-
Construct a client, prepared with the required auth.
|
162
|
-
"""
|
163
|
-
config = cls.get_solo()
|
164
|
-
return _get_client(config.api_root, url_is_api_root=True)
|
@@ -1,8 +1,9 @@
|
|
1
1
|
from django.conf import settings
|
2
2
|
from django.utils.module_loading import import_string
|
3
3
|
|
4
|
-
from
|
4
|
+
from drf_spectacular.utils import extend_schema
|
5
5
|
from notifications_api_common.api.serializers import NotificatieSerializer
|
6
|
+
from notifications_api_common.constants import SCOPE_NOTIFICATIES_PUBLICEREN_LABEL
|
6
7
|
from rest_framework import status
|
7
8
|
from rest_framework.response import Response
|
8
9
|
from rest_framework.views import APIView
|
@@ -10,7 +11,6 @@ from rest_framework.views import APIView
|
|
10
11
|
from ...permissions import AuthScopesRequired
|
11
12
|
from ...scopes import Scope
|
12
13
|
from ...serializers import FoutSerializer, ValidatieFoutSerializer
|
13
|
-
from ..constants import SCOPE_NOTIFICATIES_PUBLICEREN_LABEL
|
14
14
|
|
15
15
|
|
16
16
|
class NotificationBaseView(APIView):
|
@@ -18,17 +18,15 @@ class NotificationBaseView(APIView):
|
|
18
18
|
Abstract view to receive webhooks
|
19
19
|
"""
|
20
20
|
|
21
|
-
|
21
|
+
schema = None
|
22
22
|
|
23
23
|
permission_classes = (AuthScopesRequired,)
|
24
|
-
required_scopes = Scope(
|
25
|
-
SCOPE_NOTIFICATIES_PUBLICEREN_LABEL
|
26
|
-
) # FIXME: this should be standalone!
|
24
|
+
required_scopes = Scope(SCOPE_NOTIFICATIES_PUBLICEREN_LABEL, private=True)
|
27
25
|
|
28
26
|
def get_serializer(self, *args, **kwargs):
|
29
27
|
return NotificatieSerializer(*args, **kwargs)
|
30
28
|
|
31
|
-
@
|
29
|
+
@extend_schema(
|
32
30
|
responses={
|
33
31
|
204: "",
|
34
32
|
400: ValidatieFoutSerializer,
|
@@ -55,7 +53,9 @@ class NotificationBaseView(APIView):
|
|
55
53
|
class NotificationView(NotificationBaseView):
|
56
54
|
action = "create"
|
57
55
|
permission_classes = (AuthScopesRequired,)
|
58
|
-
required_scopes = {
|
56
|
+
required_scopes = {
|
57
|
+
"create": Scope(SCOPE_NOTIFICATIES_PUBLICEREN_LABEL, private=True)
|
58
|
+
}
|
59
59
|
|
60
60
|
def create(self, request, *args, **kwargs):
|
61
61
|
return self.post(request, *args, **kwargs)
|
@@ -4,7 +4,7 @@ from djangorestframework_camel_case.util import underscoreize
|
|
4
4
|
|
5
5
|
from ..authorizations.models import Applicatie
|
6
6
|
from ..authorizations.serializers import ApplicatieUuidSerializer
|
7
|
-
from ..client import get_client
|
7
|
+
from ..client import get_client, to_internal_data
|
8
8
|
from ..constants import CommonResourceAction
|
9
9
|
from ..utils import get_uuid_from_path
|
10
10
|
|
@@ -20,8 +20,13 @@ class LoggingHandler:
|
|
20
20
|
class AuthHandler:
|
21
21
|
def _request_auth(self, url: str) -> dict:
|
22
22
|
client = get_client(url)
|
23
|
-
|
24
|
-
|
23
|
+
|
24
|
+
if not client:
|
25
|
+
return {}
|
26
|
+
|
27
|
+
response = client.get(url)
|
28
|
+
data = to_internal_data(response)
|
29
|
+
return underscoreize(data)
|
25
30
|
|
26
31
|
def handle(self, message: dict) -> None:
|
27
32
|
uuid = get_uuid_from_path(message["resource_url"])
|
@@ -0,0 +1,23 @@
|
|
1
|
+
# Generated by Django 5.1.2 on 2024-10-25 14:07
|
2
|
+
|
3
|
+
from django.db import migrations
|
4
|
+
|
5
|
+
|
6
|
+
class Migration(migrations.Migration):
|
7
|
+
|
8
|
+
dependencies = [
|
9
|
+
("notifications", "0010_auto_20220704_1419"),
|
10
|
+
]
|
11
|
+
|
12
|
+
operations = [
|
13
|
+
migrations.RemoveField(
|
14
|
+
model_name="subscription",
|
15
|
+
name="config",
|
16
|
+
),
|
17
|
+
migrations.DeleteModel(
|
18
|
+
name="NotificationsConfig",
|
19
|
+
),
|
20
|
+
migrations.DeleteModel(
|
21
|
+
name="Subscription",
|
22
|
+
),
|
23
|
+
]
|
vng_api_common/oas.py
CHANGED
@@ -1,23 +1,19 @@
|
|
1
1
|
"""
|
2
2
|
Utility module for Open API Specification 3.0.x.
|
3
|
-
|
4
|
-
This should get merged into gemma-zds-client, but some heavy refactoring is
|
5
|
-
needed for that.
|
6
3
|
"""
|
7
4
|
|
8
5
|
from typing import Union
|
9
6
|
|
10
7
|
import requests
|
11
8
|
import yaml
|
12
|
-
from drf_yasg import openapi
|
13
9
|
|
14
10
|
TYPE_MAP = {
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
11
|
+
"object": dict,
|
12
|
+
"string": str,
|
13
|
+
"number": (float, int),
|
14
|
+
"integer": int,
|
15
|
+
"boolean": bool,
|
16
|
+
"array": list,
|
21
17
|
}
|
22
18
|
|
23
19
|
|
vng_api_common/routers.py
CHANGED
@@ -8,7 +8,7 @@ class APIRootView(_APIRootView):
|
|
8
8
|
permission_classes = ()
|
9
9
|
|
10
10
|
|
11
|
-
class
|
11
|
+
class NestedRegisteringMixin:
|
12
12
|
_nested_router = None
|
13
13
|
|
14
14
|
def __init__(self, *args, **kwargs):
|
@@ -47,11 +47,11 @@ class ZDSNestedRegisteringMixin:
|
|
47
47
|
)
|
48
48
|
|
49
49
|
|
50
|
-
class NestedSimpleRouter(
|
50
|
+
class NestedSimpleRouter(NestedRegisteringMixin, routers.NestedSimpleRouter):
|
51
51
|
pass
|
52
52
|
|
53
53
|
|
54
|
-
class DefaultRouter(
|
54
|
+
class DefaultRouter(NestedRegisteringMixin, routers.DefaultRouter):
|
55
55
|
APIRootView = APIRootView
|
56
56
|
|
57
57
|
|