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.

78 lines
2.2 KiB

  1. import json
  2. import uuid
  3. from functools import wraps
  4. from django.contrib.auth.models import User
  5. from django.http import HttpResponseBadRequest, JsonResponse
  6. from six import string_types
  7. def uuid_or_400(f):
  8. @wraps(f)
  9. def wrapper(request, *args, **kwds):
  10. try:
  11. uuid.UUID(args[0])
  12. except ValueError:
  13. return HttpResponseBadRequest()
  14. return f(request, *args, **kwds)
  15. return wrapper
  16. def make_error(msg):
  17. return JsonResponse({"error": msg}, status=400)
  18. def check_api_key(f):
  19. @wraps(f)
  20. def wrapper(request, *args, **kwds):
  21. try:
  22. data = json.loads(request.body.decode("utf-8"))
  23. except ValueError:
  24. return make_error("could not parse request body")
  25. api_key = str(data.get("api_key", ""))
  26. if api_key == "":
  27. return make_error("wrong api_key")
  28. try:
  29. user = User.objects.get(profile__api_key=api_key)
  30. except User.DoesNotExist:
  31. return make_error("wrong api_key")
  32. request.json = data
  33. request.user = user
  34. return f(request, *args, **kwds)
  35. return wrapper
  36. def validate_json(schema):
  37. """ Validate request.json contents against `schema`.
  38. Supports a tiny subset of JSON schema spec.
  39. """
  40. def decorator(f):
  41. @wraps(f)
  42. def wrapper(request, *args, **kwds):
  43. for key, spec in schema["properties"].items():
  44. if key not in request.json:
  45. continue
  46. value = request.json[key]
  47. if spec["type"] == "string":
  48. if not isinstance(value, string_types):
  49. return make_error("%s is not a string" % key)
  50. elif spec["type"] == "number":
  51. if not isinstance(value, int):
  52. return make_error("%s is not a number" % key)
  53. if "minimum" in spec and value < spec["minimum"]:
  54. return make_error("%s is too small" % key)
  55. if "maximum" in spec and value > spec["maximum"]:
  56. return make_error("%s is too large" % key)
  57. return f(request, *args, **kwds)
  58. return wrapper
  59. return decorator