Skip to content
This repository has been archived by the owner on Jul 9, 2020. It is now read-only.

Commit

Permalink
[controller] Refactored forbid_unallowed (added invalid_response)
Browse files Browse the repository at this point in the history
Allow using the logic in invalid_response also in third party apps.
  • Loading branch information
nemesifier committed Feb 13, 2017
1 parent 59e2f9d commit 13fc0a5
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions django_netjsonconfig/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,19 +60,25 @@ def forbid_unallowed(request, param_group, param, allowed_values=None):
"""
checks for malformed requests - eg: missing parameters (HTTP 400)
or unauthorized requests - eg: wrong key (HTTP 403)
logs suspicious activity
returns either ``None`` if the request is legitimate
or a ``ControllerResponse`` with the appropiate HTTP status
if the request is legitimate, returns ``None``
otherwise calls ``invalid_response``
"""
error = None
value = getattr(request, param_group).get(param)
if not value:
error = 'error: missing required parameter "{}"\n'.format(param)
logger.warning(error, extra={'request': request, 'stack': True})
return ControllerResponse(error, content_type='text/plain', status=400)
return invalid_response(request, error, status=400)
if allowed_values and not isinstance(allowed_values, list):
allowed_values = [allowed_values]
if allowed_values is not None and value not in allowed_values:
error = 'error: wrong {}\n'.format(param)
logger.warning(error, extra={'request': request, 'stack': True})
return ControllerResponse(error, content_type='text/plain', status=403)
return invalid_response(request, error, status=403)


def invalid_response(request, error, status, content_type='text/plain'):
"""
logs an invalid request and returns a ``ControllerResponse``
with the specified HTTP status code, which defaults to 403
"""
logger.warning(error, extra={'request': request, 'stack': True})
return ControllerResponse(error, content_type=content_type, status=status)

0 comments on commit 13fc0a5

Please sign in to comment.