fix auth2

This commit is contained in:
ValueOn AG 2025-05-16 16:17:28 +02:00
parent ff63ebcb39
commit 57592562f4
2 changed files with 73 additions and 3 deletions

View file

@ -25,7 +25,7 @@ APP_TOKEN_EXPIRY=300
APP_ALLOWED_ORIGINS=http://localhost:8080,https://playground.poweron-center.net,http://localhost:5176,https://nyla.poweron-center.net
# Logging configuration
APP_LOGGING_LOG_LEVEL = WARNING
APP_LOGGING_LOG_LEVEL = INFO
APP_LOGGING_LOG_FILE = /home/poweron.log
APP_LOGGING_FORMAT = %(asctime)s - %(levelname)s - %(name)s - %(message)s
APP_LOGGING_DATE_FORMAT = %Y-%m-%d %H:%M:%S

View file

@ -80,7 +80,10 @@ async def registerUser(userData: dict = Body(...)):
rootMandateId = adminGateway.getInitialId("mandates")
adminUserId = adminGateway.getInitialId("users")
logger.info(f"Root mandate ID: {rootMandateId}, Admin user ID: {adminUserId}")
if not rootMandateId or not adminUserId:
logger.error("System initialization error: Missing root mandate or admin user")
raise HTTPException(
status_code=500,
detail="System is not properly initialized with root mandate and admin user"
@ -90,6 +93,7 @@ async def registerUser(userData: dict = Body(...)):
gateway = getGatewayInterface(rootMandateId, adminUserId)
if "username" not in userData or "password" not in userData:
logger.error("Missing required fields in registration data")
raise HTTPException(status_code=400, detail="Username and password required")
try:
@ -110,19 +114,82 @@ async def registerUser(userData: dict = Body(...)):
if "fullName" in userData and userData["fullName"]:
userCreateData["fullName"] = userData["fullName"]
logger.info(f"Attempting to create user with data: {userCreateData}")
# First check if user already exists
existingUser = gateway.getUserByUsername(userData["username"])
if existingUser:
logger.error(f"User {userData['username']} already exists")
raise HTTPException(
status_code=400,
detail=f"User {userData['username']} already exists"
)
# Create the user
newUser = gateway.createUser(**userCreateData)
logger.info(f"User created successfully: {newUser}")
# Wait a short moment to ensure database consistency
import time
time.sleep(0.5)
# Verify that the password was properly stored
createdUser = gateway.getUserByUsername(userData["username"])
if not createdUser or "hashedPassword" not in createdUser:
logger.info(f"Retrieved created user: {createdUser}")
if not createdUser:
logger.error("User creation verification failed: User not found after creation")
raise HTTPException(
status_code=500,
detail="Failed to verify user creation. Please try again."
)
if "hashedPassword" not in createdUser:
logger.error("User creation verification failed: Password not stored")
# If password wasn't stored, delete the user and raise an error
if createdUser:
logger.info(f"Attempting to delete user {createdUser['id']} due to missing password")
try:
gateway.deleteUser(createdUser["id"])
logger.info(f"Successfully deleted user {createdUser['id']} after password storage failure")
except Exception as deleteError:
logger.error(f"Failed to delete user after password storage failure: {str(deleteError)}")
raise HTTPException(
status_code=500,
detail="Failed to store password securely. Please try again."
)
# Final verification - try to authenticate the user
try:
authResult = gateway.authenticateUser(userData["username"], userData["password"])
if not authResult:
logger.error("Final verification failed: Could not authenticate newly created user")
# Delete the user if authentication fails
if createdUser:
try:
gateway.deleteUser(createdUser["id"])
logger.info(f"Successfully deleted user {createdUser['id']} after authentication failure")
except Exception as deleteError:
logger.error(f"Failed to delete user after authentication failure: {str(deleteError)}")
raise HTTPException(
status_code=500,
detail="Failed to verify user authentication. Please try again."
)
except Exception as authError:
logger.error(f"Authentication verification failed: {str(authError)}")
# Delete the user if authentication fails
if createdUser:
try:
gateway.deleteUser(createdUser["id"])
logger.info(f"Successfully deleted user {createdUser['id']} after authentication error")
except Exception as deleteError:
logger.error(f"Failed to delete user after authentication error: {str(deleteError)}")
raise HTTPException(
status_code=500,
detail="Failed to verify user authentication. Please try again."
)
logger.info("User registration completed successfully")
return newUser
except ValueError as e:
logger.error(f"ValueError in registration: {str(e)}")
@ -133,7 +200,10 @@ async def registerUser(userData: dict = Body(...)):
except Exception as e:
import traceback
logger.error(f"Unexpected error in registration: {str(e)}")
logger.error("Full traceback:")
logger.error(traceback.format_exc())
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Error args: {e.args}")
raise HTTPException(status_code=500, detail=f"Registration failed: {str(e)}")
@router.post("/register-with-msal", response_model=Dict[str, Any])