diff --git a/backend/open_webui/models/chats.py b/backend/open_webui/models/chats.py index cadb5a3a79..5449d245d5 100644 --- a/backend/open_webui/models/chats.py +++ b/backend/open_webui/models/chats.py @@ -943,6 +943,16 @@ class ChatTable: return count + def count_chats_by_folder_id_and_user_id(self, folder_id: str, user_id: str) -> int: + with get_db() as db: + query = db.query(Chat).filter_by(user_id=user_id) + + query = query.filter_by(folder_id=folder_id) + count = query.count() + + log.info(f"Count of chats for folder '{folder_id}': {count}") + return count + def delete_tag_by_id_and_user_id_and_tag_name( self, id: str, user_id: str, tag_name: str ) -> bool: diff --git a/backend/open_webui/routers/folders.py b/backend/open_webui/routers/folders.py index 36dbfee5c5..ddee71ea4d 100644 --- a/backend/open_webui/routers/folders.py +++ b/backend/open_webui/routers/folders.py @@ -262,15 +262,15 @@ async def update_folder_is_expanded_by_id( async def delete_folder_by_id( request: Request, id: str, user=Depends(get_verified_user) ): - chat_delete_permission = has_permission( - user.id, "chat.delete", request.app.state.config.USER_PERMISSIONS - ) - - if user.role != "admin" and not chat_delete_permission: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail=ERROR_MESSAGES.ACCESS_PROHIBITED, + if Chats.count_chats_by_folder_id_and_user_id(id, user.id): + chat_delete_permission = has_permission( + user.id, "chat.delete", request.app.state.config.USER_PERMISSIONS ) + if user.role != "admin" and not chat_delete_permission: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=ERROR_MESSAGES.ACCESS_PROHIBITED, + ) folder = Folders.get_folder_by_id_and_user_id(id, user.id) if folder: