File size: 1,352 Bytes
9766e10
48d9c32
 
9766e10
 
 
 
 
 
48d9c32
 
9766e10
48d9c32
9766e10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48d9c32
9766e10
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
import logging
from fastapi import Request, Response
from starlette.responses import JSONResponse
from app.core.constants import (
    REQUEST_ID_HEADER,
    SECURITY_HEADERS,
    UNAUTHORIZED_HEADERS
)
from app.core.context import request_id_ctx
import os

logger = logging.getLogger(__name__)

async def auth_middleware(request: Request, call_next) -> Response:
    if request.url.path in ["/", "/openapi.json"]:
        return await call_next(request)
    
    request_id = request_id_ctx.get('not-set')
    auth_header = request.headers.get("Authorization")
    if not auth_header or not auth_header.startswith("Bearer "):
        return JSONResponse(
            status_code=401, 
            content={"detail": "Unauthorized", "request_id": request_id},
            headers= {
                REQUEST_ID_HEADER: request_id,
                **SECURITY_HEADERS,
                **UNAUTHORIZED_HEADERS
            }
        )
    
    token = auth_header.split(" ")[1]
    if token != os.getenv("SERVER_AUTH"):
        return JSONResponse(
            status_code=401, 
            content={"detail": "Unauthorized", "request_id": request_id},
            headers= {
                REQUEST_ID_HEADER: request_id,
                **SECURITY_HEADERS,
                **UNAUTHORIZED_HEADERS
            }
        )

    return await call_next(request)