8
8
9
9
10
10
class 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
12
22
13
23
14
24
class APIKeyQuery (APIKeyBase ):
@@ -21,14 +31,7 @@ def __init__(
21
31
22
32
async def __call__ (self , request : Request ) -> Optional [str ]:
23
33
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 )
32
35
33
36
34
37
class APIKeyHeader (APIKeyBase ):
@@ -41,14 +44,7 @@ def __init__(
41
44
42
45
async def __call__ (self , request : Request ) -> Optional [str ]:
43
46
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 )
52
48
53
49
54
50
class APIKeyCookie (APIKeyBase ):
@@ -60,12 +56,5 @@ def __init__(
60
56
self .auto_error = auto_error
61
57
62
58
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