File size: 1,420 Bytes
fa8ac55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import secrets
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from app.routers import router as api_router
from app.config import settings

app = FastAPI(title="AgriVision API")


@app.middleware("http")
async def check_bearer_token(request, call_next):
    if not settings.BEARER_TOKEN:
        return JSONResponse(
            status_code=500,
            content={"detail": "BEARER_TOKEN is not configured on the server"},
        )

    auth_header = request.headers.get("Authorization", "")
    if not auth_header.startswith("Bearer "):
        return JSONResponse(
            status_code=401,
            content={"detail": "Missing or invalid Authorization header"},
            headers={"WWW-Authenticate": "Bearer"},
        )

    provided_token = auth_header[len("Bearer "):].strip()
    if not secrets.compare_digest(provided_token, settings.BEARER_TOKEN):
        return JSONResponse(
            status_code=401,
            content={"detail": "Invalid bearer token"},
            headers={"WWW-Authenticate": "Bearer"},
        )

    return await call_next(request)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(api_router)

@app.get("/")
def read_root():
    return {"message": "Welcome to AgriVision API"}