88
99
1010class APIKeyBase (SecurityBase ):
11- pass
11+
12+ @staticmethod
13+ def check_api_key (api_key : str , auto_error : bool ) -> Optional [str ]:
14+ if not api_key :
15+ if auto_error :
16+ raise HTTPException (
17+ status_code = HTTP_403_FORBIDDEN , detail = "Not authenticated"
18+ )
19+ else :
20+ return None
21+ return api_key
1222
1323
1424class APIKeyQuery (APIKeyBase ):
@@ -21,14 +31,7 @@ def __init__(
2131
2232 async def __call__ (self , request : Request ) -> Optional [str ]:
2333 api_key : str = request .query_params .get (self .model .name )
24- if not api_key :
25- if self .auto_error :
26- raise HTTPException (
27- status_code = HTTP_403_FORBIDDEN , detail = "Not authenticated"
28- )
29- else :
30- return None
31- return api_key
34+ return self .check_api_key (api_key , self .auto_error )
3235
3336
3437class APIKeyHeader (APIKeyBase ):
@@ -41,14 +44,7 @@ def __init__(
4144
4245 async def __call__ (self , request : Request ) -> Optional [str ]:
4346 api_key : str = request .headers .get (self .model .name )
44- if not api_key :
45- if self .auto_error :
46- raise HTTPException (
47- status_code = HTTP_403_FORBIDDEN , detail = "Not authenticated"
48- )
49- else :
50- return None
51- return api_key
47+ return self .check_api_key (api_key , self .auto_error )
5248
5349
5450class APIKeyCookie (APIKeyBase ):
@@ -60,12 +56,5 @@ def __init__(
6056 self .auto_error = auto_error
6157
6258 async def __call__ (self , request : Request ) -> Optional [str ]:
63- api_key = request .cookies .get (self .model .name )
64- if not api_key :
65- if self .auto_error :
66- raise HTTPException (
67- status_code = HTTP_403_FORBIDDEN , detail = "Not authenticated"
68- )
69- else :
70- return None
71- return api_key
59+ api_key : str = request .cookies .get (self .model .name )
60+ return self .check_api_key (api_key , self .auto_error )
0 commit comments