|
| 1 | +import json |
| 2 | +from http import HTTPStatus |
| 3 | + |
| 4 | +from django.http import HttpResponse |
| 5 | +from django.urls import path |
| 6 | +from django.urls import register_converter |
| 7 | +from django.utils.decorators import method_decorator |
| 8 | +from django.views import View |
| 9 | +from django.views.decorators.csrf import csrf_exempt |
| 10 | +from pydantic import ValidationError |
| 11 | + |
| 12 | +from scim2_models import Context |
| 13 | +from scim2_models import Error |
| 14 | +from scim2_models import ListResponse |
| 15 | +from scim2_models import PatchOp |
| 16 | +from scim2_models import SearchRequest |
| 17 | +from scim2_models import UniquenessException |
| 18 | +from scim2_models import User |
| 19 | + |
| 20 | +from .integrations import delete_record |
| 21 | +from .integrations import from_scim_user |
| 22 | +from .integrations import get_record |
| 23 | +from .integrations import list_records |
| 24 | +from .integrations import save_record |
| 25 | +from .integrations import to_scim_user |
| 26 | + |
| 27 | +# -- setup-start -- |
| 28 | +def scim_response(payload, status=HTTPStatus.OK): |
| 29 | + """Build a Django response with the SCIM media type.""" |
| 30 | + return HttpResponse( |
| 31 | + payload, |
| 32 | + status=status, |
| 33 | + content_type="application/scim+json", |
| 34 | + ) |
| 35 | +# -- setup-end -- |
| 36 | + |
| 37 | + |
| 38 | +# -- refinements-start -- |
| 39 | +# -- converters-start -- |
| 40 | +class UserConverter: |
| 41 | + regex = "[^/]+" |
| 42 | + |
| 43 | + def to_python(self, id): |
| 44 | + try: |
| 45 | + return get_record(id) |
| 46 | + except KeyError: |
| 47 | + raise ValueError |
| 48 | + |
| 49 | + def to_url(self, record): |
| 50 | + return record["id"] |
| 51 | + |
| 52 | + |
| 53 | +register_converter(UserConverter, "user") |
| 54 | +# -- converters-end -- |
| 55 | + |
| 56 | + |
| 57 | +# -- validation-helper-start -- |
| 58 | +def scim_validation_error(error): |
| 59 | + """Turn Pydantic validation errors into a SCIM error response.""" |
| 60 | + scim_error = Error.from_validation_error(error.errors()[0]) |
| 61 | + return scim_response(scim_error.model_dump_json(), scim_error.status) |
| 62 | +# -- validation-helper-end -- |
| 63 | + |
| 64 | + |
| 65 | +# -- uniqueness-helper-start -- |
| 66 | +def scim_uniqueness_error(error): |
| 67 | + """Turn uniqueness errors into a SCIM 409 response.""" |
| 68 | + scim_error = UniquenessException(detail=str(error)).to_error() |
| 69 | + return scim_response(scim_error.model_dump_json(), HTTPStatus.CONFLICT) |
| 70 | +# -- uniqueness-helper-end -- |
| 71 | + |
| 72 | + |
| 73 | +# -- error-handler-start -- |
| 74 | +def handler404(request, exception): |
| 75 | + """Turn Django 404 errors into SCIM error responses.""" |
| 76 | + scim_error = Error(status=404, detail=str(exception)) |
| 77 | + return scim_response(scim_error.model_dump_json(), HTTPStatus.NOT_FOUND) |
| 78 | +# -- error-handler-end -- |
| 79 | +# -- refinements-end -- |
| 80 | + |
| 81 | + |
| 82 | +# -- endpoints-start -- |
| 83 | +# -- single-resource-start -- |
| 84 | +@method_decorator(csrf_exempt, name="dispatch") |
| 85 | +class UserView(View): |
| 86 | + """Handle GET, PATCH and DELETE on one SCIM user resource.""" |
| 87 | + |
| 88 | + def get(self, request, app_record): |
| 89 | + scim_user = to_scim_user(app_record) |
| 90 | + return scim_response( |
| 91 | + scim_user.model_dump_json(scim_ctx=Context.RESOURCE_QUERY_RESPONSE) |
| 92 | + ) |
| 93 | + |
| 94 | + def delete(self, request, app_record): |
| 95 | + delete_record(app_record["id"]) |
| 96 | + return scim_response("", HTTPStatus.NO_CONTENT) |
| 97 | + |
| 98 | + def patch(self, request, app_record): |
| 99 | + try: |
| 100 | + patch = PatchOp[User].model_validate( |
| 101 | + json.loads(request.body), |
| 102 | + scim_ctx=Context.RESOURCE_PATCH_REQUEST, |
| 103 | + ) |
| 104 | + except ValidationError as error: |
| 105 | + return scim_validation_error(error) |
| 106 | + |
| 107 | + scim_user = to_scim_user(app_record) |
| 108 | + patch.patch(scim_user) |
| 109 | + |
| 110 | + updated_record = from_scim_user(scim_user) |
| 111 | + try: |
| 112 | + save_record(updated_record) |
| 113 | + except ValueError as error: |
| 114 | + return scim_uniqueness_error(error) |
| 115 | + |
| 116 | + return scim_response( |
| 117 | + scim_user.model_dump_json(scim_ctx=Context.RESOURCE_PATCH_RESPONSE) |
| 118 | + ) |
| 119 | +# -- single-resource-end -- |
| 120 | + |
| 121 | + |
| 122 | +# -- collection-start -- |
| 123 | +@method_decorator(csrf_exempt, name="dispatch") |
| 124 | +class UsersView(View): |
| 125 | + """Handle GET and POST on the SCIM users collection.""" |
| 126 | + |
| 127 | + def get(self, request): |
| 128 | + try: |
| 129 | + req = SearchRequest.model_validate(request.GET) |
| 130 | + except ValidationError as error: |
| 131 | + return scim_validation_error(error) |
| 132 | + all_records = list_records() |
| 133 | + page = all_records[req.start_index_0 : req.stop_index_0] |
| 134 | + resources = [to_scim_user(record) for record in page] |
| 135 | + response = ListResponse[User]( |
| 136 | + total_results=len(all_records), |
| 137 | + start_index=req.start_index or 1, |
| 138 | + items_per_page=len(resources), |
| 139 | + resources=resources, |
| 140 | + ) |
| 141 | + return scim_response( |
| 142 | + response.model_dump_json(scim_ctx=Context.RESOURCE_QUERY_RESPONSE) |
| 143 | + ) |
| 144 | + |
| 145 | + def post(self, request): |
| 146 | + try: |
| 147 | + request_user = User.model_validate( |
| 148 | + json.loads(request.body), |
| 149 | + scim_ctx=Context.RESOURCE_CREATION_REQUEST, |
| 150 | + ) |
| 151 | + except ValidationError as error: |
| 152 | + return scim_validation_error(error) |
| 153 | + |
| 154 | + app_record = from_scim_user(request_user) |
| 155 | + try: |
| 156 | + save_record(app_record) |
| 157 | + except ValueError as error: |
| 158 | + return scim_uniqueness_error(error) |
| 159 | + |
| 160 | + response_user = to_scim_user(app_record) |
| 161 | + return scim_response( |
| 162 | + response_user.model_dump_json(scim_ctx=Context.RESOURCE_CREATION_RESPONSE), |
| 163 | + HTTPStatus.CREATED, |
| 164 | + ) |
| 165 | + |
| 166 | + |
| 167 | +urlpatterns = [ |
| 168 | + path("scim/v2/Users", UsersView.as_view(), name="scim_users"), |
| 169 | + path("scim/v2/Users/<user:app_record>", UserView.as_view(), name="scim_user"), |
| 170 | +] |
| 171 | +# -- collection-end -- |
| 172 | +# -- endpoints-end -- |
0 commit comments