Spaces:
Runtime error
Runtime error
Commit ·
9af3b3c
1
Parent(s): a6a2032
add security
Browse files- app/core/middleware.py +20 -0
- app/main.py +5 -0
- requirements.txt +0 -0
app/core/middleware.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 2 |
+
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
| 3 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 4 |
+
from starlette.responses import Response
|
| 5 |
+
|
| 6 |
+
security = HTTPBasic()
|
| 7 |
+
|
| 8 |
+
class BasicAuthMiddleware(BaseHTTPMiddleware):
|
| 9 |
+
def __init__(self, app: FastAPI, username: str, password: str):
|
| 10 |
+
super().__init__(app)
|
| 11 |
+
self.username = username
|
| 12 |
+
self.password = password
|
| 13 |
+
|
| 14 |
+
async def dispatch(self, request: Request, call_next):
|
| 15 |
+
if request.url.path.startswith("/docs") or request.url.path.startswith("/redoc"):
|
| 16 |
+
credentials: HTTPBasicCredentials = await security(request)
|
| 17 |
+
if not (credentials.username == self.username and credentials.password == self.password):
|
| 18 |
+
return Response("Unauthorized", status_code=401, headers={"WWW-Authenticate": "Basic"})
|
| 19 |
+
response = await call_next(request)
|
| 20 |
+
return response
|
app/main.py
CHANGED
|
@@ -19,6 +19,7 @@ from app.db.base import *
|
|
| 19 |
from app.core.auth import *
|
| 20 |
# from app.router.user import *
|
| 21 |
from app.core.database import *
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
# Load environment variables from .env file
|
|
@@ -51,6 +52,10 @@ async def lifespan(app: FastAPI):
|
|
| 51 |
logger.error(e)
|
| 52 |
|
| 53 |
app = FastAPI(lifespan=lifespan)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
# Allow CORS for specific origin with credentials
|
| 55 |
origins = [
|
| 56 |
os.getenv("client")
|
|
|
|
| 19 |
from app.core.auth import *
|
| 20 |
# from app.router.user import *
|
| 21 |
from app.core.database import *
|
| 22 |
+
from app.core.middleware import BasicAuthMiddleware
|
| 23 |
|
| 24 |
|
| 25 |
# Load environment variables from .env file
|
|
|
|
| 52 |
logger.error(e)
|
| 53 |
|
| 54 |
app = FastAPI(lifespan=lifespan)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
app.add_middleware(BasicAuthMiddleware, username=os.getenv("fastapiusername"), password=os.getenv("fastapipassword"))
|
| 59 |
# Allow CORS for specific origin with credentials
|
| 60 |
origins = [
|
| 61 |
os.getenv("client")
|
requirements.txt
CHANGED
|
Binary files a/requirements.txt and b/requirements.txt differ
|
|
|