diff --git a/backend/database/user_manager.py b/backend/database/user_manager.py index 693fc64..99da1ab 100644 --- a/backend/database/user_manager.py +++ b/backend/database/user_manager.py @@ -247,3 +247,19 @@ def update_user_requires_password_update( self.db_session.commit() self.db_session.refresh(db_user) return db_user + + def delete_user_by_username(self, username: str) -> User: + """ + Delete a user based on their username. + + Args: + username (str): The username of the user. + + Returns: + User: The deleted User object if found, else None. + """ + db_user = self.db_session.query(User).filter(User.username == username).first() + if db_user: + self.db_session.delete(db_user) + self.db_session.commit() + return db_user diff --git a/backend/models/user.py b/backend/models/user.py index ffe1b22..6024545 100644 --- a/backend/models/user.py +++ b/backend/models/user.py @@ -162,6 +162,10 @@ class ForgotPasswordRequest(BaseModel): email: EmailStr +class DeleteUserRequest(BaseModel): + username: str + + class ResetPasswordRequest(BaseModel): token: str = Field(...) new_password: str = Field(...) diff --git a/backend/routes/user_routes.py b/backend/routes/user_routes.py index 6153199..fd1ecda 100644 --- a/backend/routes/user_routes.py +++ b/backend/routes/user_routes.py @@ -4,6 +4,7 @@ from models.user import ( ChangePasswordRequest, + DeleteUserRequest, ForgotPasswordRequest, ResetPasswordRequest, SendVerificationEmailRequest, @@ -212,3 +213,20 @@ async def verify_email(request: VerifyEmailRequest): @user_router.get("/users/is-email-verified/") async def is_user_verified(current_user: User = Depends(get_current_user)): return {"email_verified": current_user.email_verified} + + +@user_router.delete("/users/delete/") +async def delete_user( + request: DeleteUserRequest, + current_admin_user: User = Depends(get_current_admin_user), +): + with DatabaseManager() as session: + user_manager = UserManager(session) + + # Delete user + deleted_user = user_manager.delete_user_by_username(request.username) + + if not deleted_user: + raise HTTPException(status_code=404, detail="User not found") + + return {"message": f"Successfully deleted user {request.username}."} diff --git a/frontend/src/pages/admin/UserManagement.jsx b/frontend/src/pages/admin/UserManagement.jsx index 4392c9a..152ad95 100644 --- a/frontend/src/pages/admin/UserManagement.jsx +++ b/frontend/src/pages/admin/UserManagement.jsx @@ -18,6 +18,19 @@ function UserManagement() { } }; + const handleDeleteUser = async () => { + try { + await axios.delete(`${API_URL}users/delete/`, { + data: {username: selectedUser.username} + }); + // Refetch users after deletion + const response = await axios.get(`${API_URL}users/`); + setUsers(response.data); + } catch (error) { + console.error('Error deleting user', error); + } + }; + const fetchRoles = async () => { try { const response = await axios.get(`${API_URL}users/roles/`); @@ -155,6 +168,7 @@ function UserManagement() { +