summaryrefslogtreecommitdiff
path: root/src/soc_collector/auth.py
diff options
context:
space:
mode:
Diffstat (limited to 'src/soc_collector/auth.py')
-rw-r--r--src/soc_collector/auth.py46
1 files changed, 46 insertions, 0 deletions
diff --git a/src/soc_collector/auth.py b/src/soc_collector/auth.py
new file mode 100644
index 0000000..4aacb52
--- /dev/null
+++ b/src/soc_collector/auth.py
@@ -0,0 +1,46 @@
+"""Auth module"""
+from typing import List
+from fastapi import Request, HTTPException
+
+
+def load_api_keys(path: str) -> List[str]:
+ """Load API keys from file
+
+ :param path: Path to API keys file.
+ :return: List[str]
+ """
+ keys: List[str] = []
+
+ with open(path, encoding="utf-8") as f_data:
+ key_file = f_data.readlines()
+
+ for line in key_file:
+ if line[0] == "#" or len(line) < 3:
+ continue
+
+ key = line.split(";")[0]
+ keys.append(key)
+
+ return keys
+
+
+def authorize_client(request: Request, api_keys: List[str]) -> None:
+ """Authorize a client request.
+
+ Parameters:
+ request (Request): The HTTP request.
+ api_keys (List[str]): List of accepted api_keys.
+
+ Raises HTTPException with status_code=401 if authorize fail.
+
+ Returns:
+ None
+ """
+
+ if "API-KEY" not in request.headers:
+ raise HTTPException(status_code=401, detail="API-KEY header missing")
+
+ request_key = request.headers["API-KEY"].strip()
+
+ if request_key not in api_keys:
+ raise HTTPException(status_code=401, detail="API-KEY header invalid")