7
7
from typing import Annotated , AsyncIterator
8
8
9
9
from elasticsearch_dsl import Q , Search
10
- from fastapi import Depends , HTTPException , Query
11
- from fastapi .security import OAuth2PasswordBearer
10
+ from fastapi import Depends , HTTPException , Query , Request
11
+ from fastapi .security import HTTPBearer
12
12
from httpx import AsyncClient , HTTPStatusError
13
13
from openai import AsyncOpenAI
14
14
from pydantic import constr
27
27
28
28
journal_constraints = constr (pattern = r"^\d{4}-\d{3}[0-9X]$" )
29
29
30
- auth = OAuth2PasswordBearer (
31
- tokenUrl = "/token" , # Will be overriden
32
- auto_error = False ,
33
- )
30
+
31
+ class HTTPBearerDirect (HTTPBearer ):
32
+ """HTTPBearer class that returns directly the token in the call."""
33
+
34
+ async def __call__ (self , request : Request ) -> str | None : # type: ignore
35
+ """Intercept the bearer token in the headers."""
36
+ auth_credentials = await super ().__call__ (request )
37
+ return auth_credentials .credentials if auth_credentials else None
38
+
39
+
40
+ auth = HTTPBearerDirect (auto_error = False )
34
41
35
42
36
43
@cache
@@ -55,24 +62,30 @@ async def get_httpx_client(
55
62
56
63
57
64
async def get_user_id (
58
- token : Annotated [str | None , Depends (auth )],
65
+ request : Request ,
66
+ token : Annotated [str , Depends (auth )],
59
67
settings : Annotated [Settings , Depends (get_settings )],
60
68
httpx_client : Annotated [AsyncClient , Depends (get_httpx_client )],
61
69
) -> str :
62
70
"""Validate JWT token and returns user ID."""
63
- if settings .keycloak .validate_token and settings .keycloak .user_info_endpoint :
64
- try :
65
- response = await httpx_client .get (
66
- settings .keycloak .user_info_endpoint ,
67
- headers = {"Authorization" : f"Bearer { token } " },
68
- )
69
- response .raise_for_status ()
70
- user_info = response .json ()
71
- return user_info ["sub" ]
72
- except HTTPStatusError :
73
- raise HTTPException (
74
- status_code = HTTP_401_UNAUTHORIZED , detail = "Invalid token."
75
- )
71
+ if hasattr (request .state , "sub" ):
72
+ return request .state .sub
73
+ if settings .keycloak .validate_token :
74
+ if settings .keycloak .user_info_endpoint :
75
+ try :
76
+ response = await httpx_client .get (
77
+ settings .keycloak .user_info_endpoint ,
78
+ headers = {"Authorization" : f"Bearer { token } " },
79
+ )
80
+ response .raise_for_status ()
81
+ user_info = response .json ()
82
+ return user_info ["sub" ]
83
+ except HTTPStatusError :
84
+ raise HTTPException (
85
+ status_code = HTTP_401_UNAUTHORIZED , detail = "Invalid token."
86
+ )
87
+ else :
88
+ raise HTTPException (status_code = 404 , detail = "user info url not provided." )
76
89
else :
77
90
return "dev"
78
91
0 commit comments