From 7a9cc24e057487658b293529d1a24571355c35a9 Mon Sep 17 00:00:00 2001 From: GotthardG <51994228+GotthardG@users.noreply.github.com> Date: Thu, 27 Feb 2025 10:39:45 +0100 Subject: [PATCH] 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. --- backend/app/routers/auth.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py index bbc9527..d3e2aa8 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -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(