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:
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user