You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.5 KiB

  1. import json
  2. from functools import wraps
  3. from django.contrib.auth.models import User
  4. from django.http import HttpResponseForbidden, JsonResponse
  5. from hc.lib.jsonschema import ValidationError, validate
  6. def make_error(msg):
  7. return JsonResponse({"error": msg}, status=400)
  8. def check_api_key(f):
  9. @wraps(f)
  10. def wrapper(request, *args, **kwds):
  11. request.json = {}
  12. if request.body:
  13. try:
  14. request.json = json.loads(request.body.decode())
  15. except ValueError:
  16. return make_error("could not parse request body")
  17. if "HTTP_X_API_KEY" in request.META:
  18. api_key = request.META["HTTP_X_API_KEY"]
  19. else:
  20. api_key = request.json.get("api_key", "")
  21. if api_key == "":
  22. return make_error("wrong api_key")
  23. try:
  24. request.user = User.objects.get(profile__api_key=api_key)
  25. except User.DoesNotExist:
  26. return HttpResponseForbidden()
  27. return f(request, *args, **kwds)
  28. return wrapper
  29. def validate_json(schema):
  30. """ Validate request.json contents against `schema`.
  31. Supports a tiny subset of JSON schema spec.
  32. """
  33. def decorator(f):
  34. @wraps(f)
  35. def wrapper(request, *args, **kwds):
  36. try:
  37. validate(request.json, schema)
  38. except ValidationError as e:
  39. return make_error("json validation error: %s" % e)
  40. return f(request, *args, **kwds)
  41. return wrapper
  42. return decorator