-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapi.py
More file actions
67 lines (49 loc) · 1.78 KB
/
api.py
File metadata and controls
67 lines (49 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import hmac
import os
from functools import wraps
from django.http import HttpResponseNotFound
from ninja import NinjaAPI
from ninja.security import HttpBearer
from manage_breast_screening.dicom.api import router as dicom_router
from .api_schema import ErrorResponse, StatusResponse
def check_availability():
def decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
if os.getenv("API_ENABLED", "true").lower() != "true":
return 403, {
"title": "Forbidden",
"status": 403,
"detail": "API is not available",
}
return func(request, *args, **kwargs)
return wrapper
return decorator
def docs_enabled():
def decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
if not os.getenv("API_DOCS_ENABLED", "true").lower() == "true":
return HttpResponseNotFound("API documentation is not available")
return func(request, *args, **kwargs)
return wrapper
return decorator
class GlobalAuth(HttpBearer):
def authenticate(self, request, token):
expected_token = os.getenv("API_AUTH_TOKEN")
if not expected_token:
return None
if hmac.compare_digest(token, expected_token):
return token
api = NinjaAPI(
auth=GlobalAuth(),
docs_decorator=docs_enabled(),
title="Manage Breast Screening API",
version="1.0.0",
)
api.add_router("/dicom/", dicom_router, tags=["DICOM"])
api.add_decorator(check_availability())
dicom_router.add_decorator(check_availability())
@api.get("/status", response={200: StatusResponse, 403: ErrorResponse}, tags=["Status"])
def status(request):
return 200, {"status": "API is available"}