172 lines
5.7 KiB
Python
172 lines
5.7 KiB
Python
from fastapi import APIRouter, HTTPException, Depends, Body, Path, Request
|
|
from typing import List, Dict, Any, Optional
|
|
from fastapi import status
|
|
from datetime import datetime
|
|
import logging
|
|
|
|
# Import auth module
|
|
import modules.security.auth as auth
|
|
|
|
# Import interfaces
|
|
import modules.interfaces.gatewayInterface as gatewayInterface
|
|
import modules.interfaces.gatewayModel as gatewayModel
|
|
|
|
# Configure logger
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Model attributes for User
|
|
userAttributes = gatewayModel.getModelAttributes(gatewayModel.User)
|
|
|
|
router = APIRouter(
|
|
prefix="/api/users",
|
|
tags=["Users"],
|
|
responses={404: {"description": "Not found"}}
|
|
)
|
|
|
|
@router.get("/", response_model=List[Dict[str, Any]], tags=["Users"])
|
|
async def get_users(currentUser: Dict[str, Any] = Depends(auth.getCurrentActiveUser)):
|
|
"""Get all users in the current mandate"""
|
|
try:
|
|
interfaceGateway = gatewayInterface.getInterface(currentUser)
|
|
return interfaceGateway.getUsers()
|
|
except Exception as e:
|
|
logger.error(f"Error getting users: {str(e)}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail=f"Failed to get users: {str(e)}"
|
|
)
|
|
|
|
@router.get("/{userId}", response_model=Dict[str, Any], tags=["Users"])
|
|
async def get_user(
|
|
userId: str,
|
|
currentUser: Dict[str, Any] = Depends(auth.getCurrentActiveUser)
|
|
):
|
|
"""Get a specific user by ID"""
|
|
try:
|
|
interfaceGateway = gatewayInterface.getInterface(currentUser)
|
|
user = interfaceGateway.getUserById(userId)
|
|
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"User {userId} not found"
|
|
)
|
|
|
|
return user
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"Error getting user {userId}: {str(e)}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail=f"Failed to get user: {str(e)}"
|
|
)
|
|
|
|
@router.post("/", response_model=gatewayModel.User, tags=["Users"])
|
|
async def create_user(
|
|
userData: gatewayModel.User,
|
|
currentUser: Dict[str, Any] = Depends(auth.getCurrentActiveUser)
|
|
):
|
|
"""Create a new user"""
|
|
try:
|
|
# Get admin user for user creation
|
|
interfaceRoot = auth.getRootInterface()
|
|
|
|
try:
|
|
# Convert User model to dict and pass to createUser
|
|
createdUser = interfaceRoot.createUser(
|
|
username=userData.username,
|
|
email=userData.email,
|
|
fullName=userData.fullName,
|
|
language=userData.language,
|
|
disabled=userData.disabled,
|
|
privilege=userData.privilege,
|
|
authenticationAuthority=userData.authenticationAuthority
|
|
)
|
|
except ValueError as e:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=str(e)
|
|
)
|
|
|
|
if not createdUser:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="Failed to create user"
|
|
)
|
|
|
|
return createdUser
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"Error creating user: {str(e)}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail=f"Failed to create user: {str(e)}"
|
|
)
|
|
|
|
@router.put("/{userId}", response_model=gatewayModel.User, tags=["Users"])
|
|
async def update_user(
|
|
userId: str,
|
|
userData: gatewayModel.User,
|
|
currentUser: Dict[str, Any] = Depends(auth.getCurrentActiveUser)
|
|
):
|
|
"""Update an existing user"""
|
|
try:
|
|
# Get admin user for user updates
|
|
interfaceRoot = auth.getRootInterface()
|
|
|
|
# Check if user exists
|
|
existingUser = interfaceRoot.getUserById(userId)
|
|
if not existingUser:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"User {userId} not found"
|
|
)
|
|
|
|
# Update user data
|
|
try:
|
|
updatedUser = interfaceRoot.updateUser(userId, userData)
|
|
except ValueError as e:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=str(e)
|
|
)
|
|
|
|
if not updatedUser:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="Failed to update user"
|
|
)
|
|
|
|
return updatedUser
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"Error updating user {userId}: {str(e)}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail=f"Failed to update user: {str(e)}"
|
|
)
|
|
|
|
@router.delete("/{userId}", response_model=Dict[str, Any], tags=["Users"])
|
|
async def delete_user(
|
|
userId: str,
|
|
currentUser: Dict[str, Any] = Depends(auth.getCurrentActiveUser)
|
|
):
|
|
"""Delete a user"""
|
|
try:
|
|
interfaceGateway = gatewayInterface.getInterface(currentUser)
|
|
interfaceGateway.deleteUser(userId)
|
|
return {"message": f"User {userId} deleted successfully"}
|
|
except ValueError as e:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=str(e)
|
|
)
|
|
except Exception as e:
|
|
logger.error(f"Error deleting user {userId}: {str(e)}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail=f"Failed to delete user: {str(e)}"
|
|
)
|