Add development-only user simulation using local file

This change introduces a fallback mechanism for development environments, allowing authentication to simulate a user from a local file named "user" when not found in the mock database. The file must include a username on the first line and a space-delimited list of pgroups on the second line. This enhancement helps streamline development workflows while maintaining error handling for missing or malformed files.
This commit is contained in:
GotthardG 2025-02-27 10:39:45 +01:00
parent e070fd4662
commit 7a9cc24e05

View File

@ -4,6 +4,7 @@ from fastapi.security import OAuth2AuthorizationCodeBearer
from app.schemas import loginToken, loginData
import jwt
import os
from datetime import datetime, timedelta, timezone
# Define an APIRouter for authentication
@ -83,6 +84,34 @@ async def login(form_data: OAuth2PasswordRequestForm = Depends()):
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
else:
# For development only: if the user is not in the mock db,
# then simulate authentication.
# Read the pgroups from the local file called "user" that lives only on
# your machine.
file_path = "user" # Adjust path as needed
if not os.path.exists(file_path):
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Development user file not found",
)
with open(file_path, "r") as f:
lines = f.read().splitlines()
if len(lines) < 2:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="User file must have at least two lines: "
"a username on the first and the list of pgroups on the second",
)
# The first line of the file is the username
file_username = lines[0].strip()
# The second line is the list of pgroups (space-delimited)
pgroups = lines[1].strip().split()
user = {
"username": file_username,
"pgroups": pgroups,
}
# Create token
access_token = create_access_token(