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.

117 lines
3.3 KiB

  1. import json
  2. from functools import wraps
  3. from django.db.models import Q
  4. from django.http import HttpResponse, JsonResponse
  5. from hc.accounts.models import Project
  6. from hc.lib.jsonschema import ValidationError, validate
  7. def error(msg, status=400):
  8. return JsonResponse({"error": msg}, status=status)
  9. def authorize(f):
  10. @wraps(f)
  11. def wrapper(request, *args, **kwds):
  12. if "HTTP_X_API_KEY" in request.META:
  13. api_key = request.META["HTTP_X_API_KEY"]
  14. else:
  15. api_key = str(request.json.get("api_key", ""))
  16. if len(api_key) != 32:
  17. return error("missing api key", 401)
  18. try:
  19. request.project = Project.objects.get(api_key=api_key)
  20. except Project.DoesNotExist:
  21. return error("wrong api key", 401)
  22. request.readonly = False
  23. return f(request, *args, **kwds)
  24. return wrapper
  25. def authorize_read(f):
  26. @wraps(f)
  27. def wrapper(request, *args, **kwds):
  28. if "HTTP_X_API_KEY" in request.META:
  29. api_key = request.META["HTTP_X_API_KEY"]
  30. else:
  31. api_key = str(request.json.get("api_key", ""))
  32. if len(api_key) != 32:
  33. return error("missing api key", 401)
  34. write_key_match = Q(api_key=api_key)
  35. read_key_match = Q(api_key_readonly=api_key)
  36. try:
  37. request.project = Project.objects.get(write_key_match | read_key_match)
  38. except Project.DoesNotExist:
  39. return error("wrong api key", 401)
  40. request.readonly = api_key == request.project.api_key_readonly
  41. return f(request, *args, **kwds)
  42. return wrapper
  43. def validate_json(schema=None):
  44. """ Parse request json and validate it against `schema`.
  45. Put the parsed result in `request.json`.
  46. If schema is None then only parse and don't validate.
  47. Supports a limited subset of JSON schema spec.
  48. """
  49. def decorator(f):
  50. @wraps(f)
  51. def wrapper(request, *args, **kwds):
  52. if request.body:
  53. try:
  54. request.json = json.loads(request.body.decode())
  55. except ValueError:
  56. return error("could not parse request body")
  57. else:
  58. request.json = {}
  59. if schema:
  60. try:
  61. validate(request.json, schema)
  62. except ValidationError as e:
  63. return error("json validation error: %s" % e)
  64. return f(request, *args, **kwds)
  65. return wrapper
  66. return decorator
  67. def cors(*methods):
  68. methods = set(methods)
  69. methods.add("OPTIONS")
  70. methods_str = ", ".join(methods)
  71. def decorator(f):
  72. @wraps(f)
  73. def wrapper(request, *args, **kwds):
  74. if request.method == "OPTIONS":
  75. # Handle OPTIONS here
  76. response = HttpResponse(status=204)
  77. elif request.method in methods:
  78. response = f(request, *args, **kwds)
  79. else:
  80. response = HttpResponse(status=405)
  81. response["Access-Control-Allow-Origin"] = "*"
  82. response["Access-Control-Allow-Headers"] = "X-Api-Key"
  83. response["Access-Control-Allow-Methods"] = methods_str
  84. response["Access-Control-Max-Age"] = "600"
  85. return response
  86. return wrapper
  87. return decorator