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
+95
View File
@@ -244,6 +244,101 @@ def require_admin_permission():
return admin_checker
def compute_effective_permissions(current_user, db: Session) -> list:
"""Return the current user's effective permissions as "resource:action" strings.
is_admin gets every permission in the catalog; otherwise the union of all
permissions granted by any of the user's assigned roles (most-permissive-wins).
"""
from models.role import Permission, role_permissions, user_roles
if current_user.is_admin:
rows = db.query(Permission.resource, Permission.action).all()
else:
rows = (
db.query(Permission.resource, Permission.action)
.join(role_permissions, role_permissions.c.permission_id == Permission.id)
.join(user_roles, user_roles.c.role_id == role_permissions.c.role_id)
.filter(user_roles.c.user_id == current_user.id)
.distinct()
.all()
)
return [f"{resource}:{action}" for resource, action in rows]
def link_system_role(user, db: Session) -> None:
"""Link a newly-created user to the system Role matching their legacy
`role` value, mirroring the one-time migration backfill so new users
start with the same baseline permissions as already-migrated ones.
No-op if the matching system role doesn't exist or is already linked.
Caller is responsible for commit/refresh.
"""
from models.role import Role
role = db.query(Role).filter(Role.name == user.role.value, Role.is_system == True).first()
if role and role not in user.roles:
user.roles.append(role)
def user_has_permission(current_user, resource: str, action: str, db: Session) -> bool:
"""Most-permissive-wins check across all of current_user's assigned roles.
is_admin is a universal bypass and never needs a role/permission row.
"""
if current_user.is_admin:
return True
from models.role import Permission, role_permissions, user_roles
exists = (
db.query(Permission.id)
.join(role_permissions, role_permissions.c.permission_id == Permission.id)
.join(user_roles, user_roles.c.role_id == role_permissions.c.role_id)
.filter(
user_roles.c.user_id == current_user.id,
Permission.resource == resource,
Permission.action == action,
)
.first()
)
return exists is not None
def require_permission(resource: str, action: str):
"""Dependency factory requiring the current user to hold resource:action
via any assigned role (or be an admin). Usage: Depends(require_permission('shot', 'create'))
"""
def permission_checker(
token_data: dict = Depends(get_current_user_from_token),
db: Session = Depends(lambda: None)
):
from database import get_db
# Get database session if not provided
if db is None:
db_gen = get_db()
db = next(db_gen)
try:
current_user = _get_user_from_db(db, token_data["user_id"])
if not user_has_permission(current_user, resource, action, db):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Missing permission: {resource}:{action}"
)
return current_user
finally:
db.close()
else:
current_user = _get_user_from_db(db, token_data["user_id"])
if not user_has_permission(current_user, resource, action, db):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Missing permission: {resource}:{action}"
)
return current_user
return permission_checker
def create_role_dependency(required_roles: list):
"""Create a dependency that requires specific user roles with proper DB injection."""
def role_checker(