Skip to content

Commit 30b270b

Browse files
ShahriyarRsvlandeg
andauthored
♻️ Move duplicated code portion to a static method in the APIKeyBase super class (#3142)
Co-authored-by: Sofie Van Landeghem <[email protected]> Co-authored-by: svlandeg <[email protected]>
1 parent d5ecbac commit 30b270b

1 file changed

Lines changed: 12 additions & 25 deletions

File tree

fastapi/security/api_key.py

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,15 @@
99

1010

1111
class APIKeyBase(SecurityBase):
12-
pass
12+
@staticmethod
13+
def check_api_key(api_key: Optional[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+
return None
20+
return api_key
1321

1422

1523
class APIKeyQuery(APIKeyBase):
@@ -101,14 +109,7 @@ def __init__(
101109

102110
async def __call__(self, request: Request) -> Optional[str]:
103111
api_key = request.query_params.get(self.model.name)
104-
if not api_key:
105-
if self.auto_error:
106-
raise HTTPException(
107-
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
108-
)
109-
else:
110-
return None
111-
return api_key
112+
return self.check_api_key(api_key, self.auto_error)
112113

113114

114115
class APIKeyHeader(APIKeyBase):
@@ -196,14 +197,7 @@ def __init__(
196197

197198
async def __call__(self, request: Request) -> Optional[str]:
198199
api_key = request.headers.get(self.model.name)
199-
if not api_key:
200-
if self.auto_error:
201-
raise HTTPException(
202-
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
203-
)
204-
else:
205-
return None
206-
return api_key
200+
return self.check_api_key(api_key, self.auto_error)
207201

208202

209203
class APIKeyCookie(APIKeyBase):
@@ -291,11 +285,4 @@ def __init__(
291285

292286
async def __call__(self, request: Request) -> Optional[str]:
293287
api_key = request.cookies.get(self.model.name)
294-
if not api_key:
295-
if self.auto_error:
296-
raise HTTPException(
297-
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
298-
)
299-
else:
300-
return None
301-
return api_key
288+
return self.check_api_key(api_key, self.auto_error)

0 commit comments

Comments
 (0)