|
| 1 | +import re |
| 2 | + |
| 3 | +from rest_framework.exceptions import ValidationError |
| 4 | +from rest_framework.filters import BaseFilterBackend, OrderingFilter |
| 5 | + |
| 6 | +from rest_framework_json_api.utils import format_value |
| 7 | + |
| 8 | + |
| 9 | +class OrderingFilter(OrderingFilter): |
| 10 | + """ |
| 11 | + A backend filter that implements http://jsonapi.org/format/#fetching-sorting and |
| 12 | + raises a 400 error if any sort field is invalid. |
| 13 | +
|
| 14 | + If you prefer *not* to report 400 errors for invalid sort fields, just use |
| 15 | + :py:class:`rest_framework.filters.OrderingFilter` with |
| 16 | + :py:attr:`~rest_framework.filters.OrderingFilter.ordering_param` = "sort" |
| 17 | +
|
| 18 | + Also applies DJA format_value() to convert (e.g. camelcase) to underscore. |
| 19 | + (See JSON_API_FORMAT_FIELD_NAMES in docs/usage.md) |
| 20 | + """ |
| 21 | + #: override :py:attr:`rest_framework.filters.OrderingFilter.ordering_param` |
| 22 | + #: with JSON:API-compliant query parameter name. |
| 23 | + ordering_param = 'sort' |
| 24 | + |
| 25 | + def remove_invalid_fields(self, queryset, fields, view, request): |
| 26 | + """ |
| 27 | + Extend :py:meth:`rest_framework.filters.OrderingFilter.remove_invalid_fields` to |
| 28 | + validate that all provided sort fields exist (as contrasted with the super's behavior |
| 29 | + which is to silently remove invalid fields). |
| 30 | +
|
| 31 | + :raises ValidationError: if a sort field is invalid. |
| 32 | + """ |
| 33 | + valid_fields = [ |
| 34 | + item[0] for item in self.get_valid_fields(queryset, view, |
| 35 | + {'request': request}) |
| 36 | + ] |
| 37 | + bad_terms = [ |
| 38 | + term for term in fields |
| 39 | + if format_value(term.replace(".", "__").lstrip('-'), "underscore") not in valid_fields |
| 40 | + ] |
| 41 | + if bad_terms: |
| 42 | + raise ValidationError('invalid sort parameter{}: {}'.format( |
| 43 | + ('s' if len(bad_terms) > 1 else ''), ','.join(bad_terms))) |
| 44 | + # this looks like it duplicates code above, but we want the ValidationError to report |
| 45 | + # the actual parameter supplied while we want the fields passed to the super() to |
| 46 | + # be correctly rewritten. |
| 47 | + # The leading `-` has to be stripped to prevent format_value from turning it into `_`. |
| 48 | + underscore_fields = [] |
| 49 | + for item in fields: |
| 50 | + item_rewritten = item.replace(".", "__") |
| 51 | + if item_rewritten.startswith('-'): |
| 52 | + underscore_fields.append( |
| 53 | + '-' + format_value(item_rewritten.lstrip('-'), "underscore")) |
| 54 | + else: |
| 55 | + underscore_fields.append(format_value(item_rewritten, "underscore")) |
| 56 | + |
| 57 | + return super(OrderingFilter, self).remove_invalid_fields( |
| 58 | + queryset, underscore_fields, view, request) |
| 59 | + |
| 60 | + |
| 61 | +class QueryParameterValidationFilter(BaseFilterBackend): |
| 62 | + """ |
| 63 | + A backend filter that performs strict validation of query parameters for |
| 64 | + JSON:API spec conformance and raises a 400 error if non-conforming usage is |
| 65 | + found. |
| 66 | +
|
| 67 | + If you want to add some additional non-standard query parameters, |
| 68 | + override :py:attr:`query_regex` adding the new parameters. Make sure to comply with |
| 69 | + the rules at http://jsonapi.org/format/#query-parameters. |
| 70 | + """ |
| 71 | + #: compiled regex that matches the allowed http://jsonapi.org/format/#query-parameters: |
| 72 | + #: `sort` and `include` stand alone; `filter`, `fields`, and `page` have []'s |
| 73 | + query_regex = re.compile(r'^(sort|include)$|^(filter|fields|page)(\[[\w\.\-]+\])?$') |
| 74 | + |
| 75 | + def validate_query_params(self, request): |
| 76 | + """ |
| 77 | + Validate that query params are in the list of valid query keywords in |
| 78 | + :py:attr:`query_regex` |
| 79 | +
|
| 80 | + :raises ValidationError: if not. |
| 81 | + """ |
| 82 | + # TODO: For jsonapi error object conformance, must set jsonapi errors "parameter" for |
| 83 | + # the ValidationError. This requires extending DRF/DJA Exceptions. |
| 84 | + for qp in request.query_params.keys(): |
| 85 | + if not self.query_regex.match(qp): |
| 86 | + raise ValidationError('invalid query parameter: {}'.format(qp)) |
| 87 | + if len(request.query_params.getlist(qp)) > 1: |
| 88 | + raise ValidationError( |
| 89 | + 'repeated query parameter not allowed: {}'.format(qp)) |
| 90 | + |
| 91 | + def filter_queryset(self, request, queryset, view): |
| 92 | + """ |
| 93 | + Overrides :py:meth:`BaseFilterBackend.filter_queryset` by first validating the |
| 94 | + query params with :py:meth:`validate_query_params` |
| 95 | + """ |
| 96 | + self.validate_query_params(request) |
| 97 | + return queryset |
0 commit comments