Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(users): add batch import and deletion

XZH3de25361eab2
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index f99b7c5cf..553ab4064 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -1,7 +1,9 @@
"""Auth router — login, logout, status, registration, profile, and user-management endpoints."""
from contextvars import Token as _CtxToken
+import csv
from datetime import datetime, timedelta, timezone
+import io
import logging
import re
@@ -19,7 +21,7 @@ from fastapi import (
status,
)
from fastapi.responses import FileResponse, HTMLResponse
-from pydantic import BaseModel, Field, field_validator
+from pydantic import BaseModel, Field, ValidationError, field_validator
from deeptutor.services.config import load_auth_settings
@@ -74,6 +76,9 @@ router = APIRouter()
_COOKIE_NAME = "dt_token"
_COOKIE_MAX_AGE = TOKEN_EXPIRE_HOURS * 3600
+_USER_IMPORT_MAX_BYTES = 2 * 1024 * 1024
+_USER_IMPORT_MAX_ROWS = 500
+_USER_BATCH_MAX_ROWS = 500
def _cookie_attrs() -> dict:
@@ -174,6 +179,26 @@ class AdminCreateUserRequest(RegisterRequest):
preset: AccountPreset = "standard"
+class AdminBatchDeleteRequest(BaseModel):
+ """Usernames for an admin-initiated batch deletion."""
+
+ usernames: list[str] = Field(min_length=1, max_length=_USER_BATCH_MAX_ROWS)
+
+ @field_validator("usernames")
+ @classmethod
+ def usernames_valid(cls, value: list[str]) -> list[str]:
+ usernames: list[str] = []
+ for raw_username in value:
+ username = raw_username.strip()
+ if not username:
+ raise ValueError("Usernames cannot be empty")
+ if username not in usernames:
+ usernames.append(username)
+ if not usernames:
+ raise ValueError("At least one username is required")
+ return usernames
+
+
class AuthStatusResponse(BaseModel):
"""Response body for the GET /status endpoint."""
@@ -1106,22 +1131,20 @@ async def put_learner_profile(
return {"learner_profile": updated}
[email protected]("/users", status_code=status.HTTP_201_CREATED)
-async def admin_create_user(
+def _validation_message(exc: ValidationError) -> str:
+ parts = []
+ for error in exc.errors():
+ location = ".".join(str(item) for item in error.get("loc", ()))
+ parts.append(f"{location or 'row'}: {error.get('msg', 'Invalid value')}")
+ return "; ".join(parts)
+
+
+def _create_admin_user(
body: AdminCreateUserRequest,
- current: TokenPayload = Depends(require_admin),
+ current: TokenPayload | None,
) -> dict:
- """Admin-only: create a new user account.
-
- Replaces the public ``/register`` flow once the first admin exists. The
- new account is always created with role=``user``; admins can promote
- later via ``PUT /users/{username}/role``.
- """
- if not AUTH_ENABLED:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Auth is disabled — user creation is not available.",
- )
+ """Create one ordinary account through the shared admin provision path."""
+ actor = current.username if current else "local"
if POCKETBASE_ENABLED:
if body.preset != "standard":
@@ -1135,10 +1158,7 @@ async def admin_create_user(
status_code=status.HTTP_409_CONFLICT,
detail="Failed to create user — username may already be taken.",
)
- logger.info(
- f"Admin '{current.username if current else 'local'}' created PocketBase user "
- f"'{body.username}'"
- )
+ logger.info("Admin '%s' created PocketBase user '%s'", actor, body.username)
return {
"ok": True,
"user_id": result.get("id", ""),
@@ -1148,23 +1168,25 @@ async def admin_create_user(
"preset": "standard",
}
- existing = {u["username"] for u in list_users()}
- if body.username in existing:
+ if any(item.get("username") == body.username for item in list_users()):
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken")
+
+ add_user(body.username, body.password, preset=body.preset)
+ created = next(
+ (item for item in list_users() if item.get("username") == body.username),
+ None,
+ )
+ user_id = str(created.get("id") or "") if created else ""
+ role = str(created.get("role") or "user") if created else "user"
+ preset = str(created.get("preset") or "standard") if created else "standard"
+
+ if role != "user":
+ delete_user(body.username)
raise HTTPException(
- status_code=status.HTTP_409_CONFLICT,
- detail="Username already taken",
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail="Only non-admin users can be provisioned by this endpoint.",
)
- add_user(body.username, body.password, preset=body.preset)
- user_id = ""
- role = "user"
- preset = "standard"
- for item in list_users():
- if item.get("username") == body.username:
- user_id = str(item.get("id") or "")
- role = str(item.get("role") or "user")
- preset = str(item.get("preset") or "standard")
- break
if preset == "learner":
from deeptutor.multi_user.grants import learner_grant, save_grant
@@ -1188,38 +1210,167 @@ async def admin_create_user(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="The learner preset could not be initialized.",
) from exc
+
logger.info(
- f"Admin '{current.username if current else 'local'}' created user '{body.username}' "
- f"(role={role!r}, preset={preset!r})"
+ "Admin '%s' created user '%s' (role=%r, preset=%r)",
+ actor,
+ body.username,
+ role,
+ preset,
)
return {
"ok": True,
"user_id": user_id,
"username": body.username,
"role": role,
- "is_admin": role == "admin",
+ "is_admin": False,
"preset": preset,
}
[email protected]("/users/{username}", status_code=status.HTTP_200_OK)
-async def remove_user(
- username: str,
[email protected]("/users", status_code=status.HTTP_201_CREATED)
+async def admin_create_user(
+ body: AdminCreateUserRequest,
current: TokenPayload = Depends(require_admin),
) -> dict:
- """Delete a user. Admins cannot delete their own account."""
- if current and username == current.username:
+ """Admin-only: create one ordinary user account."""
+ if not AUTH_ENABLED:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Auth is disabled — user creation is not available.",
+ )
+ return _create_admin_user(body, current)
+
+
[email protected]("/users/import")
+async def admin_import_users(
+ file: UploadFile = File(...),
+ current: TokenPayload = Depends(require_admin),
+) -> dict:
+ """Admin-only: provision ordinary users from a CSV file.
+
+ The response is row-oriented so one invalid record does not erase the
+ context of the valid records around it. Passwords are never returned.
+ """
+ if not AUTH_ENABLED:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
- detail="You cannot delete your own account",
+ detail="Auth is disabled — user import is not available.",
+ )
+
+ content = await file.read(_USER_IMPORT_MAX_BYTES + 1)
+ await file.close()
+ if len(content) > _USER_IMPORT_MAX_BYTES:
+ raise HTTPException(
+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
+ detail="User import file exceeds 2 MB.",
)
+ try:
+ text = content.decode("utf-8-sig")
+ except UnicodeDecodeError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="User import must be a UTF-8 CSV file.",
+ ) from exc
+
+ reader = csv.DictReader(io.StringIO(text, newline=""))
+ fieldnames = [str(name or "").strip().lower() for name in reader.fieldnames or []]
+ expected = ["username", "password", "preset"]
+ if fieldnames != expected:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail="CSV header must be exactly: username,password,preset",
+ )
+
+ parsed: list[tuple[int, AdminCreateUserRequest, str]] = []
+ results: list[dict] = []
+ rows = list(reader)
+ if not rows:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail="User import file contains no user rows.",
+ )
+ if len(rows) > _USER_IMPORT_MAX_ROWS:
+ raise HTTPException(
+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
+ detail=f"User import cannot exceed {_USER_IMPORT_MAX_ROWS} rows.",
+ )
+ for row_number, row in enumerate(rows, start=2):
+ username = str(row.get("username") or "").strip()
+ if row.get(None):
+ results.append(
+ {
+ "row": row_number,
+ "username": username[:100],
+ "ok": False,
+ "error": "Row has more values than the CSV header.",
+ }
+ )
+ continue
+ try:
+ body = AdminCreateUserRequest(
+ username=username,
+ password=str(row.get("password") or ""),
+ preset=str(row.get("preset") or "").strip() or "standard",
+ )
+ except ValidationError as exc:
+ results.append(
+ {
+ "row": row_number,
+ "username": username[:100],
+ "ok": False,
+ "error": _validation_message(exc),
+ }
+ )
+ continue
+ parsed.append((row_number, body, username[:100]))
+
+ for row_number, body, username in parsed:
+ try:
+ created = _create_admin_user(body, current)
+ except HTTPException as exc:
+ detail = exc.detail if isinstance(exc.detail, str) else "Failed to create user"
+ results.append({"row": row_number, "username": username, "ok": False, "error": detail})
+ except Exception:
+ logger.exception("Admin user import failed for row %s", row_number)
+ results.append(
+ {
+ "row": row_number,
+ "username": username,
+ "ok": False,
+ "error": "Failed to create user.",
+ }
+ )
+ else:
+ results.append({"row": row_number, "username": username, "ok": True, "user": created})
+
+ results.sort(key=lambda result: result["row"])
+ created_count = sum(1 for result in results if result["ok"])
+ failed_count = len(results) - created_count
+ logger.info(
+ "Admin '%s' imported users: %s created, %s failed",
+ current.username if current else "local",
+ created_count,
+ failed_count,
+ )
+ return {
+ "ok": failed_count == 0,
+ "created_count": created_count,
+ "failed_count": failed_count,
+ "results": results,
+ }
+
+
+def _delete_admin_user(username: str, current: TokenPayload | None) -> tuple[int, str]:
+ if current and username == current.username:
+ return 400, "You cannot delete your own account"
# Capture the id before the record disappears so the avatar file can go too.
info = get_user_info(username)
removed = delete_user(username)
if not removed:
- raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
+ return 404, "User not found"
user_id = str(info.get("id") or "") if info else ""
if user_id and _USER_ID_RE.match(user_id):
@@ -1227,10 +1378,50 @@ async def remove_user(
delete_avatar_file(user_id)
- logger.info(f"Admin '{current.username if current else 'local'}' deleted user '{username}'")
+ actor = current.username if current else "local"
+ logger.info("Admin '%s' deleted user '%s'", actor, username)
+ return 200, ""
+
+
[email protected]("/users/{username}", status_code=status.HTTP_200_OK)
+async def remove_user(
+ username: str,
+ current: TokenPayload = Depends(require_admin),
+) -> dict:
+ """Delete a user. Admins cannot delete their own account."""
+ status_code, detail = _delete_admin_user(username, current)
+ if status_code != 200:
+ raise HTTPException(status_code=status_code, detail=detail)
return {"ok": True}
[email protected]("/users/batch-delete")
+async def batch_remove_users(
+ body: AdminBatchDeleteRequest,
+ current: TokenPayload = Depends(require_admin),
+) -> dict:
+ """Delete selected users and report each outcome separately."""
+ results: list[dict] = []
+ for username in body.usernames:
+ _status_code, detail = _delete_admin_user(username, current)
+ results.append({"username": username, "ok": not detail, "error": detail or None})
+
+ deleted_count = sum(1 for result in results if result["ok"])
+ failed_count = len(results) - deleted_count
+ logger.info(
+ "Admin '%s' batch-deleted users: %s deleted, %s failed",
+ current.username if current else "local",
+ deleted_count,
+ failed_count,
+ )
+ return {
+ "ok": failed_count == 0,
+ "deleted_count": deleted_count,
+ "failed_count": failed_count,
+ "results": results,
+ }
+
+
@router.put("/users/{username}/role", status_code=status.HTTP_200_OK)
async def update_user_role(
username: str,
diff --git a/tests/multi_user/test_admin_user_batches.py b/tests/multi_user/test_admin_user_batches.py
new file mode 100644
index 000000000..1d5c61b41
--- /dev/null
+++ b/tests/multi_user/test_admin_user_batches.py
@@ -0,0 +1,176 @@
+"""Regression tests for admin batch user provisioning and deletion."""
+
+from __future__ import annotations
+
+import pytest
+
+
+def batch_client(mu_isolated_root, seed_user, monkeypatch):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ import deeptutor.api.routers.auth as auth_router
+ from deeptutor.services.auth import TokenPayload
+
+ admin = seed_user("root", role="admin")
+ tokens = {
+ "admin-token": TokenPayload(username="root", role="admin", user_id=admin["id"]),
+ "user-token": TokenPayload(username="alice", role="user", user_id="u_alice"),
+ }
+ monkeypatch.setattr(auth_router, "AUTH_ENABLED", True)
+ monkeypatch.setattr(auth_router, "POCKETBASE_ENABLED", False)
+ monkeypatch.setattr(auth_router, "decode_token", lambda token: tokens.get(token))
+
+ app = FastAPI()
+ app.include_router(auth_router.router, prefix="/api/auth")
+ return TestClient(app), {
+ "admin": {"Authorization": "Bearer admin-token"},
+ "user": {"Authorization": "Bearer user-token"},
+ }
+
+
+def test_import_reports_rows_and_creates_only_ordinary_users(batch_client):
+ client, headers = batch_client
+ csv_data = (
+ "username,password,preset\n"
+ "alice,alice-password-123,learner\n"
+ "bob,bob-password-123,standard\n"
+ "carol,carol-password-123,custom\n"
+ "alice,duplicate-password-123,standard\n"
+ "carol,short,standard\n"
+ )
+
+ response = client.post(
+ "/api/auth/users/import",
+ files={"file": ("users.csv", csv_data.encode("utf-8"), "text/csv")},
+ headers=headers["admin"],
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["created_count"] == 3
+ assert body["failed_count"] == 2
+ assert [result["ok"] for result in body["results"]] == [True, True, True, False, False], body
+ assert "Username already taken" in body["results"][3]["error"]
+ assert "Password must be at least 8 characters" in body["results"][4]["error"]
+ assert all(result["user"]["role"] == "user" for result in body["results"][:3])
+ assert all(result["user"]["is_admin"] is False for result in body["results"][:3])
+
+ users = {
+ item["username"]: item
+ for item in client.get("/api/auth/users", headers=headers["admin"]).json()
+ }
+ assert set(users) == {"root", "alice", "bob", "carol"}
+ assert users["alice"]["preset"] == "learner"
+ assert users["carol"]["preset"] == "custom"
+ assert all(item["role"] == "user" for name, item in users.items() if name != "root")
+
+
+def test_import_rejects_role_column_and_creates_nothing(batch_client):
+ client, headers = batch_client
+ csv_data = "username,password,preset,role\nalice,alice-password-123,standard,admin\n"
+
+ response = client.post(
+ "/api/auth/users/import",
+ files={"file": ("users.csv", csv_data.encode("utf-8"), "text/csv")},
+ headers=headers["admin"],
+ )
+
+ assert response.status_code == 422
+ assert response.json()["detail"] == "CSV header must be exactly: username,password,preset"
+ usernames = {
+ item["username"] for item in client.get("/api/auth/users", headers=headers["admin"]).json()
+ }
+ assert usernames == {"root"}
+
+
+def test_import_rolls_back_learner_when_grant_initialization_fails(batch_client, monkeypatch):
+ client, headers = batch_client
+ from deeptutor.multi_user import grants
+
+ def fail_save_grant(*args, **kwargs):
+ raise RuntimeError("grant initialization unavailable")
+
+ monkeypatch.setattr(grants, "save_grant", fail_save_grant)
+
+ response = client.post(
+ "/api/auth/users/import",
+ files={
+ "file": (
+ "users.csv",
+ b"username,password,preset\nalice,alice-password-123,learner\n",
+ "text/csv",
+ )
+ },
+ headers=headers["admin"],
+ )
+
+ assert response.status_code == 200
+ result = response.json()["results"][0]
+ assert result["ok"] is False
+ assert result["error"] == "The learner preset could not be initialized."
+ usernames = {
+ item["username"] for item in client.get("/api/auth/users", headers=headers["admin"]).json()
+ }
+ assert usernames == {"root"}
+
+
+def test_import_requires_admin(batch_client):
+ client, headers = batch_client
+
+ response = client.post(
+ "/api/auth/users/import",
+ files={
+ "file": (
+ "users.csv",
+ b"username,password,preset\nalice,alice-password-123,standard\n",
+ "text/csv",
+ )
+ },
+ headers=headers["user"],
+ )
+
+ assert response.status_code == 403
+
+
+def test_batch_delete_requires_admin(batch_client):
+ client, headers = batch_client
+
+ response = client.post(
+ "/api/auth/users/batch-delete",
+ json={"usernames": ["alice"]},
+ headers=headers["user"],
+ )
+
+ assert response.status_code == 403
+
+
+def test_batch_delete_reports_partial_results_and_protects_current_admin(batch_client, seed_user):
+ client, headers = batch_client
+ seed_user("alice")
+ seed_user("bob")
+
+ response = client.post(
+ "/api/auth/users/batch-delete",
+ json={"usernames": ["alice", "root", "missing", "bob"]},
+ headers=headers["admin"],
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body == {
+ "ok": False,
+ "deleted_count": 2,
+ "failed_count": 2,
+ "results": [
+ {"username": "alice", "ok": True, "error": None},
+ {"username": "root", "ok": False, "error": "You cannot delete your own account"},
+ {"username": "missing", "ok": False, "error": "User not found"},
+ {"username": "bob", "ok": True, "error": None},
+ ],
+ }
+ usernames = {
+ item["username"] for item in client.get("/api/auth/users", headers=headers["admin"]).json()
+ }
+ assert usernames == {"root"}
diff --git a/web/app/(admin)/admin/users/page.tsx b/web/app/(admin)/admin/users/page.tsx
index 475d2e148..de3c06756 100644
--- a/web/app/(admin)/admin/users/page.tsx
+++ b/web/app/(admin)/admin/users/page.tsx
@@ -5,12 +5,15 @@ import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { fetchAuthStatus } from "@/lib/auth";
import {
+ deleteUsers,
listUsers,
deleteUser,
setUserRole,
createUser,
+ importUsers,
type UserRecord,
type AccountPreset,
+ type UserImportResult,
} from "@/lib/admin-api";
import { GrantEditor } from "@/features/multi-user/components/GrantEditor";
import { BookPermissionEditor } from "@/features/multi-user/components/BookPermissionEditor";
@@ -28,6 +31,7 @@ import {
RefreshCw,
ArrowLeft,
SlidersHorizontal,
+ Upload,
UserPlus,
Users,
X,
@@ -58,7 +62,11 @@ export default function AdminUsersPage() {
const [actionError, setActionError] = useState("");
const [expandedUserId, setExpandedUserId] = useState<string | null>(null);
const [showCreateDialog, setShowCreateDialog] = useState(false);
+ const [showImportDialog, setShowImportDialog] = useState(false);
const [query, setQuery] = useState("");
+ const [selectedUsernames, setSelectedUsernames] = useState<string[]>([]);
+ const [showBatchDeleteConfirm, setShowBatchDeleteConfirm] = useState(false);
+ const [batchDeleteBusy, setBatchDeleteBusy] = useState(false);
const [confirmTarget, setConfirmTarget] = useState<{
kind: "delete" | "promote" | "demote";
user: UserRecord;
@@ -69,6 +77,10 @@ export default function AdminUsersPage() {
const [createPreset, setCreatePreset] = useState<AccountPreset>("standard");
const [createSubmitting, setCreateSubmitting] = useState(false);
const [createError, setCreateError] = useState("");
+ const [importFile, setImportFile] = useState<File | null>(null);
+ const [importSubmitting, setImportSubmitting] = useState(false);
+ const [importError, setImportError] = useState("");
+ const [importResult, setImportResult] = useState<UserImportResult | null>(null);
const load = useCallback(async () => {
setLoading(true);
@@ -106,6 +118,19 @@ export default function AdminUsersPage() {
setShowCreateDialog(true);
}
+ function openImportDialog() {
+ setImportFile(null);
+ setImportError("");
+ setImportResult(null);
+ setImportSubmitting(false);
+ setShowImportDialog(true);
+ }
+
+ function closeImportDialog() {
+ if (importSubmitting) return;
+ setShowImportDialog(false);
+ }
+
function closeCreateDialog() {
if (createSubmitting) return;
setShowCreateDialog(false);
@@ -176,6 +201,70 @@ export default function AdminUsersPage() {
}
}
+ async function handleImportSubmit(event: React.FormEvent) {
+ event.preventDefault();
+ if (importSubmitting) return;
+ if (!importFile) {
+ setImportError(t("Select a CSV file."));
+ return;
+ }
+ setImportSubmitting(true);
+ setImportError("");
+ try {
+ const result = await importUsers(importFile);
+ setImportResult(result);
+ await load();
+ } catch (e) {
+ setImportError(
+ e instanceof Error ? e.message : t("Failed to import users"),
+ );
+ } finally {
+ setImportSubmitting(false);
+ }
+ }
+
+ function toggleSelectedUsername(username: string) {
+ setSelectedUsernames((current) =>
+ current.includes(username)
+ ? current.filter((item) => item !== username)
+ : [...current, username],
+ );
+ }
+
+ async function handleBatchDeleteConfirm() {
+ if (batchDeleteBusy || selectedUsernames.length === 0) return;
+ setBatchDeleteBusy(true);
+ setActionError("");
+ try {
+ const result = await deleteUsers(selectedUsernames);
+ const failed = new Set(
+ result.results
+ .filter((item) => !item.ok)
+ .map((item) => item.username),
+ );
+ setSelectedUsernames((current) =>
+ current.filter((username) => failed.has(username)),
+ );
+ setShowBatchDeleteConfirm(false);
+ await load();
+ if (failed.size > 0) {
+ setActionError(
+ t("{{count}} users could not be deleted: {{users}}", {
+ count: failed.size,
+ users: [...failed].join(", "),
+ }),
+ );
+ }
+ } catch (e) {
+ setShowBatchDeleteConfirm(false);
+ setActionError(
+ e instanceof Error ? e.message : t("Failed to delete users"),
+ );
+ } finally {
+ setBatchDeleteBusy(false);
+ }
+ }
+
useEffect(() => {
if (!expandedUserId) return;
const expanded = users.find((user) => user.id === expandedUserId);
@@ -184,8 +273,26 @@ export default function AdminUsersPage() {
}
}, [expandedUserId, users]);
+ useEffect(() => {
+ if (selectedUsernames.length === 0) return;
+ const usernames = new Set(users.map((user) => user.username));
+ setSelectedUsernames((current) => {
+ const retained = current.filter((username) => usernames.has(username));
+ return retained.length === current.length ? current : retained;
+ });
+ }, [users, selectedUsernames]);
+
const normalizedQuery = query.trim().toLowerCase();
const filteredUsers = filterUsersByQuery(users, query);
+ const selectableFilteredUsers = filteredUsers.filter(
+ (user) => user.username !== currentUser,
+ );
+ const selectedUsernameSet = new Set(selectedUsernames);
+ const allFilteredSelected =
+ selectableFilteredUsers.length > 0 &&
+ selectableFilteredUsers.every((user) =>
+ selectedUsernameSet.has(user.username),
+ );
return (
<div className="h-screen overflow-y-auto bg-[var(--background)] px-4 py-10 [scrollbar-gutter:stable]">
@@ -218,6 +325,15 @@ export default function AdminUsersPage() {
<UserPlus size={14} />
{t("Add user")}
</button>
+ <button
+ onClick={openImportDialog}
+ className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm
+ border border-[var(--border)] text-[var(--foreground)]
+ hover:bg-[var(--card)] transition-colors"
+ >
+ <Upload size={14} />
+ {t("Import users")}
+ </button>
<button
onClick={load}
disabled={loading}
@@ -273,6 +389,29 @@ export default function AdminUsersPage() {
</div>
)}
+ {!loading && !error && selectedUsernames.length > 0 && (
+ <div className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-[var(--border)] bg-[var(--card)] px-4 py-3">
+ <span className="text-sm text-[var(--muted-foreground)]">
+ {t("{{count}} users selected", { count: selectedUsernames.length })}
+ </span>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => setSelectedUsernames([])}
+ className="rounded-lg px-3 py-1.5 text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)] transition-colors"
+ >
+ {t("Clear selection")}
+ </button>
+ <button
+ onClick={() => setShowBatchDeleteConfirm(true)}
+ className="flex items-center gap-1.5 rounded-lg border border-red-500/40 px-3 py-1.5 text-sm text-red-600 hover:bg-red-500/10 transition-colors dark:text-red-400"
+ >
+ <Trash2 size={14} />
+ {t("Delete selected")}
+ </button>
+ </div>
+ </div>
+ )}
+
<div className="rounded-2xl border border-[var(--border)] bg-[var(--card)] overflow-hidden shadow-sm">
{loading ? (
<div className="divide-y divide-[var(--border)]" aria-hidden>
@@ -340,6 +479,30 @@ export default function AdminUsersPage() {
<table className="w-full text-sm">
<thead>
<tr className="border-b border-[var(--border)] text-left text-xs text-[var(--muted-foreground)] uppercase tracking-wider">
+ <th className="w-12 px-5 py-3">
+ <input
+ type="checkbox"
+ checked={allFilteredSelected}
+ disabled={selectableFilteredUsers.length === 0}
+ onChange={() => {
+ const displayed = new Set(
+ selectableFilteredUsers.map((user) => user.username),
+ );
+ setSelectedUsernames((current) =>
+ allFilteredSelected
+ ? current.filter((username) => !displayed.has(username))
+ : [
+ ...current,
+ ...selectableFilteredUsers
+ .map((user) => user.username)
+ .filter((username) => !current.includes(username)),
+ ],
+ );
+ }}
+ aria-label={t("Select displayed users")}
+ className="h-4 w-4 rounded border-[var(--border)] accent-[var(--foreground)]"
+ />
+ </th>
<th className="px-5 py-3 font-medium">{t("Username")}</th>
<th className="px-5 py-3 font-medium">{t("Role")}</th>
<th className="px-5 py-3 font-medium">{t("Joined")}</th>
@@ -356,6 +519,18 @@ export default function AdminUsersPage() {
return (
<Fragment key={user.username}>
<tr className="group hover:bg-[var(--background)]/50 transition-colors">
+ <td className="px-5 py-3.5">
+ <input
+ type="checkbox"
+ checked={selectedUsernameSet.has(user.username)}
+ disabled={isSelf}
+ onChange={() => toggleSelectedUsername(user.username)}
+ aria-label={t("Select {{username}}", {
+ username: user.username,
+ })}
+ className="h-4 w-4 rounded border-[var(--border)] accent-[var(--foreground)] disabled:opacity-30"
+ />
+ </td>
<td className="px-5 py-3">
<div className="flex items-center gap-3">
<UserAvatar
@@ -471,7 +646,7 @@ export default function AdminUsersPage() {
</tr>
{canManageAssignments && expandedUserId === user.id && (
<tr>
- <td colSpan={4} className="p-0">
+ <td colSpan={5} className="p-0">
<GrantEditor
key={user.id}
userId={user.id}
@@ -576,6 +751,31 @@ export default function AdminUsersPage() {
)}
</ConfirmDialog>
+ <ConfirmDialog
+ open={showBatchDeleteConfirm}
+ title={t("Delete users")}
+ tone="danger"
+ confirmLabel={t("Delete users")}
+ busyLabel={t("Deleting…")}
+ busy={batchDeleteBusy}
+ onConfirm={handleBatchDeleteConfirm}
+ onCancel={() => setShowBatchDeleteConfirm(false)}
+ >
+ <p>
+ {t(
+ "This permanently removes {{count}} accounts and their assignments. This cannot be undone.",
+ { count: selectedUsernames.length },
+ )}
+ </p>
+ <ul className="mt-3 max-h-40 space-y-1 overflow-y-auto text-sm text-[var(--muted-foreground)]">
+ {selectedUsernames.map((username) => (
+ <li key={username} className="truncate">
+ {username}
+ </li>
+ ))}
+ </ul>
+ </ConfirmDialog>
+
{showCreateDialog && (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-[var(--overlay)] px-4"
@@ -699,6 +899,111 @@ export default function AdminUsersPage() {
</form>
</div>
)}
+
+ {showImportDialog && (
+ <div
+ className="fixed inset-0 z-50 flex items-center justify-center bg-[var(--overlay)] px-4"
+ role="dialog"
+ aria-modal="true"
+ onClick={closeImportDialog}
+ >
+ <form
+ onClick={(e) => e.stopPropagation()}
+ onSubmit={handleImportSubmit}
+ className="max-h-[85vh] w-full max-w-md overflow-y-auto rounded-2xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-xl"
+ >
+ <div className="mb-4 flex items-center justify-between">
+ <h2 className="text-base font-semibold text-[var(--foreground)]">
+ {t("Import users")}
+ </h2>
+ <button
+ type="button"
+ onClick={closeImportDialog}
+ disabled={importSubmitting}
+ className="rounded-md p-1 text-[var(--muted-foreground)] hover:bg-[var(--background)] hover:text-[var(--foreground)] disabled:opacity-40"
+ aria-label={t("Close")}
+ >
+ <X size={16} />
+ </button>
+ </div>
+
+ <label className="mb-3 block text-xs text-[var(--muted-foreground)]">
+ {t("CSV file")}
+ <input
+ type="file"
+ accept=".csv,text/csv"
+ onChange={(e) => {
+ setImportFile(e.target.files?.[0] ?? null);
+ setImportResult(null);
+ setImportError("");
+ }}
+ disabled={importSubmitting}
+ autoFocus
+ className="mt-1 w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
+ />
+ </label>
+
+ <p className="mb-3 text-[11px] leading-relaxed text-[var(--muted-foreground)]">
+ {t("Header: username,password,preset. Only ordinary user accounts can be imported.")}
+ </p>
+
+ {importError && (
+ <p className="mb-3 text-xs text-red-500">{importError}</p>
+ )}
+
+ {importResult && (
+ <div className="mb-4">
+ <p className="text-sm font-medium text-[var(--foreground)]">
+ {t("{{created}} created, {{failed}} failed", {
+ created: importResult.created_count,
+ failed: importResult.failed_count,
+ })}
+ </p>
+ <ul className="mt-2 max-h-44 space-y-1 overflow-y-auto text-xs text-[var(--muted-foreground)]">
+ {importResult.results.map((result) => (
+ <li
+ key={`${result.row}-${result.username}`}
+ className="flex items-start justify-between gap-3"
+ >
+ <span className="min-w-0 truncate">
+ {t("Row {{row}}", { row: result.row })} · {result.username}
+ </span>
+ <span
+ className={
+ result.ok
+ ? "shrink-0 text-emerald-600 dark:text-emerald-400"
+ : "shrink-0 text-red-500"
+ }
+ >
+ {result.ok ? t("Created") : result.error}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ <div className="flex items-center justify-end gap-2">
+ <button
+ type="button"
+ onClick={closeImportDialog}
+ disabled={importSubmitting}
+ className="rounded-lg px-3 py-1.5 text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)] disabled:opacity-40"
+ >
+ {t("Close")}
+ </button>
+ <button
+ type="submit"
+ disabled={importSubmitting || !importFile}
+ className="flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-sm font-medium text-[var(--background)] hover:opacity-90 disabled:opacity-40"
+ >
+ <Upload size={14} />
+ {importSubmitting ? t("Importing…") : t("Import")}
+ </button>
+ </div>
+ </form>
+ </div>
+ )}
</div>
);
}
diff --git a/web/lib/admin-api.ts b/web/lib/admin-api.ts
index e0a12ed5d..0480beac5 100644
--- a/web/lib/admin-api.ts
+++ b/web/lib/admin-api.ts
@@ -81,6 +81,65 @@ export async function deleteUser(username: string): Promise<void> {
}
}
+export interface UserBatchResult {
+ row?: number;
+ username: string;
+ ok: boolean;
+ error?: string | null;
+ user?: CreatedUser;
+}
+
+export interface UserImportResult {
+ ok: boolean;
+ created_count: number;
+ failed_count: number;
+ results: UserBatchResult[];
+}
+
+export interface UserBatchDeleteResult {
+ ok: boolean;
+ deleted_count: number;
+ failed_count: number;
+ results: Omit<UserBatchResult, "row">[];
+}
+
+export async function importUsers(file: File): Promise<UserImportResult> {
+ const body = new FormData();
+ body.append("file", file);
+ const res = await apiFetch(apiUrl("/api/auth/users/import"), {
+ method: "POST",
+ body,
+ });
+ if (!res.ok) {
+ const data = (await res.json().catch(() => ({}))) as { detail?: unknown };
+ throw new Error(
+ typeof data.detail === "string"
+ ? data.detail
+ : "Failed to import users",
+ );
+ }
+ return (await res.json()) as UserImportResult;
+}
+
+export async function deleteUsers(
+ usernames: string[],
+): Promise<UserBatchDeleteResult> {
+ const res = await apiFetch(apiUrl("/api/auth/users/batch-delete"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ usernames }),
+ });
+ if (!res.ok) {
+ const data = (await res.json().catch(() => ({}))) as { detail?: unknown };
+ throw new Error(
+ typeof data.detail === "string"
+ ? data.detail
+ : "Failed to delete users",
+ );
+ }
+ return (await res.json()) as UserBatchDeleteResult;
+}
+
export async function setUserRole(
username: string,
role: "admin" | "user",
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 8a91940f4..fa504e9bc 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2405,11 +2405,26 @@
"User Management": "User Management",
"Manage registered accounts": "Manage registered accounts",
"Add user": "Add user",
+ "Import users": "Import users",
+ "CSV file": "CSV file",
+ "Header: username,password,preset. Only ordinary user accounts can be imported.": "Header: username,password,preset. Only ordinary user accounts can be imported.",
+ "Select a CSV file.": "Select a CSV file.",
+ "{{created}} created, {{failed}} failed": "{{created}} created, {{failed}} failed",
+ "Row {{row}}": "Row {{row}}",
+ "Created": "Created",
+ "Import": "Import",
+ "Importing…": "Importing…",
+ "Failed to import users": "Failed to import users",
"Search users…": "Search users…",
"Search users": "Search users",
"{{filtered}} of {{total}}": "{{filtered}} of {{total}}",
"{{count}} user": "{{count}} user",
"{{count}} users": "{{count}} users",
+ "{{count}} users selected": "{{count}} users selected",
+ "Clear selection": "Clear selection",
+ "Delete selected": "Delete selected",
+ "Select displayed users": "Select displayed users",
+ "Select {{username}}": "Select {{username}}",
"No users yet": "No users yet",
"Accounts you create will appear here.": "Accounts you create will appear here.",
"No users match “{{query}}”": "No users match “{{query}}”",
@@ -2426,6 +2441,7 @@
"Delete {{username}}": "Delete {{username}}",
"DeepTutor Admin · User Management": "DeepTutor Admin · User Management",
"Delete user": "Delete user",
+ "Delete users": "Delete users",
"Promote": "Promote",
"Demote": "Demote",
"Deleting…": "Deleting…",
@@ -2433,6 +2449,7 @@
"Demoting…": "Demoting…",
"{{role}} · joined {{date}}": "{{role}} · joined {{date}}",
"This permanently removes the account and its assignments. This cannot be undone.": "This permanently removes the account and its assignments. This cannot be undone.",
+ "This permanently removes {{count}} accounts and their assignments. This cannot be undone.": "This permanently removes {{count}} accounts and their assignments. This cannot be undone.",
"Admins can manage users and assignments, and work in the shared main workspace.": "Admins can manage users and assignments, and work in the shared main workspace.",
"They will lose access to the admin area and switch to their own assigned workspace.": "They will lose access to the admin area and switch to their own assigned workspace.",
"Username (or email)": "Username (or email)",
@@ -2442,6 +2459,8 @@
"Failed to load users": "Failed to load users",
"Failed to create user": "Failed to create user",
"Failed to delete user": "Failed to delete user",
+ "Failed to delete users": "Failed to delete users",
+ "{{count}} users could not be deleted: {{users}}": "{{count}} users could not be deleted: {{users}}",
"Failed to update role": "Failed to update role",
"My profile": "My profile",
"View your account and personalize your avatar": "View your account and personalize your avatar",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index d44038055..e2d7af0cc 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2405,11 +2405,26 @@
"User Management": "用户管理",
"Manage registered accounts": "管理已注册账户",
"Add user": "添加用户",
+ "Import users": "导入用户",
+ "CSV file": "CSV 文件",
+ "Header: username,password,preset. Only ordinary user accounts can be imported.": "表头:username,password,preset。只能导入普通用户账号。",
+ "Select a CSV file.": "请选择 CSV 文件。",
+ "{{created}} created, {{failed}} failed": "已创建 {{created}} 个,失败 {{failed}} 个",
+ "Row {{row}}": "第 {{row}} 行",
+ "Created": "已创建",
+ "Import": "导入",
+ "Importing…": "正在导入…",
+ "Failed to import users": "导入用户失败",
"Search users…": "搜索用户…",
"Search users": "搜索用户",
"{{filtered}} of {{total}}": "{{filtered}} / {{total}}",
"{{count}} user": "{{count}} 位用户",
"{{count}} users": "{{count}} 位用户",
+ "{{count}} users selected": "已选择 {{count}} 位用户",
+ "Clear selection": "清除选择",
+ "Delete selected": "删除所选",
+ "Select displayed users": "选择当前显示的用户",
+ "Select {{username}}": "选择 {{username}}",
"No users yet": "暂无用户",
"Accounts you create will appear here.": "你创建的账户将显示在这里。",
"No users match “{{query}}”": "没有与“{{query}}”匹配的用户",
@@ -2426,6 +2441,7 @@
"Delete {{username}}": "删除 {{username}}",
"DeepTutor Admin · User Management": "DeepTutor 管理后台 · 用户管理",
"Delete user": "删除用户",
+ "Delete users": "删除用户",
"Promote": "提升",
"Demote": "降级",
"Deleting…": "正在删除…",
@@ -2433,6 +2449,7 @@
"Demoting…": "正在降级…",
"{{role}} · joined {{date}}": "{{role}} · 注册于 {{date}}",
"This permanently removes the account and its assignments. This cannot be undone.": "这将永久删除该账户及其分配,且无法撤销。",
+ "This permanently removes {{count}} accounts and their assignments. This cannot be undone.": "这将永久删除 {{count}} 个账户及其分配,且无法撤销。",
"Admins can manage users and assignments, and work in the shared main workspace.": "管理员可以管理用户和分配,并在共享的主工作区中操作。",
"They will lose access to the admin area and switch to their own assigned workspace.": "该用户将无法再访问管理区域,并切换到分配给自己的工作区。",
"Username (or email)": "用户名(或邮箱)",
@@ -2442,6 +2459,8 @@
"Failed to load users": "加载用户失败",
"Failed to create user": "创建用户失败",
"Failed to delete user": "删除用户失败",
+ "Failed to delete users": "删除用户失败",
+ "{{count}} users could not be deleted: {{users}}": "有 {{count}} 位用户未能删除:{{users}}",
"Failed to update role": "更新角色失败",
"My profile": "个人资料",
"View your account and personalize your avatar": "查看账户信息并个性化你的头像",
diff --git a/web/tests/admin-user-batches.test.ts b/web/tests/admin-user-batches.test.ts
new file mode 100644
index 000000000..4477d8fae
--- /dev/null
+++ b/web/tests/admin-user-batches.test.ts
@@ -0,0 +1,65 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+
+const adminApi = readFileSync(
+ path.resolve(process.cwd(), "lib/admin-api.ts"),
+ "utf8",
+);
+const usersPage = readFileSync(
+ path.resolve(process.cwd(), "app/(admin)/admin/users/page.tsx"),
+ "utf8",
+);
+const authRouter = readFileSync(
+ path.resolve(process.cwd(), "..", "deeptutor", "api", "routers", "auth.py"),
+ "utf8",
+);
+const en = JSON.parse(
+ readFileSync(path.resolve(process.cwd(), "locales/en/app.json"), "utf8"),
+) as Record<string, string>;
+const zh = JSON.parse(
+ readFileSync(path.resolve(process.cwd(), "locales/zh/app.json"), "utf8"),
+) as Record<string, string>;
+
+test("admin API exposes row-oriented user import and batch deletion", () => {
+ assert.match(adminApi, /apiUrl\("\/api\/auth\/users\/import"\)/);
+ assert.match(adminApi, /body\.append\("file", file\)/);
+ assert.match(adminApi, /interface UserImportResult/);
+ assert.match(adminApi, /apiUrl\("\/api\/auth\/users\/batch-delete"\)/);
+ assert.match(adminApi, /JSON\.stringify\(\{ usernames \}\)/);
+});
+
+test("users page wires CSV import and multi-select deletion", () => {
+ assert.match(usersPage, /showImportDialog/);
+ assert.match(usersPage, /accept="\.csv,text\/csv"/);
+ assert.match(usersPage, /type="checkbox"/);
+ assert.match(usersPage, /disabled=\{isSelf\}/);
+ assert.match(usersPage, /setShowBatchDeleteConfirm\(true\)/);
+ assert.match(usersPage, /colSpan=\{5\}/);
+});
+
+test("batch import cannot provision administrators", () => {
+ assert.match(authRouter, /fieldnames != expected/);
+ assert.match(authRouter, /if role != "user":/);
+ assert.match(authRouter, /Only non-admin users can be provisioned/);
+});
+
+test("batch user copy is present in both supported locales", () => {
+ const keys = [
+ "Import users",
+ "CSV file",
+ "{{count}} users selected",
+ "Delete selected",
+ "Delete users",
+ "{{created}} created, {{failed}} failed",
+ "Failed to import users",
+ "Failed to delete users",
+ ];
+ for (const key of keys) {
+ assert.ok(key in en, `missing English key: ${key}`);
+ assert.ok(key in zh, `missing Chinese key: ${key}`);
+ assert.notEqual(en[key], "");
+ assert.notEqual(zh[key], "");
+ }
+});