]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
♻️ Move duplicated code portion to a static method in the `APIKeyBase` super class...
authorShahriyar Rzayev <rzayev.sehriyar@gmail.com>
Thu, 30 Jan 2025 12:17:20 +0000 (13:17 +0100)
committerGitHub <noreply@github.com>
Thu, 30 Jan 2025 12:17:20 +0000 (12:17 +0000)
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: svlandeg <svlandeg@github.com>
fastapi/security/api_key.py

index d68bdb037ee4e8c88ebf2bd6e43ddffedc5dcc49..70c2dca8a81fea5620185374ce22ba77c356027f 100644 (file)
@@ -9,7 +9,15 @@ from typing_extensions import Annotated, Doc
 
 
 class APIKeyBase(SecurityBase):
-    pass
+    @staticmethod
+    def check_api_key(api_key: Optional[str], auto_error: bool) -> Optional[str]:
+        if not api_key:
+            if auto_error:
+                raise HTTPException(
+                    status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
+                )
+            return None
+        return api_key
 
 
 class APIKeyQuery(APIKeyBase):
@@ -101,14 +109,7 @@ class APIKeyQuery(APIKeyBase):
 
     async def __call__(self, request: Request) -> Optional[str]:
         api_key = request.query_params.get(self.model.name)
-        if not api_key:
-            if self.auto_error:
-                raise HTTPException(
-                    status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
-                )
-            else:
-                return None
-        return api_key
+        return self.check_api_key(api_key, self.auto_error)
 
 
 class APIKeyHeader(APIKeyBase):
@@ -196,14 +197,7 @@ class APIKeyHeader(APIKeyBase):
 
     async def __call__(self, request: Request) -> Optional[str]:
         api_key = request.headers.get(self.model.name)
-        if not api_key:
-            if self.auto_error:
-                raise HTTPException(
-                    status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
-                )
-            else:
-                return None
-        return api_key
+        return self.check_api_key(api_key, self.auto_error)
 
 
 class APIKeyCookie(APIKeyBase):
@@ -291,11 +285,4 @@ class APIKeyCookie(APIKeyBase):
 
     async def __call__(self, request: Request) -> Optional[str]:
         api_key = request.cookies.get(self.model.name)
-        if not api_key:
-            if self.auto_error:
-                raise HTTPException(
-                    status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
-                )
-            else:
-                return None
-        return api_key
+        return self.check_api_key(api_key, self.auto_error)