Add multi-role permission system with a Role Management admin page

Users can now hold multiple roles, each with its own editable set of
create/edit/delete-style permissions across assets, shots, tasks, task
assignment, review approve/retake, submissions, uploads, and notes
(including internal vs. client note visibility). The 4 existing roles
(coordinator/director/artist/developer) are migrated into the new system
as system roles, seeded to reproduce today's actual behavior exactly;
admins can create custom roles (e.g. "Reviewer", "Outsourcing") via the
new Role Management page and assign multiple roles to a user via a new
"Manage Roles" action on the Team page.

Backend:
- New Role/Permission models and role_permissions/user_roles tables,
  plus a one-off, idempotent seed/backfill migration script.
- New require_permission()/user_has_permission() dependency, wired into
  the actual mutation endpoints across shots/assets/tasks/reviews,
  always preserving existing ownership- and self-service-based access
  (e.g. artists editing their own task status, own notes, own uploads,
  own submissions) as an unconditional fallback alongside the new
  permission checks - nothing that worked before now requires a role.
- New endpoints: PUT/DELETE on task submissions (wires up soft-deletion
  columns that existed on the model but were never exposed), plus full
  role CRUD and per-user role assignment.
- Along the way: fixed newly-created users not being linked to their
  matching system role (silently leaving them with zero permissions),
  and unified an inconsistency between the single vs. bulk task status
  endpoints that allowed different roles to bulk-update status.

Frontend:
- Role Management page with a grouped, human-readable permission editor
  (icons, plain-language action labels, per-resource select-all, live
  selected count) replacing an earlier dense matrix prototype.
- hasPermission() added to the existing usePermission() composable
  without touching its current isAdmin/isCoordinatorOrAdmin consumers.
- Note composer gets an Internal/Client toggle; submissions gain inline
  edit/delete actions gated the same ownership-or-permission way as notes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-18 20:41:17 +08:00
parent 976ec40b52
commit db2c414c1a
33 changed files with 1697 additions and 137 deletions
+51 -5
View File
@@ -1,5 +1,5 @@
from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from sqlalchemy.orm import Session
from sqlalchemy.orm import Session, selectinload
from typing import List, Optional
from passlib.context import CryptContext
from pathlib import Path
@@ -12,7 +12,9 @@ from database import get_db
from models.user import User, UserRole
from models.project import ProjectMember
from models.task import Task
from models.role import Role
from schemas.user import UserResponse, UserApproval, UserRoleUpdate, UserUpdate, UserAdminUpdate, UserAdminCreate, UserAdminEdit, UserPasswordReset, UserPasswordChange
from schemas.role import UserRolesUpdate
from utils.auth import get_current_user_from_token, _get_user_from_db, require_admin_permission
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
@@ -98,7 +100,7 @@ async def update_user_role(
user.role = role_data.role
db.commit()
return {
"message": f"User {user.email} role updated to {role_data.role}",
"user_id": user.id,
@@ -106,6 +108,42 @@ async def update_user_role(
}
@router.put("/{user_id}/roles", response_model=dict)
async def update_user_roles(
user_id: int,
roles_data: UserRolesUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(require_admin_permission_with_db)
):
"""Replace a user's full set of assigned custom roles (Admin permission required).
This is the new multi-role system and is independent of the legacy
single `role` field updated by PUT /{user_id}/role above.
"""
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
roles = db.query(Role).filter(Role.id.in_(roles_data.role_ids)).all()
if len(roles) != len(set(roles_data.role_ids)):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="One or more role_ids are invalid"
)
user.roles = roles
db.commit()
return {
"message": f"User {user.email} roles updated",
"user_id": user.id,
"role_ids": [role.id for role in user.roles]
}
@router.put("/{user_id}/admin", response_model=dict)
async def update_user_admin_permission(
user_id: int,
@@ -149,7 +187,7 @@ async def list_users(
current_user: User = Depends(require_admin_or_coordinator)
):
"""List all users (Admin and Coordinator only)."""
users = db.query(User).offset(skip).limit(limit).all()
users = db.query(User).options(selectinload(User.roles)).offset(skip).limit(limit).all()
return users
@@ -169,7 +207,10 @@ async def get_current_user_profile(
db: Session = Depends(get_db)
):
"""Get current user's profile."""
from utils.auth import compute_effective_permissions
current_user = _get_user_from_db(db, token_data["user_id"])
current_user.permissions = compute_effective_permissions(current_user, db)
return current_user
@@ -214,7 +255,7 @@ async def get_user(
current_user: User = Depends(require_admin_or_coordinator)
):
"""Get user by ID (Admin and Coordinator only)."""
user = db.query(User).filter(User.id == user_id).first()
user = db.query(User).options(selectinload(User.roles)).filter(User.id == user_id).first()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
@@ -255,7 +296,12 @@ async def admin_create_user(
db.add(new_user)
db.commit()
db.refresh(new_user)
from utils.auth import link_system_role
link_system_role(new_user, db)
db.commit()
db.refresh(new_user)
return new_user