feat: add role/permission system with tests support

- Add Role model with 17 default permissions
- Add init_wizard to create admin/guest roles on first startup
- Protect admin role from modification/deletion via API
- Fix MilestoneCreate schema (project_id optional)
- Fix delete role to clean up role_permissions first
- Add check_project_role RBAC function
This commit is contained in:
2026-03-15 12:25:59 +00:00
parent fee2320cee
commit 61e3349ca4
5 changed files with 172 additions and 18 deletions

View File

@@ -56,17 +56,43 @@ def check_permission(db: Session, user_id: int, project_id: int, permission: str
)
# Keep old function for backward compatibility (deprecated)
def check_project_role(db: Session, user_id: int, project_id: int, min_role: str = "viewer"):
"""Legacy function - maps old role names to new permission system."""
# Map old roles to permissions
role_to_perm = {
"admin": "project.edit",
"mgr": "milestone.create",
"dev": "issue.create",
"ops": "issue.view",
"viewer": "project.view",
}
def check_project_role(db: Session, user_id: int, project_id: int, min_role: str = "member"):
"""Check if user has at least the specified role in a project."""
# Check if user is global admin
user = db.query(models.User).filter(models.User.id == user_id).first()
if user and user.is_admin:
return True
perm = role_to_perm.get(min_role, "project.view")
check_permission(db, user_id, project_id, perm)
# Get user's role in project
member = db.query(models.ProjectMember).filter(
models.ProjectMember.user_id == user_id,
models.ProjectMember.project_id == project_id,
).first()
if not member or not member.role_id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"You are not a member of this project"
)
role = db.query(Role).filter(Role.id == member.role_id).first()
if not role:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Role not found"
)
# Role hierarchy: admin > member > guest
role_hierarchy = {"admin": 3, "member": 2, "guest": 1}
user_role_level = role_hierarchy.get(role.name, 0)
required_level = role_hierarchy.get(min_role, 0)
if user_role_level < required_level:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Role '{min_role}' or higher required. Your role: {role.name}"
)
return True

View File

@@ -54,6 +54,8 @@ def create_milestone(project_id: int, milestone: schemas.MilestoneCreate, db: Se
milestone_code = f"{project_code}:{next_num:05x}"
data = milestone.model_dump()
# Remove project_id from data if present (it's already in the URL path)
data.pop('project_id', None)
# Handle JSON fields
if data.get("depend_on_milestones"):
data["depend_on_milestones"] = json.dumps(data["depend_on_milestones"])

View File

@@ -26,8 +26,8 @@ class PermissionResponse(BaseModel):
class RoleResponse(BaseModel):
id: int
name: str
description: str | None
is_global: bool
description: str | None = None
is_global: bool | None = None
permission_ids: List[int] = []
class Config:
@@ -37,8 +37,8 @@ class RoleResponse(BaseModel):
class RoleDetailResponse(BaseModel):
id: int
name: str
description: str | None
is_global: bool
description: str | None = None
is_global: bool | None = None
permissions: List[PermissionResponse] = []
class Config:
@@ -141,6 +141,10 @@ def update_role(role_id: int, role: RoleUpdate, db: Session = Depends(get_db), c
if not db_role:
raise HTTPException(status_code=404, detail="Role not found")
# Prevent modifying the admin role
if db_role.name == "admin":
raise HTTPException(status_code=403, detail="Cannot modify the admin role")
for key, value in role.model_dump(exclude_unset=True).items():
setattr(db_role, key, value)
db.commit()
@@ -166,10 +170,17 @@ def delete_role(role_id: int, db: Session = Depends(get_db), current_user: model
if not db_role:
raise HTTPException(status_code=404, detail="Role not found")
# Prevent deleting the admin or guest role
if db_role.name in ("admin", "guest"):
raise HTTPException(status_code=403, detail=f"Cannot delete the '{db_role.name}' role")
member_count = db.query(models.ProjectMember).filter(models.ProjectMember.role_id == role_id).count()
if member_count > 0:
raise HTTPException(status_code=400, detail="Role is in use by members")
# Delete role permissions first
db.query(RolePermission).filter(RolePermission.role_id == role_id).delete()
db.delete(db_role)
db.commit()
return None
@@ -185,6 +196,10 @@ def assign_permissions(role_id: int, perm_assign: PermissionAssign, db: Session
if not role:
raise HTTPException(status_code=404, detail="Role not found")
# Prevent modifying permissions of the admin role
if role.name == "admin":
raise HTTPException(status_code=403, detail="Cannot modify permissions of the admin role")
db.query(RolePermission).filter(RolePermission.role_id == role_id).delete()
for perm_id in perm_assign.permission_ids: