commonground-api-common 1.13.3__py3-none-any.whl → 2.0.0__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.
Files changed (32) hide show
  1. {commonground_api_common-1.13.3.dist-info → commonground_api_common-2.0.0.dist-info}/METADATA +22 -23
  2. {commonground_api_common-1.13.3.dist-info → commonground_api_common-2.0.0.dist-info}/RECORD +30 -27
  3. {commonground_api_common-1.13.3.dist-info → commonground_api_common-2.0.0.dist-info}/WHEEL +1 -1
  4. vng_api_common/__init__.py +1 -1
  5. vng_api_common/admin.py +1 -20
  6. vng_api_common/authorizations/admin.py +1 -1
  7. vng_api_common/authorizations/middleware.py +244 -0
  8. vng_api_common/authorizations/migrations/0016_remove_authorizationsconfig_api_root_and_more.py +76 -0
  9. vng_api_common/authorizations/models.py +38 -3
  10. vng_api_common/authorizations/utils.py +17 -0
  11. vng_api_common/client.py +56 -27
  12. vng_api_common/conf/api.py +0 -3
  13. vng_api_common/management/commands/generate_swagger.py +1 -1
  14. vng_api_common/middleware.py +1 -227
  15. vng_api_common/migrations/0006_delete_apicredential.py +119 -0
  16. vng_api_common/mocks.py +4 -1
  17. vng_api_common/models.py +0 -111
  18. vng_api_common/notifications/api/views.py +1 -1
  19. vng_api_common/notifications/handlers.py +8 -3
  20. vng_api_common/notifications/migrations/0011_remove_subscription_config_and_more.py +23 -0
  21. vng_api_common/oas.py +0 -3
  22. vng_api_common/routers.py +3 -3
  23. vng_api_common/tests/schema.py +12 -0
  24. vng_api_common/utils.py +0 -22
  25. vng_api_common/validators.py +0 -38
  26. vng_api_common/views.py +26 -22
  27. vng_api_common/notifications/constants.py +0 -3
  28. vng_api_common/notifications/models.py +0 -97
  29. {commonground_api_common-1.13.3.data → commonground_api_common-2.0.0.data}/scripts/generate_schema +0 -0
  30. {commonground_api_common-1.13.3.data → commonground_api_common-2.0.0.data}/scripts/patch_content_types +0 -0
  31. {commonground_api_common-1.13.3.data → commonground_api_common-2.0.0.data}/scripts/use_external_components +0 -0
  32. {commonground_api_common-1.13.3.dist-info → commonground_api_common-2.0.0.dist-info}/top_level.txt +0 -0
@@ -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,8 +1,5 @@
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
vng_api_common/routers.py CHANGED
@@ -8,7 +8,7 @@ class APIRootView(_APIRootView):
8
8
  permission_classes = ()
9
9
 
10
10
 
11
- class ZDSNestedRegisteringMixin:
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(ZDSNestedRegisteringMixin, routers.NestedSimpleRouter):
50
+ class NestedSimpleRouter(NestedRegisteringMixin, routers.NestedSimpleRouter):
51
51
  pass
52
52
 
53
53
 
54
- class DefaultRouter(ZDSNestedRegisteringMixin, routers.DefaultRouter):
54
+ class DefaultRouter(NestedRegisteringMixin, routers.DefaultRouter):
55
55
  APIRootView = APIRootView
56
56
 
57
57
 
@@ -5,6 +5,8 @@ from urllib.parse import urlparse
5
5
  from django.conf import settings
6
6
 
7
7
  import yaml
8
+ from requests_mock import Mocker
9
+ from zgw_consumers_oas.schema_loading import read_schema
8
10
 
9
11
  DEFAULT_PATH_PARAMETERS = {"version": "1"}
10
12
 
@@ -69,3 +71,13 @@ def get_validation_errors(response, field, index=0):
69
71
  return error
70
72
 
71
73
  i += 1
74
+
75
+
76
+ def mock_service_oas_get(
77
+ mock: Mocker, url: str, service: str, oas_url: str = ""
78
+ ) -> None:
79
+ if not oas_url:
80
+ oas_url = f"{url}schema/openapi.yaml?v=3"
81
+
82
+ content = read_schema(service)
83
+ mock.get(oas_url, content=content)
vng_api_common/utils.py CHANGED
@@ -13,9 +13,6 @@ from django.utils.encoding import smart_str
13
13
  from django.utils.module_loading import import_string
14
14
 
15
15
  from rest_framework.utils import formatting
16
- from zds_client.client import ClientError
17
-
18
- from .client import get_client
19
16
 
20
17
  try:
21
18
  from djangorestframework_camel_case.util import (
@@ -186,25 +183,6 @@ def get_uuid_from_path(path: str) -> str:
186
183
  return uuid_str
187
184
 
188
185
 
189
- def request_object_attribute(
190
- url: str, attribute: str, resource: Union[str, None] = None
191
- ) -> str:
192
- client = get_client(url)
193
-
194
- try:
195
- result = client.retrieve(resource, url=url)[attribute]
196
- except (ClientError, KeyError) as exc:
197
- logger.warning(
198
- "%s was retrieved from %s with the %s: %s",
199
- attribute,
200
- url,
201
- exc.__class__.__name__,
202
- exc,
203
- )
204
- result = ""
205
- return result
206
-
207
-
208
186
  def generate_unique_identification(instance: models.Model, date_field_name: str):
209
187
  model = type(instance)
210
188
  model_name = getattr(model, "IDENTIFICATIE_PREFIX", model._meta.model_name.upper())
@@ -11,10 +11,8 @@ from django.utils.deconstruct import deconstructible
11
11
  from django.utils.module_loading import import_string
12
12
  from django.utils.translation import gettext_lazy as _
13
13
 
14
- import requests
15
14
  from rest_framework import serializers, validators
16
15
 
17
- from .client import get_client
18
16
  from .constants import RSIN_LENGTH
19
17
  from .oas import fetcher, obj_has_shape
20
18
 
@@ -221,42 +219,6 @@ class InformatieObjectUniqueValidator(validators.UniqueTogetherValidator):
221
219
  super().__call__(attrs)
222
220
 
223
221
 
224
- class ObjectInformatieObjectValidator:
225
- """
226
- Validate that the INFORMATIEOBJECT is linked already in the DRC.
227
- """
228
-
229
- message = _(
230
- "Het informatieobject is in het DRC nog niet gerelateerd aan dit object."
231
- )
232
- code = "inconsistent-relation"
233
- requires_context = True
234
-
235
- def __call__(self, informatieobject: str, serializer):
236
- object_url = serializer.context["parent_object"].get_absolute_api_url(
237
- self.request
238
- )
239
-
240
- # dynamic so that it can be mocked in tests easily
241
- client = get_client(informatieobject)
242
-
243
- try:
244
- oios = client.list(
245
- "objectinformatieobject",
246
- query_params={
247
- "informatieobject": informatieobject,
248
- "object": object_url,
249
- },
250
- )
251
- except requests.HTTPError as exc:
252
- raise serializers.ValidationError(
253
- exc.args[0], code="relation-validation-error"
254
- ) from exc
255
-
256
- if len(oios) == 0:
257
- raise serializers.ValidationError(self.message, code=self.code)
258
-
259
-
260
222
  @deconstructible
261
223
  class UntilNowValidator:
262
224
  """
vng_api_common/views.py CHANGED
@@ -1,6 +1,7 @@
1
1
  import logging
2
2
  import os
3
3
  from collections import OrderedDict
4
+ from typing import Optional
4
5
 
5
6
  from django.apps import apps
6
7
  from django.conf import settings
@@ -13,7 +14,8 @@ import requests
13
14
  from rest_framework import exceptions as drf_exceptions, status
14
15
  from rest_framework.response import Response
15
16
  from rest_framework.views import exception_handler as drf_exception_handler
16
- from zds_client import ClientError
17
+
18
+ from vng_api_common.client import Client, ClientError
17
19
 
18
20
  from . import exceptions
19
21
  from .compat import sentry_client
@@ -128,12 +130,20 @@ def _test_ac_config() -> list:
128
130
  auth_config = AuthorizationsConfig.get_solo()
129
131
 
130
132
  # check if AC auth is configured
131
- ac_client = AuthorizationsConfig.get_client()
132
- has_ac_auth = ac_client.auth is not None
133
+ ac_client: Optional[Client] = AuthorizationsConfig.get_client()
134
+ has_ac_auth = ac_client.auth is not None if ac_client else False
133
135
 
134
136
  checks = [
135
137
  (_("Type of component"), auth_config.get_component_display(), None),
136
- (_("AC"), auth_config.api_root, auth_config.api_root.endswith("/")),
138
+ (
139
+ _("AC"),
140
+ (
141
+ auth_config.authorizations_api_service.api_root
142
+ if ac_client
143
+ else _("Missing")
144
+ ),
145
+ bool(ac_client),
146
+ ),
137
147
  (
138
148
  _("Credentials for AC"),
139
149
  _("Configured") if has_ac_auth else _("Missing"),
@@ -145,18 +155,17 @@ def _test_ac_config() -> list:
145
155
  if has_ac_auth:
146
156
  error = False
147
157
 
158
+ client_id = ac_client.auth.service.client_id
159
+
148
160
  try:
149
- ac_client.list(
150
- "applicatie", query_params={"clientIds": ac_client.auth.client_id}
161
+ response: requests.Response = ac_client.get(
162
+ "applicaties", params={"clientIds": client_id}
151
163
  )
152
- except requests.ConnectionError:
164
+
165
+ response.raise_for_status()
166
+ except requests.RequestException:
153
167
  error = True
154
168
  message = _("Could not connect with AC")
155
- except ClientError as exc:
156
- error = True
157
- message = _(
158
- "Cannot retrieve authorizations: HTTP {status_code} - {error_code}"
159
- ).format(status_code=exc.args[0]["status"], error_code=exc.args[0]["code"])
160
169
  else:
161
170
  message = _("Can retrieve authorizations")
162
171
 
@@ -166,14 +175,13 @@ def _test_ac_config() -> list:
166
175
 
167
176
 
168
177
  def _test_nrc_config() -> list:
169
- if not apps.is_installed("vng_api_common.notifications"):
178
+ if not apps.is_installed("notifications_api_common"):
170
179
  return []
171
180
 
172
181
  from notifications_api_common.models import NotificationsConfig, Subscription
173
182
 
174
183
  nrc_config = NotificationsConfig.get_solo()
175
-
176
- nrc_client = NotificationsConfig.get_client()
184
+ nrc_client: Optional[Client] = NotificationsConfig.get_client()
177
185
 
178
186
  has_nrc_auth = nrc_client.auth is not None if nrc_client else False
179
187
 
@@ -199,15 +207,11 @@ def _test_nrc_config() -> list:
199
207
  error = False
200
208
 
201
209
  try:
202
- nrc_client.list("kanaal")
203
- except requests.ConnectionError:
210
+ response: requests.Response = nrc_client.get("kanaal")
211
+ response.raise_for_status()
212
+ except requests.RequestException:
204
213
  error = True
205
214
  message = _("Could not connect with NRC")
206
- except ClientError as exc:
207
- error = True
208
- message = _(
209
- "Cannot retrieve kanalen: HTTP {status_code} - {error_code}"
210
- ).format(status_code=exc.args[0]["status"], error_code=exc.args[0]["code"])
211
215
  else:
212
216
  message = _("Can retrieve kanalen")
213
217
 
@@ -1,3 +0,0 @@
1
- # Exernally defined scopes.
2
- SCOPE_NOTIFICATIES_CONSUMEREN_LABEL = "notificaties.consumeren"
3
- SCOPE_NOTIFICATIES_PUBLICEREN_LABEL = "notificaties.publiceren"
@@ -1,97 +0,0 @@
1
- import uuid
2
- from urllib.parse import urljoin
3
-
4
- from django.contrib.postgres.fields import ArrayField
5
- from django.db import models
6
- from django.utils.translation import gettext_lazy as _
7
-
8
- from zds_client import ClientAuth
9
-
10
- from ..client import get_client
11
- from ..decorators import field_default
12
- from ..models import APICredential, ClientConfig
13
-
14
-
15
- @field_default("api_root", "https://notificaties-api.vng.cloud/api/v1/")
16
- class NotificationsConfig(ClientConfig):
17
- class Meta:
18
- verbose_name = _("Notificatiescomponentconfiguratie")
19
-
20
- def get_auth(self) -> ClientAuth:
21
- auth = APICredential.get_auth(self.api_root)
22
- return auth
23
-
24
-
25
- class Subscription(models.Model):
26
- """
27
- A single subscription.
28
-
29
- TODO: on change/update, update the subscription
30
- """
31
-
32
- config = models.ForeignKey("NotificationsConfig", on_delete=models.CASCADE)
33
-
34
- callback_url = models.URLField(
35
- _("callback url"), help_text=_("Where to send the notifications (webhook url)")
36
- )
37
- client_id = models.CharField(
38
- _("client ID"),
39
- max_length=50,
40
- help_text=_("Client ID to construct the auth token"),
41
- )
42
- secret = models.CharField(
43
- _("client secret"),
44
- max_length=50,
45
- help_text=_("Secret to construct the auth token"),
46
- )
47
- channels = ArrayField(
48
- models.CharField(max_length=100),
49
- verbose_name=_("channels"),
50
- help_text=_("Comma-separated list of channels to subscribe to"),
51
- )
52
-
53
- _subscription = models.URLField(
54
- _("NC subscription"),
55
- blank=True,
56
- editable=False,
57
- help_text=_("Subscription as it is known in the NC"),
58
- )
59
-
60
- class Meta:
61
- verbose_name = _("Webhook subscription")
62
- verbose_name_plural = _("Webhook subscriptions")
63
-
64
- def __str__(self):
65
- return f"{', '.join(self.channels)} - {self.callback_url}"
66
-
67
- def register(self) -> None:
68
- """
69
- Registers the webhook with the notification component.
70
- """
71
- dummy_detail_url = urljoin(self.config.api_root, f"foo/{uuid.uuid4()}")
72
- client = get_client(dummy_detail_url)
73
-
74
- # This authentication is for the NC to call us. Thus, it's *not* for
75
- # calling the NC to create a subscription.
76
- self_auth = ClientAuth(
77
- client_id=self.client_id,
78
- secret=self.secret,
79
- )
80
- data = {
81
- "callbackUrl": self.callback_url,
82
- "auth": self_auth.credentials()["Authorization"],
83
- "kanalen": [
84
- {
85
- "naam": channel,
86
- # FIXME: You need to be able to configure these.
87
- "filters": {},
88
- }
89
- for channel in self.channels
90
- ],
91
- }
92
-
93
- # register the subscriber
94
- subscriber = client.create("abonnement", data=data)
95
-
96
- self._subscription = subscriber["url"]
97
- self.save(update_fields=["_subscription"])