Phase 6: Admin portal

Adds is_site_admin-gated site administration: user management (list,
deactivate/reactivate, reset password, promote/demote), room management
(list all rooms including private ones, archive/unarchive, force-transfer
ownership), and an audit log of every admin action.

Backend: User.is_active (deactivation) and Room.is_archived (archive) are
new columns; AdminAuditLog is a new table matching ARCHITECTURE.md's
admin_audit_log design, written to in the same transaction as every
mutating admin action. require_site_admin (dependencies.py) gates all
/api/admin/* routes. get_current_user now rechecks is_active on every
request, so deactivating a user kills their already-open session
immediately, not just future logins. An admin can't deactivate or demote
their own account (the one self-lockout guard included). Archived rooms
drop out of the open-room browse list but stay readable for existing
members.

Frontend: new /admin route (AdminRoute guard, redirects non-admins to
/rooms) with a tabbed Users / Rooms / Audit log / Settings page, plus an
"Admin" link in the account menu for site admins.

Bot/integration management and system settings -- both listed in the
original issue -- are intentionally not here: bot management has nothing
to manage until Phase 7 builds the actual bot data model, and there's no
settings storage or concrete setting to configure yet. Settings has an
empty placeholder tab; bot management is deferred entirely to Phase 7.
Confirmed this scope cut with the repo owner before implementing.

New tests/test_admin.py (14 tests, full suite now 58/58) covers every
admin endpoint's permission gate, the self-action guards, deactivation's
immediate effect on an already-open session, and that every mutating
action produces exactly one audit log row.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-14 07:37:29 -06:00
co-authored by Claude Sonnet 5
parent 0b995ef75f
commit 4aa8ef89c5
22 changed files with 1394 additions and 10 deletions
+6 -1
View File
@@ -18,7 +18,7 @@ async def get_current_user(
raise HTTPException(status_code=401, detail="Not authenticated")
user = await db.get(User, uuid.UUID(user_id))
if user is None:
if user is None or not user.is_active:
request.session.clear()
raise HTTPException(status_code=401, detail="Not authenticated")
@@ -46,3 +46,8 @@ async def require_room_role(
if _ROLE_RANK[membership.role] < _ROLE_RANK[minimum]:
raise HTTPException(status_code=403, detail="Insufficient room role")
return membership
def require_site_admin(user: User) -> None:
if not user.is_site_admin:
raise HTTPException(status_code=403, detail="Site admin required")
+2 -1
View File
@@ -8,7 +8,7 @@ from redis.asyncio import Redis
from starlette.middleware.sessions import SessionMiddleware
from app.config import settings
from app.routers import auth, health, invites, push, rooms
from app.routers import admin, auth, health, invites, push, rooms
from app.ws.broadcaster import RoomBroadcaster
from app.ws.chat import router as ws_router
from app.ws.connection_manager import ConnectionManager
@@ -49,6 +49,7 @@ def create_app() -> FastAPI:
app.include_router(rooms.router)
app.include_router(invites.router)
app.include_router(push.router)
app.include_router(admin.router)
app.include_router(ws_router)
return app
+2
View File
@@ -1,3 +1,4 @@
from app.models.admin_audit_log import AdminAuditLog
from app.models.base import Base
from app.models.invite import InviteStatus, RoomInvite
from app.models.membership import RoomMembership, RoomRole
@@ -16,4 +17,5 @@ __all__ = [
"RoomInvite",
"InviteStatus",
"PushSubscription",
"AdminAuditLog",
]
+24
View File
@@ -0,0 +1,24 @@
import uuid
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, String, func
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class AdminAuditLog(Base):
__tablename__ = "admin_audit_log"
id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
actor_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id"), index=True, nullable=False)
action: Mapped[str] = mapped_column(String(100), nullable=False)
target_type: Mapped[str] = mapped_column(String(50), nullable=False)
target_id: Mapped[uuid.UUID] = mapped_column(nullable=False)
metadata_: Mapped[dict | None] = mapped_column("metadata", JSONB)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False, index=True
)
actor = relationship("User")
+1
View File
@@ -14,6 +14,7 @@ class Room(Base):
name: Mapped[str] = mapped_column(String(100), unique=True, index=True, nullable=False)
description: Mapped[str | None] = mapped_column(Text)
is_private: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
is_archived: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
owner_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id"), nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
+1
View File
@@ -16,6 +16,7 @@ class User(Base):
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
is_bot: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
is_site_admin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
+225
View File
@@ -0,0 +1,225 @@
import uuid
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.dependencies import get_current_user, require_site_admin
from app.models import Room, RoomMembership, User
from app.schemas.admin import (
AdminRoomRead,
AdminUserRead,
AuditLogEntryRead,
ResetPasswordRequest,
TransferOwnershipRequest,
)
from app.services.admin_service import (
CannotActOnSelfError,
RoomNotFoundError,
TargetNotRoomMemberError,
UserNotFoundError,
list_audit_log,
list_rooms_admin,
list_users,
reset_user_password,
set_room_archived,
set_user_active,
set_user_site_admin,
transfer_ownership_admin,
)
router = APIRouter(prefix="/api/admin", tags=["admin"])
@router.get("/users", response_model=list[AdminUserRead])
async def list_users_endpoint(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
require_site_admin(current_user)
return await list_users(db)
@router.post("/users/{user_id}/deactivate", response_model=AdminUserRead)
async def deactivate_user_endpoint(
user_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
require_site_admin(current_user)
try:
return await set_user_active(db, current_user, user_id, active=False)
except CannotActOnSelfError:
raise HTTPException(status_code=400, detail="Cannot deactivate your own account")
except UserNotFoundError:
raise HTTPException(status_code=404, detail="User not found")
@router.post("/users/{user_id}/reactivate", response_model=AdminUserRead)
async def reactivate_user_endpoint(
user_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
require_site_admin(current_user)
try:
return await set_user_active(db, current_user, user_id, active=True)
except CannotActOnSelfError:
raise HTTPException(status_code=400, detail="Cannot reactivate your own account")
except UserNotFoundError:
raise HTTPException(status_code=404, detail="User not found")
@router.post("/users/{user_id}/reset-password", status_code=204)
async def reset_user_password_endpoint(
user_id: uuid.UUID,
data: ResetPasswordRequest,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
require_site_admin(current_user)
try:
await reset_user_password(db, current_user, user_id, data.new_password)
except UserNotFoundError:
raise HTTPException(status_code=404, detail="User not found")
@router.post("/users/{user_id}/promote", response_model=AdminUserRead)
async def promote_user_endpoint(
user_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
require_site_admin(current_user)
try:
return await set_user_site_admin(db, current_user, user_id, is_admin=True)
except CannotActOnSelfError:
raise HTTPException(status_code=400, detail="Cannot promote your own account")
except UserNotFoundError:
raise HTTPException(status_code=404, detail="User not found")
@router.post("/users/{user_id}/demote", response_model=AdminUserRead)
async def demote_user_endpoint(
user_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
require_site_admin(current_user)
try:
return await set_user_site_admin(db, current_user, user_id, is_admin=False)
except CannotActOnSelfError:
raise HTTPException(status_code=400, detail="Cannot demote your own account")
except UserNotFoundError:
raise HTTPException(status_code=404, detail="User not found")
@router.get("/rooms", response_model=list[AdminRoomRead])
async def list_rooms_endpoint(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
require_site_admin(current_user)
rooms = await list_rooms_admin(db)
return [
AdminRoomRead(
id=room.id,
name=room.name,
description=room.description,
is_private=room.is_private,
is_archived=room.is_archived,
owner_id=room.owner_id,
created_at=room.created_at,
member_count=member_count,
)
for room, member_count in rooms
]
@router.post("/rooms/{room_id}/archive", response_model=AdminRoomRead)
async def archive_room_endpoint(
room_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
require_site_admin(current_user)
try:
room = await set_room_archived(db, current_user, room_id, archived=True)
except RoomNotFoundError:
raise HTTPException(status_code=404, detail="Room not found")
return await _to_admin_room_read(db, room)
@router.post("/rooms/{room_id}/unarchive", response_model=AdminRoomRead)
async def unarchive_room_endpoint(
room_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
require_site_admin(current_user)
try:
room = await set_room_archived(db, current_user, room_id, archived=False)
except RoomNotFoundError:
raise HTTPException(status_code=404, detail="Room not found")
return await _to_admin_room_read(db, room)
@router.post("/rooms/{room_id}/transfer-ownership", response_model=AdminRoomRead)
async def transfer_ownership_endpoint(
room_id: uuid.UUID,
data: TransferOwnershipRequest,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
require_site_admin(current_user)
try:
room = await transfer_ownership_admin(db, current_user, room_id, data.new_owner_id)
except RoomNotFoundError:
raise HTTPException(status_code=404, detail="Room not found")
except TargetNotRoomMemberError:
raise HTTPException(
status_code=400, detail="New owner must already be a member of the room"
)
return await _to_admin_room_read(db, room)
async def _to_admin_room_read(db: AsyncSession, room: Room) -> AdminRoomRead:
result = await db.execute(
select(func.count()).select_from(RoomMembership).where(RoomMembership.room_id == room.id)
)
member_count = result.scalar_one()
return AdminRoomRead(
id=room.id,
name=room.name,
description=room.description,
is_private=room.is_private,
is_archived=room.is_archived,
owner_id=room.owner_id,
created_at=room.created_at,
member_count=member_count,
)
@router.get("/audit-log", response_model=list[AuditLogEntryRead])
async def list_audit_log_endpoint(
limit: int = Query(default=50, ge=1, le=200),
offset: int = Query(default=0, ge=0),
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
require_site_admin(current_user)
entries = await list_audit_log(db, limit=limit, offset=offset)
return [
AuditLogEntryRead(
id=e.id,
actor_id=e.actor_id,
actor_username=e.actor.username,
action=e.action,
target_type=e.target_type,
target_id=e.target_id,
metadata=e.metadata_,
created_at=e.created_at,
)
for e in entries
]
+7 -1
View File
@@ -6,7 +6,11 @@ from app.dependencies import get_current_user
from app.models import User
from app.schemas.auth import LoginRequest
from app.schemas.user import UserRead
from app.services.auth_service import InvalidCredentialsError, authenticate_user
from app.services.auth_service import (
AccountDeactivatedError,
InvalidCredentialsError,
authenticate_user,
)
# No POST /register here: this is an invite-only site. Accounts are created
# by an operator via `python -m app.cli create-user` (see app/cli.py), not
@@ -25,6 +29,8 @@ async def login(
)
except InvalidCredentialsError:
raise HTTPException(status_code=401, detail="Invalid username/email or password")
except AccountDeactivatedError:
raise HTTPException(status_code=401, detail="Account is deactivated")
request.session["user_id"] = str(user.id)
return user
+48
View File
@@ -0,0 +1,48 @@
import uuid
from datetime import datetime
from pydantic import BaseModel, ConfigDict, EmailStr, Field
class AdminUserRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
username: str
email: EmailStr
is_bot: bool
is_site_admin: bool
is_active: bool
created_at: datetime
class AdminRoomRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
name: str
description: str | None
is_private: bool
is_archived: bool
owner_id: uuid.UUID
created_at: datetime
member_count: int
class AuditLogEntryRead(BaseModel):
id: uuid.UUID
actor_id: uuid.UUID
actor_username: str
action: str
target_type: str
target_id: uuid.UUID
metadata: dict | None
created_at: datetime
class ResetPasswordRequest(BaseModel):
new_password: str = Field(min_length=8, max_length=200)
class TransferOwnershipRequest(BaseModel):
new_owner_id: uuid.UUID
+171
View File
@@ -0,0 +1,171 @@
import uuid
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.models import AdminAuditLog, Room, RoomMembership, RoomRole, User
from app.security import hash_password
class UserNotFoundError(Exception):
pass
class RoomNotFoundError(Exception):
pass
class CannotActOnSelfError(Exception):
pass
class TargetNotRoomMemberError(Exception):
pass
async def _get_user(db: AsyncSession, user_id: uuid.UUID) -> User:
user = await db.get(User, user_id)
if user is None:
raise UserNotFoundError()
return user
async def _get_room(db: AsyncSession, room_id: uuid.UUID) -> Room:
room = await db.get(Room, room_id)
if room is None:
raise RoomNotFoundError()
return room
async def _get_membership(
db: AsyncSession, room_id: uuid.UUID, user_id: uuid.UUID
) -> RoomMembership:
result = await db.execute(
select(RoomMembership).where(
RoomMembership.room_id == room_id, RoomMembership.user_id == user_id
)
)
membership = result.scalar_one_or_none()
if membership is None:
raise TargetNotRoomMemberError()
return membership
def _log(
db: AsyncSession,
actor: User,
action: str,
target_type: str,
target_id: uuid.UUID,
metadata: dict | None = None,
) -> None:
db.add(
AdminAuditLog(
actor_id=actor.id,
action=action,
target_type=target_type,
target_id=target_id,
metadata_=metadata,
)
)
async def list_users(db: AsyncSession) -> list[User]:
result = await db.execute(select(User).order_by(User.created_at))
return list(result.scalars().all())
async def set_user_active(
db: AsyncSession, actor: User, target_user_id: uuid.UUID, active: bool
) -> User:
if target_user_id == actor.id:
raise CannotActOnSelfError()
user = await _get_user(db, target_user_id)
user.is_active = active
_log(db, actor, "user.activate" if active else "user.deactivate", "user", user.id)
await db.commit()
await db.refresh(user)
return user
async def reset_user_password(
db: AsyncSession, actor: User, target_user_id: uuid.UUID, new_password: str
) -> None:
user = await _get_user(db, target_user_id)
user.password_hash = hash_password(new_password)
_log(db, actor, "user.reset_password", "user", user.id)
await db.commit()
async def set_user_site_admin(
db: AsyncSession, actor: User, target_user_id: uuid.UUID, is_admin: bool
) -> User:
if target_user_id == actor.id:
raise CannotActOnSelfError()
user = await _get_user(db, target_user_id)
user.is_site_admin = is_admin
_log(db, actor, "user.promote" if is_admin else "user.demote", "user", user.id)
await db.commit()
await db.refresh(user)
return user
async def list_rooms_admin(db: AsyncSession) -> list[tuple[Room, int]]:
result = await db.execute(
select(Room, func.count(RoomMembership.user_id))
.outerjoin(RoomMembership, RoomMembership.room_id == Room.id)
.group_by(Room.id)
.order_by(Room.created_at)
)
return [(room, count) for room, count in result.all()]
async def set_room_archived(
db: AsyncSession, actor: User, room_id: uuid.UUID, archived: bool
) -> Room:
room = await _get_room(db, room_id)
room.is_archived = archived
_log(db, actor, "room.archive" if archived else "room.unarchive", "room", room.id)
await db.commit()
await db.refresh(room)
return room
async def transfer_ownership_admin(
db: AsyncSession, actor: User, room_id: uuid.UUID, new_owner_id: uuid.UUID
) -> Room:
room = await _get_room(db, room_id)
# Same invariant as the member-initiated room_service.transfer_ownership
# (new owner must already be a member) -- this is the admin override for
# the "acting user must currently be the owner" gate, not for that one.
new_owner_membership = await _get_membership(db, room_id, new_owner_id)
current_owner_membership = await _get_membership(db, room_id, room.owner_id)
new_owner_membership.role = RoomRole.owner
current_owner_membership.role = RoomRole.admin
room.owner_id = new_owner_id
_log(
db,
actor,
"room.transfer_ownership",
"room",
room.id,
{"new_owner_id": str(new_owner_id)},
)
await db.commit()
await db.refresh(room)
return room
async def list_audit_log(
db: AsyncSession, limit: int = 50, offset: int = 0
) -> list[AdminAuditLog]:
result = await db.execute(
select(AdminAuditLog)
.options(selectinload(AdminAuditLog.actor))
.order_by(AdminAuditLog.created_at.desc())
.limit(limit)
.offset(offset)
)
return list(result.scalars().all())
+6
View File
@@ -15,6 +15,10 @@ class InvalidCredentialsError(Exception):
pass
class AccountDeactivatedError(Exception):
pass
async def register_user(db: AsyncSession, data: UserCreate) -> User:
user = User(
username=data.username,
@@ -43,4 +47,6 @@ async def authenticate_user(
user = result.scalar_one_or_none()
if user is None or not verify_password(password, user.password_hash):
raise InvalidCredentialsError()
if not user.is_active:
raise AccountDeactivatedError()
return user
+1 -1
View File
@@ -60,7 +60,7 @@ async def create_room(db: AsyncSession, owner_id: uuid.UUID, data: RoomCreate) -
async def list_open_rooms(db: AsyncSession, user_id: uuid.UUID) -> list[tuple[Room, bool]]:
result = await db.execute(
select(Room)
.where(Room.is_private.is_(False))
.where(Room.is_private.is_(False), Room.is_archived.is_(False))
.options(selectinload(Room.memberships))
.order_by(Room.created_at)
)