-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
133 lines (122 loc) · 4.51 KB
/
app.py
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
from fastapi import FastAPI, Request, HTTPException, status
import requests
from fastapi.responses import RedirectResponse, JSONResponse
from fastapi.encoders import jsonable_encoder
import uvicorn
from application import getRoutes
from pydantic import BaseModel
import json
from endpoint_definations import endpoint_definations
from config import config
import jwt
import os
from starlette import status
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response
from starlette.types import ASGIApp
from fastapi.middleware.cors import CORSMiddleware
from utils import exclusion_check
class LimitUploadSize(BaseHTTPMiddleware):
def __init__(self, app: ASGIApp, max_upload_size: int) -> None:
super().__init__(app)
self.max_upload_size = max_upload_size
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
if request.method == 'POST':
if 'content-length' not in request.headers:
return Response(status_code=status.HTTP_411_LENGTH_REQUIRED)
content_length = int(request.headers['content-length'])
if content_length > self.max_upload_size:
return Response(status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
return await call_next(request)
app = FastAPI(title=config.app_name)
app.add_middleware(LimitUploadSize, max_upload_size=3_000_000)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
routerPaths = getRoutes()
for routerPath in routerPaths:
app.include_router(routerPath)
if not os.path.isdir(config.media_path):
os.mkdir(config.media_path)
if not os.path.isdir(config.thumbnail_path):
os.mkdir(config.thumbnail_path)
@app.get("/{url:path}")
async def GETApiGateway(request: Request, url: str):
try:
method = "GET"
endpoint_url = url.split("/")
endpoint_def = endpoint_definations.get(endpoint_url[0])
if endpoint_def:
if not exclusion_check(endpoint_def["excluded_routes"], endpoint_url[1:], method):
if(endpoint_def["auth"][method]["required"]):
if not request.headers.get("www-authenticate") or len(request.headers.get("www-authenticate")) < 10:
raise HTTPException(status_code=404,
detail="JWT Required",
headers={"www-authenticate": "bearer <TOKEN> Needed"}
)
jwtToken = request.headers["www-authenticate"]
payload = jwt.decode(jwtToken, config.SECRET_KEY, algorithms=[config.ALGORITHM])
forwarding_url = ("http://{}:{}/{}".format(endpoint_def["host"], endpoint_def["port"],'/'.join(endpoint_url[1:])))
req = requests.get(forwarding_url)
return json.loads(req.content)
else:
raise HTTPException(status_code=404, detail="Route not found")
except jwt.exceptions.DecodeError as e:
return {
"error": HTTPException(
status_code=500,
detail="JWT Decode Failed",
headers={"www-authenticate": "bearer"}
)
}
except HTTPException as e:
return {
"error": e
}
except Exception as e:
return {
"error": str(e)
}
@app.post("/{url:path}")
async def POSTApiGateway(request: Request, url: str):
try:
inputParam = json.loads((await request.body()).decode('utf-8'))
method = "POST"
endpoint_url = url.split("/")
endpoint_def = endpoint_definations.get(endpoint_url[0])
if endpoint_def:
if not exclusion_check(endpoint_def["excluded_routes"], endpoint_url[1:], method):
if(endpoint_def["auth"][method]["required"]):
if not request.headers.get("www-authenticate") or len(request.headers.get("www-authenticate")) < 10:
raise HTTPException(status_code=404,
detail="JWT Required",
headers={"www-authenticate": "bearer <TOKEN> Needed"}
)
jwtToken = request.headers["www-authenticate"]
payload = jwt.decode(jwtToken, config.SECRET_KEY, algorithms=[config.ALGORITHM])
forwarding_url = ("http://{}:{}/{}".format(endpoint_def["host"], endpoint_def["port"],'/'.join(endpoint_url[1:])))
print("FORWARDING: ", forwarding_url)
req = requests.post(forwarding_url, json=jsonable_encoder(inputParam))
return json.loads(req.content)
else:
raise HTTPException(status_code=404, detail="Route not found")
except jwt.exceptions.DecodeError as e:
return {
"error": HTTPException(status_code=500,
detail="JWT Decode Failed",
headers={"www-authenticate": "bearer"}
)
}
except HTTPException as e:
return {
"error": e
}
except Exception as e:
return {
"error": str(e)
}