feat: add admin area with item CRUD, Lexical editor and access control (M6)
Backend: - Item model (title, url, points, username, content, created_at) - is_admin flag on User + startup migration for pre-existing DBs - get_current_admin dependency (401 without/invalid token, 403 for non-admins); server-side check on every admin endpoint - /api/v1/admin/items CRUD: pagination, case-insensitive title/url search, sort by title/created_at/points, in-memory rate limiting (1000 req/60s per admin -> 429) - seed_admin.py (ADMIN_USERNAME/ADMIN_PASSWORD), documented in backend/.env.example Frontend: - Auth context exposes is_admin; RequireAdmin route guard (redirects signed-out users, renders 403 page for non-admins) - AdminLayout with responsive dark sidebar; Admin link in header for admins only - AdminDashboard: paginated table (page size 10/20/50), 300ms debounced search, sortable title/points/created_at columns, edit/delete row actions - EditItemPage: create + edit with client-side validation and a Lexical (0.25) WYSIWYG editor (bold/italic/underline, H1-H6, lists, code blocks, links, undo/redo), optional debounced auto-save - DeleteConfirmation modal with warning icon and explicit "Yes, delete" confirmation - Unit tests (34) and mocked E2E workflow tests (10) All acceptance criteria for milestones/m6-setup-admin-area-prompt.md verified: 108 backend, 87 frontend unit and 29 E2E tests pass.
This commit is contained in:
1 parent
b186d0f797
commit
b440809548
38 files changed
+5415
-50
No files matched your search
+28
-1
@@ -17,6 +17,7 @@ from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy import inspect, text
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from api.v1 import router as api_v1_router
|
||||
@@ -47,10 +48,36 @@ def _error_response(status_code: int, detail: str, code: str, errors=None) -> JS
|
||||
return JSONResponse(status_code=status_code, content=payload)
|
||||
|
||||
|
||||
def _ensure_user_columns() -> None:
|
||||
"""Lightweight schema upgrade for pre-existing databases.
|
||||
|
||||
``Base.metadata.create_all`` creates missing *tables* but never alters
|
||||
existing ones, so databases created before M6 (which added
|
||||
``users.is_admin``) are patched here. Idempotent: inspects the table
|
||||
and only issues ``ALTER TABLE`` for columns that are absent.
|
||||
"""
|
||||
inspector = inspect(engine)
|
||||
if "users" not in inspector.get_table_names():
|
||||
return
|
||||
existing = {column["name"] for column in inspector.get_columns("users")}
|
||||
if "is_admin" not in existing:
|
||||
with engine.begin() as connection:
|
||||
connection.execute(
|
||||
text("ALTER TABLE users ADD COLUMN is_admin BOOLEAN NOT NULL DEFAULT 0")
|
||||
)
|
||||
logger.info("Added users.is_admin column to pre-existing database")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||
"""Create database tables on startup (idempotent for SQLite volumes)."""
|
||||
"""Create database tables (and patch old schemas) on startup.
|
||||
|
||||
Idempotent for SQLite volumes: new tables are created and existing
|
||||
ones only receive the missing-column upgrades (see
|
||||
``_ensure_user_columns``).
|
||||
"""
|
||||
Base.metadata.create_all(bind=engine)
|
||||
_ensure_user_columns()
|
||||
logger.info("Database tables ensured (engine: %s)", engine.url)
|
||||
yield
|
||||
|
||||
|
||||
+43
-7
@@ -76,11 +76,10 @@ def create_token(username: str) -> str:
|
||||
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> str:
|
||||
"""Validate the Bearer token and return the username.
|
||||
def _user_for_token(
|
||||
credentials: HTTPAuthorizationCredentials | None, db: Session
|
||||
) -> User:
|
||||
"""Validate the Bearer token and return the matching :class:`User`.
|
||||
|
||||
Raises 401 when the header is missing, the token is invalid/expired
|
||||
or was issued to a user that no longer exists.
|
||||
@@ -92,6 +91,43 @@ def get_current_user(
|
||||
except jwt.PyJWTError as exc:
|
||||
raise HTTPException(status_code=401, detail="Invalid or expired token") from exc
|
||||
username = payload.get("sub")
|
||||
if not username or db.query(User).filter(User.username == username).first() is None:
|
||||
user = db.query(User).filter(User.username == username).first() if username else None
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="Unknown user")
|
||||
return username
|
||||
return user
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> str:
|
||||
"""Validate the Bearer token and return the username.
|
||||
|
||||
Raises 401 when the header is missing, the token is invalid/expired
|
||||
or was issued to a user that no longer exists.
|
||||
"""
|
||||
return _user_for_token(credentials, db).username
|
||||
|
||||
|
||||
def get_current_user_obj(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""Validate the Bearer token and return the matching :class:`User`."""
|
||||
return _user_for_token(credentials, db)
|
||||
|
||||
|
||||
def get_current_admin(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""Admin-only dependency: validates the token *and* the ``is_admin`` flag.
|
||||
|
||||
A valid JWT alone is not enough — the account must additionally have
|
||||
``User.is_admin`` set. Raises 401 for missing/invalid tokens or unknown
|
||||
users and 403 ("Admin access required") for authenticated non-admins.
|
||||
"""
|
||||
user = _user_for_token(credentials, db)
|
||||
if not user.is_admin:
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
return user
|
||||
Reference in new issue
Block a user