131 lines
4.9 KiB
Python
131 lines
4.9 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
from typing import List
|
|
|
|
from app.core.database import get_db
|
|
from app.core.security import get_password_hash
|
|
from app.models.models import User
|
|
from app.schemas.schemas import UserResponse, UserCreate, UserUpdate
|
|
from app.api.deps import get_current_user, require_admin
|
|
|
|
router = APIRouter(prefix="/users", tags=["Users Management"], dependencies=[Depends(require_admin)])
|
|
|
|
@router.get("", response_model=List[UserResponse])
|
|
async def list_users(db: AsyncSession = Depends(get_db)):
|
|
"""Lists all user accounts in the database."""
|
|
result = await db.execute(select(User).order_by(User.id.asc()))
|
|
users = result.scalars().all()
|
|
return users
|
|
|
|
@router.post("", response_model=UserResponse)
|
|
async def create_user(payload: UserCreate, db: AsyncSession = Depends(get_db)):
|
|
"""Creates a new user account (Local or RADIUS)."""
|
|
# Check if email already registered
|
|
email_clean = payload.email.strip().lower()
|
|
result = await db.execute(select(User).where(User.email == email_clean))
|
|
existing = result.scalar_one_or_none()
|
|
if existing:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Email address is already registered."
|
|
)
|
|
|
|
user = User(
|
|
email=email_clean,
|
|
hashed_password=get_password_hash(payload.password),
|
|
full_name=payload.full_name,
|
|
role=payload.role,
|
|
auth_source=payload.auth_source,
|
|
is_active=payload.is_active
|
|
)
|
|
db.add(user)
|
|
await db.commit()
|
|
await db.refresh(user)
|
|
return user
|
|
|
|
@router.put("/{user_id}", response_model=UserResponse)
|
|
async def update_user(user_id: int, payload: UserUpdate, db: AsyncSession = Depends(get_db)):
|
|
"""Updates an existing user account."""
|
|
result = await db.execute(select(User).where(User.id == user_id))
|
|
user = result.scalar_one_or_none()
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="User not found."
|
|
)
|
|
|
|
# Prevent changing email of default admin
|
|
if user.email == "admin@oneverdrive.local" and payload.email and payload.email.strip().lower() != user.email:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Email address of the default system administrator cannot be changed."
|
|
)
|
|
|
|
if payload.email is not None:
|
|
email_clean = payload.email.strip().lower()
|
|
if email_clean != user.email:
|
|
existing_res = await db.execute(select(User).where(User.email == email_clean))
|
|
if existing_res.scalar_one_or_none():
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Target email address is already in use."
|
|
)
|
|
user.email = email_clean
|
|
|
|
if payload.password is not None and payload.password != "":
|
|
user.hashed_password = get_password_hash(payload.password)
|
|
|
|
if payload.full_name is not None:
|
|
user.full_name = payload.full_name
|
|
|
|
if payload.role is not None:
|
|
# Prevent demoting the main admin
|
|
if user.email == "admin@oneverdrive.local" and payload.role != "ADMIN":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Default system administrator role cannot be demoted."
|
|
)
|
|
user.role = payload.role
|
|
|
|
if payload.is_active is not None:
|
|
# Prevent deactivating the main admin
|
|
if user.email == "admin@oneverdrive.local" and not payload.is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Default system administrator account cannot be deactivated."
|
|
)
|
|
user.is_active = payload.is_active
|
|
|
|
db.add(user)
|
|
await db.commit()
|
|
await db.refresh(user)
|
|
return user
|
|
|
|
@router.delete("/{user_id}")
|
|
async def delete_user(user_id: int, db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user)):
|
|
"""Deletes a user account from the system."""
|
|
if user_id == current_user.id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="You cannot delete your own account."
|
|
)
|
|
|
|
result = await db.execute(select(User).where(User.id == user_id))
|
|
user = result.scalar_one_or_none()
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="User not found."
|
|
)
|
|
|
|
if user.email == "admin@oneverdrive.local":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="The default system administrator account cannot be deleted."
|
|
)
|
|
|
|
await db.delete(user)
|
|
await db.commit()
|
|
return {"message": f"User account '{user.email}' deleted successfully."}
|